Files
linkspin/public/assets/links.js
T

123 lines
17 KiB
JavaScript

// LinkSpin Links workspace (Control Room). Rotator API + postbacks + share kit. Uses the shared shell (cr-shell.js).
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null;
CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '<button class="btn pri" id="newBtn" type="button">+ New spin</button>' });
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
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' };
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 || [];
const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0);
CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days');
renderList();
const want = SEL != null ? SEL : (Number(location.hash.slice(1)) || null);
if (want != null && ROT.find(x => x.id === want)) return select(want, true);
if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; }
else select(ROT[0].id, true);
}
function renderList() {
const q = FILTER.trim().toLowerCase();
const rows = ROT.filter(x => !q || x.name.toLowerCase().includes(q) || x.code.includes(q));
$('listCount').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's');
$('items').innerHTML = rows.length ? rows.map(x => { const h = health(x); return '<div class="item' + (x.id === SEL ? ' on' : '') + '" data-id="' + x.id + '" role="button" tabindex="0">'
+ '<div><div class="nm">' + esc(x.name) + (h.cls !== 'ok' ? ' <span class="tag ' + h.cls + '">' + h.t + '</span>' : '') + (x.conversions ? ' <span class="tag ok">' + x.conversions + ' conv</span>' : '') + '</div><div class="cd">' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '</div></div>'
+ '<div class="rt"><span class="n">' + fmt(clicks7(x)) + '</span><span class="muted" style="font-size:10px">7 d</span></div></div>'; }).join('')
: '<div class="empty"><div class="muted">' + (ROT.length ? 'No link matches that filter.' : 'No links yet.') + '</div></div>';
$('items').querySelectorAll('.item').forEach(el => { const go = () => select(Number(el.dataset.id)); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
}
async function select(id, quiet) {
SEL = id; const r = ROT.find(x => x.id === id); if (!r) return;
if (String(location.hash.slice(1)) !== String(id)) history.replaceState(null, '', '#' + id);
$('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus');
$('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id));
$('dName').textContent = r.name; $('dUrl').textContent = linkUrl(r);
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 || '';
$('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(r.bots || 0)], ['Conversions', fmt(r.conversions || 0)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]]
.map(([k, v], i) => '<div class="tile' + (i === 0 ? ' hi' : '') + '"><span class="k">' + k + '</span><span class="v">' + v + '</span></div>').join('');
renderDest(r); renderShare(r);
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>'
+ '<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('')
: '<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';
$('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); } }));
}
function renderShare(r) {
const url = linkUrl(r);
const kit = [
['Short post', 'One link, every page I promote, in turn. Take a look: ' + url],
['Email or Telegram line', 'Here is the link I use for everything: ' + url + ' (it always sends you to the right page).'],
['Tracker-ready link', url + '?clickid={clickid}&s1={source} (replace the braces with your network\'s macros)'],
['Sub-id split test', url + '?s1=email-A and ' + url + '?s1=email-B (each shows up under Sources)'],
];
$('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)));
}
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>';
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 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(' · ') : '';
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => d.n));
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('dayBars').innerHTML = days.length ? days.map(d => '<i style="height:' + Math.round(d.n / dmax * 100) + '%" title="' + d.day + ' · ' + d.n + '"></i>').join('') : '';
$('dayAxis').innerHTML = days.length ? '<span>' + days[0].day + '</span><span>' + days[days.length - 1].day + '</span>' : '<span class="muted">no clicks recorded yet</span>';
}
// postbacks (account level)
async function loadPb() {
try { PB = await CR.get('/api/my/postbacks'); } catch (e) { return; }
$('pbInUrl').textContent = PB.inboundUrl + '?key=' + PB.key + '&lsid={lsid}&event=sale&value=0.00';
const rows = PB.postbacks || [];
$('pbRows').innerHTML = rows.length ? rows.map(p => '<div class="rw"><div><b>' + esc(p.name) + '</b><br><span class="mono muted" style="font-size:11px">' + p.method + ' · sent ' + fmt(p.sent) + (p.lastAt ? ' · last ' + esc(String(p.lastStatus)) : '') + '</span></div><div class="mono" style="font-size:11px;overflow-wrap:anywhere">' + esc(p.url) + '</div><div>' + p.events.map(e => '<span class="tag dim">' + e + '</span>').join(' ') + '</div><div>' + (p.enabled ? '<span class="tag ok">ON</span>' : '<span class="tag warn">OFF' + (p.fails >= 10 ? ' · failed 10x' : '') + '</span>') + '</div><div style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap"><button class="btn sm" type="button" data-test="' + p.id + '">Test</button><button class="btn sm" type="button" data-tog="' + p.id + '">' + (p.enabled ? 'Off' : 'On') + '</button><button class="btn sm" type="button" data-edit="' + p.id + '">Edit</button><button class="btn sm danger" type="button" data-del="' + p.id + '" aria-label="Remove">&times;</button></div></div>').join('')
: '<div class="rw"><span class="muted">No postbacks yet. Add your tracker\'s postback URL and pick which events fire it.</span></div>';
const log = PB.log || []; $('pbFoot').textContent = log.length ? 'last delivery: ' + new Date(log[0].ts).toLocaleString() + ' · ' + log[0].name + ' · ' + log[0].event + ' · ' + (log[0].ok ? 'ok ' + log[0].status : 'failed ' + (log[0].status || log[0].note)) + ' · ' + log.filter(l => l.ok).length + ' of the last ' + log.length + ' succeeded' : 'no deliveries yet';
$('pbRows').querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', async () => { b.disabled = true; try { const r = await api('/api/my/postbacks/' + b.dataset.test, { test: true }); toast(r.ok ? 'Test delivered, HTTP ' + r.status : 'Test failed: ' + (r.status || r.note), !r.ok); } catch (e) { toast(e.message, true); } b.disabled = false; loadPb(); }));
$('pbRows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const p = rows.find(x => x.id === b.dataset.tog); try { await api('/api/my/postbacks/' + p.id, { enabled: !p.enabled }); loadPb(); } catch (e) { toast(e.message, true); } }));
$('pbRows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this postback?', ok: 'Remove', danger: true })) return; try { await api('/api/my/postbacks/' + b.dataset.del, { remove: true }); loadPb(); } catch (e) { toast(e.message, true); } }));
$('pbRows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => pbForm(rows.find(x => x.id === b.dataset.edit))));
}
async function pbForm(p) {
const ev = (PB && PB.events) || ['join', 'wallet', 'purchase', 'external'];
const v = await dialog({ title: p ? 'Edit postback' : 'New postback', text: 'Your tracker or network gives you a postback URL with macros. Paste it; LinkSpin fills the click id it saw on the link.',
fields: [{ k: 'name', label: 'Name', value: p ? p.name : '', placeholder: 'BeMob', max: 60 }, { k: 'url', label: 'URL template', value: p ? p.url : '', placeholder: 'https://tracker.example/postback?cid={clickid}&payout={payout}&txid={txid}', mono: true, type: 'url' }, { k: 'events', label: 'Events, comma separated: ' + ev.join(', '), value: p ? p.events.join(',') : 'join,purchase' }, { k: 'method', label: 'Method, GET or POST', value: p ? p.method : 'GET', max: 4 }], ok: p ? 'Save' : 'Create' });
if (!v) return;
try { if (p) await api('/api/my/postbacks/' + p.id, v); else await api('/api/my/postbacks', v); toast(p ? 'Saved' : 'Postback added'); loadPb(); } catch (e) { toast(e.message, true); }
}
async function newSpin() {
const v = await dialog({ title: 'New spin', text: 'Name it for you, not for visitors. You add the pages next.', fields: [{ k: 'name', label: 'Name', placeholder: 'IAP main invite', max: 80 }, { k: 'url', label: 'First page to send people to (optional)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' });
if (!v || !v.name.trim()) return;
try { const r = await api('/api/my/rotations', { name: v.name }); const id = r.rotation.id; if (v.url && v.url.trim()) await api('/api/my/rotations/' + id + '/dest', { url: v.url.trim(), weight: 10 }); SEL = id; toast('Link created'); await load(true); } catch (e) { toast(e.message, true); }
}
$('newBtn').addEventListener('click', newSpin); $('newBtn2').addEventListener('click', newSpin);
$('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); });
$('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) CR.copy(linkUrl(r)); });
$('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); });
$('renameBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: r.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/rotations/' + r.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } });
$('pauseBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { paused: !r.paused }); toast(r.paused ? 'Live again' : 'Paused: visitors go to the fallback'); load(true); } catch (e) { toast(e.message, true); } });
$('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; history.replaceState(null, '', location.pathname); toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
$('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; }); }));
$('pbNew').addEventListener('click', () => pbForm(null));
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
CR.requireSession(() => { load(); loadPb(); setInterval(() => { if (!document.hidden) load(true); }, 60000); });
})();