diff --git a/board.js b/board.js index b25d440..7721ce9 100644 --- a/board.js +++ b/board.js @@ -23,9 +23,12 @@ function eligible(now) { return chain.spots().filter(s => s.kind !== 3 && now - s.boughtAt < c.spotDays * DAY && store.views(s.id).total < c.viewsOwed); } -// Hook: member LinkSpin Banner Spins fill empty slots before house ads (SPEC "house fill"). Returns -// [{ img, link, title }]. Not wired in v1: needs a LinkSpin endpoint listing members' active 468x60 spins. -function memberSpins() { return []; } +// Member LinkSpin Banner Spins fill empty slots before house ads (SPEC "house fill", built 2026-11-13). server.js refreshes the +// list every 10 minutes through LinkSpin's /api/partner/bl/spins (one active 468x60 spin per Downline Banners member); each board +// gets them in a fresh random order. [{ img, link, title }] +let SPINS = []; +function setMemberSpins(list) { SPINS = Array.isArray(list) ? list : []; } +function memberSpins() { const a = SPINS.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } function spotTile(s) { const c = cfgMod.get(); const cr = creative(s); const v = store.views(s.id); @@ -78,4 +81,4 @@ function target(ref) { return { link: creative(s).link, spotId: s.id }; } -module.exports = { creative, eligible, pick, newestOf, newest, frameable, target, memberSpins, houseFor }; +module.exports = { creative, eligible, pick, newestOf, newest, frameable, target, memberSpins, setMemberSpins, houseFor }; diff --git a/dlbnas.js b/dlbnas.js new file mode 100644 index 0000000..15d02ca --- /dev/null +++ b/dlbnas.js @@ -0,0 +1,68 @@ +// Network Ad Space for Downline Banners (SPEC "delivery": 300 guaranteed views per spot within 30 days, then Network Ad Space +// finishes it; Marty 2026-11-13 "proceed"). Same direct-write pattern as InstantAdPay's nas.js (NAS is Marty's own EvolutionScript +// site; its MySQL is the API): INSERT payments, then sponsorads with approved=1, and read `remaining` back. +// - house: one standing 468x60 banner for downlinebanners.com, a modest allowance (HOUSE_IMPS), topped up when it runs low, +// so the board gets traffic without crowding InstantAdPay members' paid ads out of NAS. +// - spots: a spot past its 30 days with fewer than 300 views gets its own banner placed in NAS for exactly the views still owed; +// what NAS serves counts toward the spot's 300 (served(spotId)). +// State in dlb-nas.json (a MySQL document through docstore). Inert unless NAS_DB_* are set. +'use strict'; +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const cfgMod = require('./config'); + +const HOUSE_IMPS = 25000, HOUSE_LOW = 3000, CATID_CRYPTO = 5; +let pool = null, S = null, R = null; +const on = () => !!(process.env.NAS_DB_HOST && process.env.NAS_DB_USER && process.env.NAS_DB_PASSWORD && process.env.NAS_DB_NAME); +const FILE = () => path.join(cfgMod.get().dataDir, 'dlb-nas.json'); +function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = {}; } S.spots = S.spots || {}; return S; } +function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) { console.error('dlbnas save', e.message); } } +function q(sql, args) { + if (!pool) pool = require('mysql2/promise').createPool({ host: process.env.NAS_DB_HOST, user: process.env.NAS_DB_USER, password: process.env.NAS_DB_PASSWORD, + database: process.env.NAS_DB_NAME, port: Number(process.env.NAS_DB_PORT || 3306), connectionLimit: 2, connectTimeout: 10000 }); + return pool.query(sql, args).then(r => r[0]); +} +async function push({ img, link, assigned, title, ref }) { + const token = 'dlb_' + crypto.randomBytes(8).toString('hex'); const now = new Date(); const edate = new Date(now.getTime() + 60 * 86400000); + const pay = await q('INSERT INTO payments (Username, Amount, Currency_code, status, Date, pay_address) VALUES (?,?,?,1,?,?)', [token, 0, 'DLB', now, ref]); + try { + const ad = await q(`INSERT INTO sponsorads (Username, Subject, Body, WebsiteURL, assigned, remaining, hits, approved, Date, adtype, Name, Email, PaymentDetails, EDate, sp, width, height, BannerURL, pid, ref_by, catid) + VALUES (?,?,NULL,?,?,?,0,1,?,1,?,?,?,?,'',?,?,?,2,0,?)`, + [token, title, link, assigned, assigned, now, 'Downline Banners', 'ads@downlinebanners.com', ref, edate, '468', '60', img, CATID_CRYPTO]); + return { id: ad.insertId, assigned }; + } catch (e) { try { await q('DELETE FROM payments WHERE ID=?', [pay.insertId]); } catch (x) {} throw e; } +} +async function served(id) { const r = await q('SELECT assigned, remaining FROM sponsorads WHERE ID=?', [Number(id)]); if (!r.length) return null; return Math.max(0, Math.min(r[0].assigned, r[0].assigned - r[0].remaining)); } + +async function tick() { + if (!on() || !R) return; + const c = cfgMod.get(); const s = load(); const site = 'https://' + c.site; + try { + // house banner: keep one running, refill when low + if (s.house) { const sv = await served(s.house.id); if (sv != null) s.house.served = sv; } + if (!s.house || (s.house.assigned - (s.house.served || 0)) < HOUSE_LOW) { + const ad = await push({ img: site + '/art/house-strip-nas.png', link: site + '/?src=nas', assigned: HOUSE_IMPS, title: 'Downline Banners: $5 banner spots, paid on-chain', ref: 'dlb_house' }); + s.houseHistory = (s.houseHistory || []).concat(s.house ? [s.house] : []); s.house = Object.assign(ad, { served: 0, at: Date.now() }); + console.log('dlbnas: house banner placed', ad.id, ad.assigned); + } + // spots past 30 days that still owe views + for (const sp of R.spots()) { + const id = String(sp.id); const owed = c.viewsOwed - R.views(sp.id); + const rec = s.spots[id]; + if (rec) { const sv = await served(rec.id); if (sv != null) rec.served = sv; continue; } + if (sp.kind === 3 || owed <= 0 || Date.now() - sp.boughtAt < c.spotDays * 86400000) continue; + const cr = R.creative(sp); let img = cr.img || ''; if (img.startsWith('/')) img = site + img; + if (!/^https:\/\/.+\.(png|jpe?g|gif)(\?.*)?$/i.test(img) && !/\/i\/[a-z0-9]+\.gif/i.test(img)) img = site + '/art/house-strip-nas.png'; + const ad = await push({ img, link: site + '/go/' + id, assigned: owed, title: 'Spot #' + id, ref: 'dlb_spot:' + id }); + s.spots[id] = Object.assign(ad, { served: 0, at: Date.now() }); console.log('dlbnas: spot', id, 'finishing', owed, 'views in NAS, ad', ad.id); + } + s.lastOk = Date.now(); delete s.lastErr; + } catch (e) { s.lastErr = String(e.message).slice(0, 200); console.error('dlbnas', e.message); } + save(); +} +// views NAS delivered for a spot (counted toward its 300) +function spotServed(id) { const r = load().spots[String(id)]; return r ? (r.served || 0) : 0; } +function init(deps) { R = deps; if (!on()) { console.log('dlbnas: off (no NAS_DB_*)'); return; } load(); setTimeout(() => tick().catch(() => {}), 30000); const t = setInterval(() => tick().catch(() => {}), 6 * 3600000); t.unref && t.unref(); } +function view() { const s = load(); return { on: on(), house: s.house || null, spots: s.spots, lastOk: s.lastOk || null, lastErr: s.lastErr || null }; } +module.exports = { init, tick, spotServed, view, on }; diff --git a/public/art/house-strip-nas.png b/public/art/house-strip-nas.png new file mode 100644 index 0000000..ccaeecd Binary files /dev/null and b/public/art/house-strip-nas.png differ diff --git a/server.js b/server.js index fed3ec3..b1611e6 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,7 @@ const board = require('./board'); const safety = require('./safety'); const keeper = require('./keeper'); const { iface } = require('./abi'); +const dlbnas = require('./dlbnas'); // Network Ad Space: standing house banner + finishing spots still owed views after 30 days (2026-11-13) const refuelspots = require('./refuelspots'); // refuel spots: $50+ Monthly Refuels earn a spot, engine wallet pays (2026-11-13) const tgproof = require('./tgproof'); // payment proof in the Telegram payments topic, one message per spot sale (2026-11-13) const hubreport = require('./hubreport'); // network hub, shadow mode: members reported by wallet (2026-11-13), off unless HUB_ENABLED @@ -189,7 +190,7 @@ const boardTokens = new Map(); // ---- dashboard data ---- function spotView(s) { - const v = store.views(s.id); const m = store.spotMeta(s.id) || {}; const cr = board.creative(s); const now = Date.now(); + const v0 = store.views(s.id); const nasV = dlbnas.spotServed(s.id); const v = Object.assign({}, v0, { total: v0.total + nasV, nas: nasV }); const m = store.spotMeta(s.id) || {}; const cr = board.creative(s); const now = Date.now(); const left = Math.max(0, C.spotDays - Math.floor((now - s.boughtAt) / 86400000)); return { id: s.id, kind: s.kind, boughtAt: s.boughtAt, tx: s.tx, valueWei: s.valueWei, views: v.total, gateViews: v.gate, owed: C.viewsOwed, clicks: store.clicks(s.id), daysLeft: left, delivering: s.kind !== 3 && left > 0 && v.total < C.viewsOwed, @@ -447,7 +448,7 @@ const server = http.createServer(async (req, res) => { // -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned. if (p === '/api/admin/status' && req.method === 'GET') { const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' }); - return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), refuelSpots: refuelspots.view() }); + return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() }); } if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' }); @@ -470,6 +471,18 @@ const server = http.createServer(async (req, res) => { hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); keeper.init(); + dlbnas.init({ spots: () => chain.spots(), views: id => store.views(id).total, creative: board.creative }); + // members' LinkSpin Banner Spins for empty board slots: one active 468x60 spin per member, refreshed every 10 minutes + const refreshSpins = async () => { + const out = []; + for (const m of chain.allMembers()) { + const r = await lsSpins({ wallet: m.address }).catch(() => null); + const sp = r && r.account && (r.spins || []).find(x => !x.paused && x.banners > 0); + if (sp) out.push({ img: 'https://rubav.com/i/' + sp.code + '.gif', link: 'https://rubav.com/c/' + sp.code + '?placement=board&s1=fill', title: (r.username ? '@' + r.username + ': ' : '') + sp.name }); + } + board.setMemberSpins(out); + }; + setTimeout(() => refreshSpins().catch(() => {}), 20000); setInterval(() => refreshSpins().catch(() => {}), 10 * 60000).unref(); server.listen(C.port, () => console.log('Downline Banners on :' + C.port + ' chain ' + C.chainName + ' (' + C.chainId + ') contract ' + (C.contract || '(not set)') + ' store: ' + (docstore.isOn() ? 'MySQL documents' : 'volume JSON'))); })().catch(e => { console.error('start failed:', e.message); process.exit(1); }); process.on('SIGTERM', () => { store.flush(); process.exit(0); });