diff --git a/chatbot.js b/chatbot.js index b906394..da28965 100644 --- a/chatbot.js +++ b/chatbot.js @@ -42,7 +42,7 @@ const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)| const CANNED = [ { id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'], re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i, - a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen. Buy here: https://linkspin.app/credits. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' }, + a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in the Ads screen (with a Load into my Banner Spin button); they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen. Buy here: https://linkspin.app/credits. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' }, { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a ticket?'], tags: ['support', 'help', 'ticket', 'contact'], re: SUPPORT_RE, handoff: true, a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' }, @@ -151,7 +151,7 @@ function seeds() { // ---- facts for the AI fallback ---- // the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24) let REFUEL_ON = () => false; -function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; } +function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; } const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.'; function systemPrompt(kbBlock) { return `You are the assistant on LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property. diff --git a/kit.js b/kit.js new file mode 100644 index 0000000..48cf73a --- /dev/null +++ b/kit.js @@ -0,0 +1,218 @@ +// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and +// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes +// LinkSpin, never mixed). +// +// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600 +// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + /.). +// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's). +// +// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit +// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } } +// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits. +// streak month 3+ at unlock an animated GIF version of each banner size +// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration +// +// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner +// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/. and served +// publicly at /kitimg/. (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of +// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { spawn } = require('child_process'); + +const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] }; +const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630']; +// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px) +const LAYOUT = { + '728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] }, + '468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] }, + '300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] }, + '160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] }, + '1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] }, +}; +let X = {}, DIR = null, OUT = null, FILE = null, SALT = null; +const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/; +const norm = e => String(e || '').trim().toLowerCase(); + +function init(opts) { + X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json'); + try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {} + const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {} + if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } } +} +const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap'; +const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay'; +function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } } +function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); } +const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7); +const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' }); + +// ---- admin: the kits --------------------------------------------------------------------------------- +function baseFile(month, size) { + const d = path.join(DIR, month); + for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; } + return null; +} +function kitView(k) { + const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; }); + return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 }; +} +function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); } +function saveKit(b) { + const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' }; + const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() }; + if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80); + if (b.released != null) { + if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' }; + k.released = !!b.released; + } + if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; } + k.updated = Date.now(); s.kits[month] = k; save(s); + return { ok: true, kit: kitView(k) }; +} +const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' }; +function uploadBase(month, size, buf, mime) { + if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' }; + if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' }; + const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()]; + if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' }; + const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true }); + for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} } + fs.writeFileSync(path.join(d, size + '.' + ext), buf); + const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s); + return { ok: true, kit: kitView(s.kits[month]) }; +} +// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs) +function usePlaceholder(month) { + const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-'; + const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'], + '1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] }; + const done = []; + for (const size of ORDER) { + const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue; + const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size); + } + return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) }; +} + +// ---- the renderer --------------------------------------------------------------------------------------- +let FONT; +function font() { + if (FONT !== undefined) return FONT; + FONT = process.env.BADGE_FONT || null; if (FONT) return FONT; + const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) return f; } return null; }; + for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } } + if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf'; + return FONT; +} +const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%'); +function run(args, cwd) { + return new Promise(resolve => { + const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd }); + const out = []; let err = ''; + p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; }); + p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err })); + }); +} +// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box +async function renderStill(base, size, name, link, stage, outFile) { + const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font(); + if (!F) return { error: 'No font for the renderer.' }; + const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules + const qrFile = outFile + '.qr.png'; + await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } }); + const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F; + const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H)); + const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]); + const showName = stage !== 0, showQr = stage === undefined || stage === 2; + const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]']; + let last = 'b'; + if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; } + if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; } + const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1']; + if (/\.jpg$/.test(outFile)) args.push('-q:v', '3'); + args.push(path.resolve(outFile)); + const r = await run(args, winPath ? path.dirname(F) : undefined); + try { fs.unlinkSync(qrFile); } catch (e) {} + if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) }; + return { ok: true }; +} +// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping +async function renderGif(base, size, name, link, outFile) { + const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png'); + for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; } + const list = outFile + '.txt'; + fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n"); + const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]); + for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} } + if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) }; + return { ok: true }; +} +const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28); +function indexFile() { return path.join(OUT, 'index.json'); } +function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); } +// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes } +async function personal(who, month, size, variant) { + const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' }; + const v = Math.round(fs.statSync(base).mtimeMs); + const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png'; + const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link); + const out = path.join(OUT, h + '.' + ext); + if (!fs.existsSync(out)) { + const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext); + let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; } + if (r.error) return r; + try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} } + noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() }); + } + const [w, hh] = SIZES[size]; + return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext }; +} +// public serving: only files already rendered for an entitled member +function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; } + +// ---- the member ------------------------------------------------------------------------------------------ +async function whoOf(email) { + const w = await X.linkFor(norm(email)); if (!w || !w.link) return null; + return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link }; +} +async function myKits(email) { + const ent = (await X.entitled(norm(email)).catch(() => null)) || null; + if (!ent || !ent.on) return { on: false }; + const s = load(); const months = ent.months || {}; + const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month + const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => { + const streakAt = months[k.month] || 0; const unlocked = streakAt > 0; + return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 }); + }); + // the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet + const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m); + if (customMonths.length) { + const e = norm(email); const have = s.credits[e] || {}; let changed = false; + for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; } + if (changed) { s.credits[e] = have; save(s); } + } + const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used })); + const cur = nowMonth; const who = await whoOf(email).catch(() => null); + return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur], + kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null, + nextRefuel: ent.nextRefuel || null }; +} +async function renderFor(email, month, size, variant) { + const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' }; + const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' }; + if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' }; + if (!SIZES[size]) return { error: 'No such size.' }; + if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' }; + const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' }; + return personal(who, month, size, variant === 'gif' ? 'gif' : 'still'); +} +async function preview(month, size, username, variant) { + const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname'); + const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link }; + return personal(who, month, size, variant === 'gif' ? 'gif' : 'still'); +} + +module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font }; diff --git a/kitspin.js b/kitspin.js new file mode 100644 index 0000000..19c7f9d --- /dev/null +++ b/kitspin.js @@ -0,0 +1,38 @@ +// "Load into my Banner Spin" for the Refuel Kit (2026-10-24). Each Banner Spin size in an unlocked kit goes into one of the +// member's Banner Spins of that size that has room, or into a new Banner Spin when the member's tier allows one more. +// The banner is the member's own personalized file (copied into uploads like a normal Banner Spin upload, so health checks, +// moderation and Member content treat it the same), labelled "Refuel Kit ", the target their own link. +// Loading the same kit twice does not add it twice. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +async function load(d) { // { kit, bannerspin, content, uploadsDir, email, month, variant, sizes } + const { kit, bannerspin, email, month } = d; + const mk = await kit.myKits(email); const k = mk.on && mk.kits.find(x => x.month === month); + if (!k) return { error: 'No such kit.' }; + if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' }; + const t = await bannerspin.tierFor(email); if (!t.ok) return { error: t.reason, status: 403 }; + const want = Array.isArray(d.sizes) && d.sizes.length ? d.sizes.map(String) : k.sizes.filter(x => x.ready).map(x => x.size); + const label = 'Refuel Kit ' + month; const results = []; + for (const size of want.filter(z => bannerspin.SIZES[z] && k.sizes.some(x => x.size === z && x.ready))) { + const mine = await bannerspin.list(email); + const has = mine.find(x => x.size === size && x.banners.some(b => b.label === label)); + if (has) { results.push({ size, spinId: has.id, spin: has.name, already: true }); continue; } + const r = await kit.renderFor(email, month, size, d.variant === 'gif' && k.gif ? 'gif' : 'still'); + if (r.error) { results.push({ size, error: r.error }); continue; } + if (r.bytes > bannerspin.MAX_BYTES) { results.push({ size, error: 'The ' + size + ' file is over 150 KB, so Banner Spin cannot take it. Use the still version.' }); continue; } + let spin = mine.find(x => x.size === size && x.banners.length < t.banners && !x.adminOff), created = false; + if (!spin) { const c = await bannerspin.create(email, { name: 'Refuel Kit ' + size, size, fallback: mk.link || '' }); if (c.error) { results.push({ size, error: c.error }); continue; } spin = c.spin; created = true; } + const name = crypto.randomBytes(12).toString('hex') + '.' + r.ext; + fs.writeFileSync(path.join(d.uploadsDir, name), fs.readFileSync(r.file)); + const mime = { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[r.ext]; + try { if (d.content) d.content.noteUpload(name, email, r.bytes, mime, ''); } catch (e) {} + bannerspin.noteImage(email, name, r.w, r.h, r.bytes, mime); + const add = await bannerspin.addBanner(email, spin.id, { image: '/uploads/' + name, target: mk.link, label }); + results.push(add.error ? { size, error: add.error } : { size, spinId: spin.id, spin: spin.name, created }); + } + return { ok: true, results }; +} +module.exports = { load }; diff --git a/public/admin.html b/public/admin.html index ce340ac..c20e20b 100644 --- a/public/admin.html +++ b/public/admin.html @@ -480,6 +480,17 @@