diff --git a/public/assets/cr-shell.js b/public/assets/cr-shell.js index 60515d0..eeb910d 100644 --- a/public/assets/cr-shell.js +++ b/public/assets/cr-shell.js @@ -16,7 +16,7 @@ window.CR = (function () { ]; // screens not built yet fall back to the classic dashboard pane so nothing is a dead end const FALLBACK = { pages: '/my#promo', zones: '/my#campaigns', team: '/my#line', wallet: '/my#wallet' }; - const BUILT = new Set(['links', 'pages', 'reports', 'team', 'wallet']); + const BUILT = new Set(['links', 'pages', 'zones', 'reports', 'team', 'wallet']); let ME = null, toastT; function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); } async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; } diff --git a/public/assets/zones-screen.js b/public/assets/zones-screen.js new file mode 100644 index 0000000..68a83dd --- /dev/null +++ b/public/assets/zones-screen.js @@ -0,0 +1,30 @@ +// LinkSpin Zones screen: list, create, embed tag, live check, quality grade. +(function () { + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog; + let Z = [], SEL = null, HOST = location.host, SIZES = [], RATE = {}; + CR.mount({ active: 'zones', title: 'Zones', sub: 'loading', actions: '' }); + const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + ' h ago'; return Math.floor(d / 86400e3) + ' d ago'; }; + const tag = z => ''; + async function load() { + let r; try { r = await CR.get('/api/my/zones'); } catch (e) { CR.sub('could not load'); return; } + Z = r.zones || []; HOST = r.host || HOST; SIZES = r.sizes || []; RATE = r.rates || {}; + const t = Z.reduce((a, z) => { a.v += z.views30; a.ok += z.viewable30; a.k += z.clicks30; a.c += z.credits; return a; }, { v: 0, ok: 0, k: 0, c: 0 }); + CR.sub(Z.length + ' zone' + (Z.length === 1 ? '' : 's') + ' · ' + fmt(t.v) + ' views in 30 days'); + $('tiles').innerHTML = [['Views served, 30 d', fmt(t.v)], ['Viewable', t.v ? Math.round(t.ok / t.v * 100) + '%' : '0%'], ['Clicks out', fmt(t.k)], ['Credits earned', fmt(t.c)]].map(([k, v], i) => '
' + k + '' + v + '
').join(''); + $('rateNote').textContent = 'You earn 1 credit per ' + (RATE.viewsPerCredit || 5) + ' viewable views of a LinkSpin campaign and 1 per ' + (RATE.nasViewsPerCredit || 10) + ' viewable views of a network ad, capped at ' + (RATE.capPerVisitorDay || 50) + ' credited views per visitor per zone per day. House banners are not paid. Bots never count.'; + const q = g => '' + [1, 2, 3, 4, 5].map(i => '').join('') + '' + (g || ''); + $('rows').innerHTML = Z.length ? Z.map(z => '
' + esc(z.name) + '' + (z.site ? ' · ' + esc(z.site) + '' : '') + '
' + z.id + ' · ' + (z.lastSeen ? 'last view ' + ago(z.lastSeen) : 'no views yet') + (z.views30 ? ' · mix: ' + fmt(z.campaign30 || 0) + ' LinkSpin / ' + fmt(z.nas30 || 0) + ' network / ' + fmt(z.house30 || 0) + ' house' : '') + '
' + z.size + '' + fmt(z.views30) + '' + (z.viewablePct == null ? '·' : z.viewablePct + '%') + '' + fmt(z.credits) + '' + (z.grade ? q(z.grade) : 'no data') + (!z.active ? ' OFF' : '') + '
').join('') + : '
No zones yet. Add one, paste the tag on your site, and the banner is live.
'; + $('foot').textContent = 'viewable = at least half the banner on screen for one second, reported by the tag · quality: A 60%+ viewable, B 40%+, C below · network frequency: one credited view per visitor per zone per day up to the cap'; + $('rows').querySelectorAll('[data-tag]').forEach(b => b.addEventListener('click', () => showTag(b.dataset.tag))); + $('rows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const z = Z.find(x => x.id === b.dataset.tog); try { await api('/api/my/zones/' + z.id, { active: !z.active }); load(); } catch (e) { toast(e.message, true); } })); + $('rows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this zone?', text: 'The tag on your site stops showing ads. Credits already earned stay.', ok: 'Remove', danger: true })) return; try { await api('/api/my/zones/' + b.dataset.del, { remove: true }); SEL = null; $('tagPanel').hidden = true; load(); } catch (e) { toast(e.message, true); } })); + if (SEL && Z.find(z => z.id === SEL)) showTag(SEL); + } + function showTag(id) { const z = Z.find(x => x.id === id); if (!z) return; SEL = id; $('tagPanel').hidden = false; $('tagTitle').textContent = 'Embed tag · ' + z.name; $('tagCode').textContent = tag(z); $('tagNote').textContent = 'Paste it where the banner should appear (' + z.size + '). It sizes itself and never loads more than one ad.'; $('tagCopy').onclick = () => CR.copy(tag(z)); $('tagCheck').onclick = async () => { await load(); const zz = Z.find(x => x.id === id); toast(zz && zz.lastSeen && Date.now() - zz.lastSeen < 3600e3 ? 'Live: last view ' + ago(zz.lastSeen) : 'No view in the last hour. Is the tag on a page people open?', !(zz && zz.lastSeen && Date.now() - zz.lastSeen < 3600e3)); }; } + $('newBtn').addEventListener('click', async () => { + const v = await dialog({ title: 'Add a zone', text: 'One zone per spot on a page. Pick the size that fits the space.', fields: [{ k: 'name', label: 'Name', placeholder: 'My blog · sidebar', max: 60 }, { k: 'site', label: 'Site it lives on', placeholder: 'myblog.com', max: 80 }, { k: 'size', label: 'Size: ' + (SIZES.join(', ') || '728x90, 468x60, 300x250, 160x600, 320x50'), value: '728x90', mono: true }], ok: 'Create' }); + if (!v) return; try { const r = await api('/api/my/zones', v); SEL = r.zone.id; toast('Zone created. Copy the tag.'); load(); } catch (e) { toast(e.message, true); } + }); + CR.requireSession(load); +})(); diff --git a/public/banners/linkspin-160x600.svg b/public/banners/linkspin-160x600.svg new file mode 100644 index 0000000..de74203 --- /dev/null +++ b/public/banners/linkspin-160x600.svg @@ -0,0 +1 @@ +LinkSpinOne link.Every pageyou promote.Get your link \ No newline at end of file diff --git a/public/banners/linkspin-300x250.svg b/public/banners/linkspin-300x250.svg new file mode 100644 index 0000000..2f2b44d --- /dev/null +++ b/public/banners/linkspin-300x250.svg @@ -0,0 +1 @@ +LinkSpinOne link. Every page you promote, in turn.Weights, hours, health checks, real numbers.Get your link \ No newline at end of file diff --git a/public/banners/linkspin-320x50.svg b/public/banners/linkspin-320x50.svg new file mode 100644 index 0000000..89dc49f --- /dev/null +++ b/public/banners/linkspin-320x50.svg @@ -0,0 +1 @@ +LinkSpinGet your link \ No newline at end of file diff --git a/public/banners/linkspin-468x60.svg b/public/banners/linkspin-468x60.svg new file mode 100644 index 0000000..38e9652 --- /dev/null +++ b/public/banners/linkspin-468x60.svg @@ -0,0 +1 @@ +LinkSpinOne link. Every page you promote, in turn.Get your link \ No newline at end of file diff --git a/public/banners/linkspin-728x90.svg b/public/banners/linkspin-728x90.svg new file mode 100644 index 0000000..52c5bae --- /dev/null +++ b/public/banners/linkspin-728x90.svg @@ -0,0 +1 @@ +LinkSpinOne link. Every page you promote, in turn.Get your link \ No newline at end of file diff --git a/public/z.js b/public/z.js new file mode 100644 index 0000000..956d01b --- /dev/null +++ b/public/z.js @@ -0,0 +1,32 @@ +/* LinkSpin zone tag. One line on your site: + Renders a banner from the LinkSpin ad pool in place, reports one viewable impression (half the banner on screen for + one second), nothing else. No cookies, no personal data. */ +(function () { + var s = document.currentScript; if (!s) return; + var zone = s.getAttribute('data-zone') || ''; if (!/^ls-[a-f0-9]{6}$/.test(zone)) return; + var base = (s.src || '').replace(/\/z\.js.*$/, ''); + var box = document.createElement('div'); box.style.cssText = 'display:inline-block;line-height:0;max-width:100%'; s.parentNode.insertBefore(box, s); + function load() { + var r = new XMLHttpRequest(); r.open('GET', base + '/api/zone/serve?z=' + encodeURIComponent(zone), true); + r.onload = function () { + if (r.status !== 200) return; var ad; try { ad = JSON.parse(r.responseText).ad; } catch (e) { return; } if (!ad || (!ad.img && !ad.frame)) return; + var el; + if (ad.frame) { // a network ad: rendered inside our own frame so its script lands in a page we control + el = document.createElement('iframe'); el.src = base + ad.frame; el.width = ad.w; el.height = ad.h; el.title = 'Advertisement'; el.setAttribute('scrolling', 'no'); el.setAttribute('frameborder', '0'); el.style.cssText = 'max-width:100%;border:0;display:block;overflow:hidden'; el.sandbox = 'allow-scripts allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation'; + box.innerHTML = ''; box.appendChild(el); + } else { + var a = document.createElement('a'); a.href = base + ad.click; a.target = '_blank'; a.rel = 'noopener nofollow sponsored'; + var img = document.createElement('img'); img.src = /^https?:/.test(ad.img) ? ad.img : base + ad.img; img.alt = ad.alt || 'Advertisement'; img.width = ad.w; img.height = ad.h; img.style.cssText = 'max-width:100%;height:auto;border:0;display:block'; + a.appendChild(img); box.innerHTML = ''; box.appendChild(a); el = img; + } + var sent = false, timer = null; + function ping() { if (sent) return; sent = true; try { navigator.sendBeacon(base + '/api/zone/seen?i=' + ad.imp); } catch (e) { var q = new XMLHttpRequest(); q.open('GET', base + '/api/zone/seen?i=' + ad.imp, true); q.send(); } } + if ('IntersectionObserver' in window) { + var io = new IntersectionObserver(function (es) { es.forEach(function (e) { if (e.intersectionRatio >= 0.5) { if (!timer) timer = setTimeout(function () { ping(); io.disconnect(); }, 1000); } else if (timer) { clearTimeout(timer); timer = null; } }); }, { threshold: [0, 0.5, 1] }); + io.observe(el); + } else { setTimeout(ping, 1500); } + }; + r.send(); + } + load(); +})(); diff --git a/public/zones.html b/public/zones.html new file mode 100644 index 0000000..26c1ea5 --- /dev/null +++ b/public/zones.html @@ -0,0 +1,34 @@ + + + + + + +Zones · LinkSpin + + + + + +
+
+
+
+
ZoneSizeViewsViewableCreditsQuality
+
+ +

What runs here

Three tiers, in order: a LinkSpin member campaign (the same pool the ad viewer serves), then a Network Ad Space ad for 728x90 and 468x60 zones, then a LinkSpin house banner. Your site carries the whole network, not just LinkSpin.
+
+
+
+
+ + + + diff --git a/server.js b/server.js index 71f96cc..b9896a8 100644 --- a/server.js +++ b/server.js @@ -40,7 +40,8 @@ const registry = require('./registry'); // network registry: who is who ac const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices const rotator = require('./rotator'); const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) -const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/ (2026-09-29) // the rotator: rotations, weighted destinations, /r/ +const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/ (2026-09-29) +const zones = require('./zones'); // ad zones on members' own sites (2026-09-29) // the rotator: rotations, weighted destinations, /r/ const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) @@ -390,6 +391,7 @@ async function boot() { const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); rotator.init({ dataDir: DATA_DIR, geo, ownHosts }); postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator }); + zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST }); pages.init({ dataDir: DATA_DIR, ownHosts, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } }); snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } }); setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); @@ -875,6 +877,19 @@ const server = http.createServer(async (req, res) => { if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); } + // -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these. + if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} } + if (p === '/api/zone/serve' && req.method === 'GET') { + const ad = await zones.serve(u.searchParams.get('z'), req, viewerGeo(req)); + res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*' }); return res.end(JSON.stringify({ ad })); + } + if (p === '/z/nas' && req.method === 'GET') { // the frame a Network Ad Space fallback renders in + const html = zones.nasFrame(String(u.searchParams.get('s') || '')); + if (!html) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html); + } + if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, { 'Access-Control-Allow-Origin': '*' }); return res.end(); } + { const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } } // -- member pages: /p/ on the app host and on every link domain; the lead form and the hit beacon live beside it let pm = /^\/p\/([a-z0-9-]{3,60})$/i.exec(p); if (pm && (req.method === 'GET' || req.method === 'HEAD')) { @@ -1831,6 +1846,19 @@ const server = http.createServer(async (req, res) => { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); const r = await rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' }); } + if (p === '/api/my/zones' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { zones: await zones.list(s.email), host: SITE_HOST, sizes: Object.keys(zones.SIZES), rates: zones.settings() }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/zones' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await zones.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/zones\/(ls-[a-f0-9]{6})$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await zones.update(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); + } if (p === '/api/my/pages' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.')); @@ -2896,6 +2924,7 @@ const server = http.createServer(async (req, res) => { if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29) if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html')); if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html')); + if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html')); if (p === '/team') return sendFile(res, path.join(PUBLIC_DIR, 'team.html')); if (p === '/wallet') return sendFile(res, path.join(PUBLIC_DIR, 'wallet.html')); if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); diff --git a/zones.js b/zones.js new file mode 100644 index 0000000..49f48d0 --- /dev/null +++ b/zones.js @@ -0,0 +1,86 @@ +// LinkSpin Zones (2026-09-29): an ad slot a member puts on their own site with one line of code. It shows the +// engine's member banner campaigns (the same pool the ad viewer serves, so every zone adds real delivery for paid +// campaigns) with a LinkSpin house creative as the fallback, and pays the site owner credits per VIEWABLE +// impression: at least half the banner on screen for one second, reported by the tag, bots excluded, capped per +// visitor per zone per day. Rates are settings, defaults = the ad viewer's own rate (2 credits per 10 views). +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +let DATA_DIR = null, ads = null, siteHost = 'linkspin.app'; +const SIZES = { '728x90': [728, 90], '468x60': [468, 60], '300x250': [300, 250], '160x600': [160, 600], '320x50': [320, 50] }; +const HOUSE = { '728x90': '/banners/linkspin-728x90.svg', '468x60': '/banners/linkspin-468x60.svg', '300x250': '/banners/linkspin-300x250.svg', '160x600': '/banners/linkspin-160x600.svg', '320x50': '/banners/linkspin-320x50.svg' }; +const NAS_SIZES = new Set(['728x90', '468x60']); // the sizes Network Ad Space serves through its showadss.php tag +const NAS_TAG = (w, h) => ''; +const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i; +const J = { db: null, FILE: () => path.join(DATA_DIR, 'zones.json'), + load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, zones: [], imps: [], acc: {} }; } for (const k of ['zones', 'imps']) if (!Array.isArray(this.db[k])) this.db[k] = []; if (!this.db.acc) this.db.acc = {}; }, + save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } }; +function init(opts) { DATA_DIR = opts.dataDir; ads = opts.ads; siteHost = opts.siteHost || siteHost; J.load(); } +const norm = e => String(e || '').trim().toLowerCase(); +const DAY = 86400000; +function settings() { let s = {}; try { s = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'zone-rates.json'), 'utf8')); } catch (e) {} return Object.assign({ viewsPerCredit: 5, nasViewsPerCredit: 10, capPerVisitorDay: 50, houseOn: 1, nasOn: 1 }, s); } +// the document an NAS fallback renders in: our own frame, so the NAS tag's document.write lands in a page we control +function nasFrame(size) { const wh = SIZES[size]; if (!wh || !NAS_SIZES.has(size)) return null; return '' + NAS_TAG(wh[0], wh[1]) + ''; } +function pubZone(z) { + const since30 = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.z === z.id && i.ts >= since30 && !i.bot); + const seen = imps.filter(i => i.ok).length; const clicks = imps.filter(i => i.k).length; const last = J.db.imps.filter(i => i.z === z.id).slice(-1)[0]; + const ratio = imps.length ? seen / imps.length : 0; + return { id: z.id, name: z.name, site: z.site, size: z.size, active: !!z.active, created: z.created, views30: imps.length, viewable30: seen, viewablePct: imps.length ? Math.round(ratio * 100) : null, clicks30: clicks, credits: z.credits || 0, grade: !imps.length ? null : ratio >= 0.6 ? 'A' : ratio >= 0.4 ? 'B' : 'C', lastSeen: last ? last.ts : 0, house30: imps.filter(i => i.house).length, nas30: imps.filter(i => i.nas).length, campaign30: imps.filter(i => i.camp).length }; +} +async function list(owner) { return J.db.zones.filter(z => z.owner === norm(owner)).map(pubZone); } +async function create(owner, body) { + if (J.db.zones.filter(z => z.owner === norm(owner)).length >= 50) return { error: 'Up to 50 zones per account.' }; + const size = SIZES[String(body.size || '')] ? String(body.size) : '728x90'; + const name = String(body.name || '').trim().slice(0, 60) || 'Zone'; const site = String(body.site || '').trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0].slice(0, 80); + const z = { id: 'ls-' + crypto.randomBytes(3).toString('hex'), owner: norm(owner), name, site, size, active: true, created: Date.now(), credits: 0 }; + J.db.zones.push(z); J.save(); return { ok: true, zone: pubZone(z) }; +} +async function update(owner, id, body) { + const z = J.db.zones.find(z => z.id === id && z.owner === norm(owner)); if (!z) return { error: 'No such zone.' }; + if (body.remove) { J.db.zones = J.db.zones.filter(x => x !== z); J.save(); return { ok: true, removed: true }; } + if (body.name != null) z.name = String(body.name).trim().slice(0, 60) || z.name; + if (body.site != null) z.site = String(body.site).trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0].slice(0, 80); + if (body.active != null) z.active = !!body.active; + J.save(); return { ok: true, zone: pubZone(z) }; +} +function tag(z) { return ''; } +// -- serving +function visitorOf(req) { const ua = String(req.headers['user-agent'] || ''); const ip = String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim(); return { v: crypto.createHash('sha256').update(new Date().toISOString().slice(0, 10) + '|' + ip + '|' + ua).digest('hex').slice(0, 16), bot: BOT.test(ua) || !ua }; } +async function serve(zoneId, req, geoOpts) { + const z = J.db.zones.find(z => z.id === String(zoneId)); if (!z || !z.active) return null; + const [w, h] = SIZES[z.size]; const vis = visitorOf(req); const s = settings(); + // waterfall: 1) a LinkSpin member campaign 2) a Network Ad Space ad (NAS serves 728x90 and 468x60) 3) the LinkSpin house banner + let ad = null; if (!vis.bot) { try { ad = await ads.serve('banner', Object.assign({ width: w, height: h, excludeEmail: z.owner }, geoOpts || {})); } catch (e) { ad = null; } } + const nas = !ad && !vis.bot && s.nasOn && NAS_SIZES.has(z.size); + const house = !ad && !nas; + if (house && !s.houseOn) return null; + const imp = { id: crypto.randomBytes(6).toString('hex'), z: z.id, ts: Date.now(), v: vis.v, bot: vis.bot ? 1 : 0, ok: 0, k: 0, house: house ? 1 : 0, nas: nas ? 1 : 0, camp: ad ? ad.id : 0 }; + J.db.imps.push(imp); if (J.db.imps.length > 300000) J.db.imps = J.db.imps.slice(-200000); J.save(); + if (nas) return { imp: imp.id, w, h, kind: 'nas', frame: '/z/nas?s=' + z.size + '&i=' + imp.id, nas: true }; + return { imp: imp.id, w, h, kind: house ? 'house' : 'campaign', img: ad ? (ad.image || ad.imageUrl || ad.src || '') : HOUSE[z.size], alt: ad ? (ad.title || 'Advertisement') : 'LinkSpin: one link, every page you promote', click: '/api/zone/click/' + imp.id, house }; +} +// the tag says the banner was at least half visible for a second: credit the owner (rate-limited per visitor per zone per day) +async function seen(impId, req) { + const imp = J.db.imps.find(i => i.id === String(impId)); if (!imp || imp.ok || imp.bot) return { ok: false }; + if (Date.now() - imp.ts > 10 * 60000) return { ok: false }; + const z = J.db.zones.find(z => z.id === imp.z); if (!z) return { ok: false }; + const s = settings(); const day = new Date().toISOString().slice(0, 10); + const todayByVisitor = J.db.imps.filter(i => i.z === z.id && i.v === imp.v && i.ok && new Date(i.ts).toISOString().slice(0, 10) === day).length; + imp.ok = 1; + if (todayByVisitor < s.capPerVisitorDay && !imp.house) { // house views are not paid: nobody bought them + // LinkSpin campaign views and NAS views accrue on separate meters with their own rates; whole credits go to the owner + const key = z.owner + (imp.nas ? '|nas' : ''); const per = imp.nas ? s.nasViewsPerCredit : s.viewsPerCredit; + J.db.acc[key] = (J.db.acc[key] || 0) + 1; + if (per > 0 && J.db.acc[key] >= per) { const cr = Math.floor(J.db.acc[key] / per); J.db.acc[key] -= cr * per; z.credits = (z.credits || 0) + cr; try { await ads.addEarned(z.owner, cr, { log: { kind: 'earn', note: 'Zone views: ' + z.name + (imp.nas ? ' (network)' : ''), ref: 'zone:' + z.id, rollup: true } }); } catch (e) {} } + } + J.save(); return { ok: true }; +} +async function click(impId) { + const imp = J.db.imps.find(i => i.id === String(impId)); if (!imp) return null; + imp.k = 1; J.save(); + if (imp.house || !imp.camp) return 'https://' + siteHost + '/'; + try { return (await ads.click(imp.camp)) || ('https://' + siteHost + '/'); } catch (e) { return 'https://' + siteHost + '/'; } +} +function totals() { const since = Date.now() - 30 * DAY; const imps = J.db.imps.filter(i => i.ts >= since && !i.bot); return { zones: J.db.zones.length, views30: imps.length, viewable30: imps.filter(i => i.ok).length, clicks30: imps.filter(i => i.k).length, nas30: imps.filter(i => i.nas).length, credits: J.db.zones.reduce((n, z) => n + (z.credits || 0), 0) }; } +module.exports = { init, SIZES, NAS_SIZES, settings, nasFrame, list, create, update, tag, serve, seen, click, totals };