afede88c4a
- GET /api/admin/content?type=&q=&from=&to=&flagged=1&page=&per=&fresh=1 (admin only, read-only): content.js normalizes rows from each module's own adminAll() (new one-pass accessors in pages, rotator, sources, zones, postbacks, audiences, messages.adminBroadcasts, videomaker.adminJobs) plus ads.adminList and accounts.listAll; owner shown as @username, email and member #; created in Central time; totals per type; busiest hosts in the current view - Flags: open member reports on an ad, dead or parked destinations, burned link domains, failing postbacks, admin-paused zones, home-page demo links. No deny list exists yet - Row actions only reuse existing moderation routes (campaign pause/resume, zone pause/resume); "Open member" jumps to the member card; page Preview works for drafts and is never counted (admin allowed on ?preview=1) - Uploads: /uploads files now recorded with their uploader in uploads-index.json; older files get the owner from whatever uses them (campaign creative, profile, wall offer) - Credits > Your purchases: buys made from linked positions are included, labelled "Position N" - Cache tags: admin.css 20261018a, admin.js 20261018b, credits-screen.js 20261018b Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
196 lines
18 KiB
JavaScript
196 lines
18 KiB
JavaScript
// Member content (admin, Marty 2026-10-18): "in the admin view, I need to be able to see all the pages that are created
|
|
// and anything else that's created by a member." One read-only list across every module that stores member-made things:
|
|
// pages, links (rotations + destinations), traffic sources, zones, ad campaigns, postbacks, uploads, profiles (bio, avatar,
|
|
// line banner, wall offers), sponsor broadcasts, hand-made audiences and Video Maker renders. Each module hands over its
|
|
// own records (adminAll and friends); this file only turns them into one row shape, flags what looks wrong, and filters /
|
|
// pages the result for GET /api/admin/content. Moderation stays where it already lives (campaign pause/resume, zone
|
|
// pause/resume); a row only points at those routes.
|
|
// Uploads in /uploads had no owner record before 2026-10-18: the owner is inferred from whatever references the file
|
|
// (a campaign creative, a profile avatar or line banner, a wall offer). New uploads are noted in DATA_DIR/uploads-index.json.
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
let R = null; // { dataDir, uploadsDir, accounts, pages, rotator, sources, zones, ads, postbacks, audiences, messages, videomaker, reports, domains, adminEmail, houseOwner, linkHost(), pagesHost(), siteHost }
|
|
function init(refs) { R = refs; }
|
|
|
|
const TYPES = [
|
|
{ key: 'page', label: 'Pages' }, { key: 'link', label: 'Links' }, { key: 'source', label: 'Sources' }, { key: 'zone', label: 'Zones' },
|
|
{ key: 'ad', label: 'Ads' }, { key: 'postback', label: 'Postbacks' }, { key: 'upload', label: 'Uploads' }, { key: 'profile', label: 'Profiles' },
|
|
{ key: 'message', label: 'Broadcasts' }, { key: 'audience', label: 'Audiences' }, { key: 'video', label: 'Videos' }
|
|
];
|
|
const CT_FMT = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
const ctDay = ts => ts ? CT_FMT.format(new Date(Number(ts))) : '';
|
|
const hostOf = u => { try { return new URL(String(u || '')).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
|
const strip = s => String(s || '').replace(/<style[\s\S]*?<\/style>|<script[\s\S]*?<\/script>/gi, ' ').replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/\s+/g, ' ').trim();
|
|
const urlsIn = s => (String(s || '').match(/https?:\/\/[^\s"'<>)]+/gi) || []).slice(0, 20);
|
|
const UP_RE = /\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))/gi;
|
|
const parse = s => { if (!s) return null; if (typeof s === 'object') return s; try { return JSON.parse(s); } catch (e) { return null; } };
|
|
|
|
// -- upload index (who uploaded which /uploads file), written by server.js handleUpload from 2026-10-18 on
|
|
const IDX = () => path.join(R.dataDir, 'uploads-index.json');
|
|
function readIdx() { try { return JSON.parse(fs.readFileSync(IDX(), 'utf8')) || {}; } catch (e) { return {}; } }
|
|
function noteUpload(name, who, size, type, url) {
|
|
try { const i = readIdx(); i[String(name)] = { who: String(who || '').toLowerCase(), size: Number(size) || 0, type: type || '', url: url || '', ts: Date.now() }; fs.writeFileSync(IDX(), JSON.stringify(i)); } catch (e) {}
|
|
}
|
|
|
|
// -- collect: every row, cached briefly so paging and typing in the search box stay quick
|
|
let cache = null;
|
|
async function collect(fresh) {
|
|
if (!fresh && cache && Date.now() - cache.ts < 15000) return cache.rows;
|
|
const accts = await R.accounts.listAll(1000000);
|
|
const byEmail = {}; for (const a of accts) byEmail[String(a.email || '').toLowerCase()] = a;
|
|
const admin = String(R.adminEmail || '').toLowerCase(), house = String(R.houseOwner || '').toLowerCase();
|
|
const ownerOf = email => {
|
|
const e = String(email || '').toLowerCase();
|
|
if (e.startsWith('demo:')) return { email: '', username: '', memberId: 0, demo: true };
|
|
const a = byEmail[e]; return { email: e, username: a && a.username || '', memberId: a && a.memberId || 0 };
|
|
};
|
|
const burned = h => { try { return !!h && !!R.domains.isBurned(h); } catch (e) { return false; } };
|
|
const linkHost = R.linkHost() || R.siteHost; const pagesHost = R.pagesHost();
|
|
const rows = [];
|
|
const add = r => {
|
|
r.owner = ownerOf(r.ownerEmail); delete r.ownerEmail;
|
|
r.flags = r.flags || []; r.actions = r.actions || []; r.counts = r.counts || {};
|
|
r.hosts = Array.from(new Set((r.hosts || []).filter(Boolean)));
|
|
for (const h of r.hosts) if (burned(h)) r.flags.push({ k: 'burned', t: h + ' is a burned link domain' });
|
|
r.day = ctDay(r.created);
|
|
r.text = [r.type, r.id, r.owner.email, r.owner.username, r.owner.username ? '@' + r.owner.username : '', r.owner.memberId ? '#' + r.owner.memberId : '', r.title, r.url, r.status].concat(r.hosts, r.search || []).join(' ').toLowerCase();
|
|
delete r.search; rows.push(r);
|
|
};
|
|
|
|
// pages
|
|
for (const p of R.pages.adminAll()) add({ type: 'page', id: p.id, ownerEmail: p.owner, title: p.title, created: p.created, updated: p.updated,
|
|
status: p.status === 'published' ? 'live' : 'draft', live: p.status === 'published',
|
|
url: pagesHost ? 'https://' + pagesHost + '/' + p.slug : 'https://' + linkHost + '/p/' + p.slug, open: '/p/' + p.slug + '?preview=1',
|
|
detail: { kind: p.type, slug: p.slug, headline: p.headline, sub: p.sub, ctaUrl: p.ctaUrl, ctaText: p.ctaText, image: p.image, formProvider: p.formProvider, scanUrl: p.scanUrl, body: p.body.slice(0, 280) },
|
|
counts: { views: p.views, uniques: p.uniques, clicks: p.clicks, leads: p.leads }, hosts: [hostOf(p.ctaUrl), hostOf(p.scanUrl)],
|
|
search: [p.slug, p.headline, p.sub, p.body, p.bonus, p.angle, p.ctaUrl, p.scanUrl, p.image] });
|
|
|
|
// links (rotations)
|
|
for (const r of R.rotator.adminAll()) {
|
|
const flags = [];
|
|
const sick = r.destinations.filter(d => d.autoPaused || (d.health && (d.health.state === 'dead' || d.health.state === 'parked')));
|
|
if (sick.length) flags.push({ k: 'health', t: sick.length + ' destination' + (sick.length > 1 ? 's' : '') + ' dead or parked' });
|
|
if (r.demo) flags.push({ k: 'demo', t: 'Home-page demo spin (no account yet)' });
|
|
const live = !r.paused && (r.destinations.some(d => d.active) || !!r.fallback);
|
|
add({ type: 'link', id: String(r.id), ownerEmail: r.owner, title: r.name, created: r.created, status: r.paused ? 'paused' : live ? 'live' : 'empty', live,
|
|
url: 'https://' + linkHost + '/r/' + r.code, open: null,
|
|
detail: { code: r.code, fallback: r.fallback, dayparted: r.dayparted, sourceId: r.sourceId, expires: r.expires, destinations: r.destinations.map(d => ({ url: d.url, label: d.label, weight: d.weight, active: d.active, autoPaused: !!d.autoPaused, health: d.health ? d.health.state : '' })) },
|
|
counts: { clicks7: r.hits7, clicks: r.hits, bots: r.bots, conversions: r.conversions }, hosts: r.destinations.map(d => hostOf(d.url)).concat(hostOf(r.fallback)), flags,
|
|
search: [r.code].concat(r.destinations.map(d => d.url + ' ' + (d.label || '')), r.fallback) });
|
|
}
|
|
|
|
// traffic sources
|
|
for (const s of R.sources.adminAll()) add({ type: 'source', id: s.id, ownerEmail: s.owner, title: s.name, created: s.created, status: s.enabled ? 'live' : 'off', live: !!s.enabled, url: s.site ? 'https://' + s.site : '', open: null,
|
|
detail: { template: s.template, site: s.site, costModel: s.costModel, postbackUrl: s.postbackUrl, method: s.method, events: s.events, params: (s.params || []).length, lastStatus: s.lastStatus },
|
|
counts: { sent: s.sent, fails: s.fails }, hosts: [hostOf(s.postbackUrl)], search: [s.template, s.site, s.postbackUrl] });
|
|
|
|
// zones (moderation: the existing admin pause / resume)
|
|
for (const z of R.zones.adminAll()) add({ type: 'zone', id: z.id, ownerEmail: z.owner, title: z.name, created: z.created, status: z.paused ? 'paused' : !z.active ? 'off' : z.status, live: z.active && !z.paused,
|
|
url: 'https://' + z.site, open: 'https://' + z.site,
|
|
detail: { site: z.site, size: z.size, tier: z.tier, statusLabel: z.statusLabel, note: z.note, lastSeen: z.lastSeen },
|
|
counts: { views30: z.views30, viewablePct: z.viewablePct, clicks30: z.clicks30, offsite30: z.offsite30, credits: z.credits }, hosts: [z.site],
|
|
flags: z.paused ? [{ k: 'paused', t: 'Paused by admin' + (z.note ? ': ' + z.note : '') }] : [],
|
|
actions: [z.paused ? { label: 'Resume zone', path: '/api/admin/zones/' + z.id, body: { paused: false, note: '' } } : { label: 'Pause zone', path: '/api/admin/zones/' + z.id, body: { paused: true, note: 'Paused from Member content ' + ctDay(Date.now()) }, warn: 'Pause this zone? It will serve the house banner only and earn nothing.' }],
|
|
search: [z.site, z.size, z.note] });
|
|
|
|
// ad campaigns (member campaigns only; house ads are the admin's own); open member reports flag the row
|
|
const open = {}; try { for (const x of await R.reports.list(5000)) if (!x.resolved) (open[x.campaignId] = open[x.campaignId] || []).push(x); } catch (e) {}
|
|
for (const c of await R.ads.adminList(1000000)) {
|
|
if (c.house || String(c.owner || '').toLowerCase() === house) continue;
|
|
const reps = open[c.id] || []; const flags = reps.length ? [{ k: 'reported', t: reps.length + ' open report' + (reps.length > 1 ? 's' : '') + ': ' + Array.from(new Set(reps.map(x => x.reason))).join(', ') }] : [];
|
|
const body = strip(c.body).slice(0, 300);
|
|
add({ type: 'ad', id: String(c.id), ownerEmail: c.owner, title: c.name, created: c.created, status: c.scheduled ? 'scheduled' : c.status, live: c.status === 'active' && !c.scheduled, url: c.targetUrl, open: c.targetUrl,
|
|
detail: { adType: c.type, imageUrl: c.imageUrl, title: c.title, body, width: c.width, height: c.height, budget: c.budget, spent: c.spent, starts: c.starts, expires: c.expires, geo: c.geo, dailyCap: c.dailyCap, audience: c.audience },
|
|
counts: { imps: c.imps, impsNas: c.impsNas, clicks: c.clicks }, hosts: [hostOf(c.targetUrl)].concat(urlsIn(c.body).map(hostOf)), flags,
|
|
actions: c.status === 'active' ? [{ label: 'Pause ad', path: '/api/admin/campaigns/' + c.id + '/pause', body: {}, warn: 'Pause campaign #' + c.id + '? It stops serving until resumed.' }] : c.status === 'paused' ? [{ label: 'Resume ad', path: '/api/admin/campaigns/' + c.id + '/resume', body: {} }] : [],
|
|
search: [c.type, c.targetUrl, c.imageUrl, c.title, body] });
|
|
}
|
|
|
|
// postbacks
|
|
for (const p of R.postbacks.adminAll()) add({ type: 'postback', id: p.id, ownerEmail: p.owner, title: p.name, created: p.created, status: p.enabled ? 'live' : 'off', live: !!p.enabled, url: '', open: null,
|
|
detail: { postbackUrl: p.url, method: p.method, events: p.events, lastStatus: p.lastStatus, lastAt: p.lastAt },
|
|
counts: { sent: p.sent, fails: p.fails }, hosts: [hostOf(p.url)], flags: p.fails >= 5 ? [{ k: 'failing', t: p.fails + ' failed deliveries in a row' }] : [], search: [p.url] });
|
|
|
|
// profiles: bio, avatar, socials, line banner, wall offers (public on the member's wall and welcome tours)
|
|
const refs = {}; const ref = (name, email, where) => { const k = name.toLowerCase(); const o = refs[k] = refs[k] || { email, where: [] }; if (!o.email) o.email = email; if (o.where.length < 6) o.where.push(where); };
|
|
for (const a of accts) {
|
|
const socials = parse(a.socials) || {}; const offers = (parse(a.wallOffers) || []).filter(Boolean);
|
|
const blob = JSON.stringify([a.avatarUrl, a.lineBannerUrl, offers]); let m; UP_RE.lastIndex = 0; while ((m = UP_RE.exec(blob))) ref(m[1], a.email, 'profile of ' + (a.username ? '@' + a.username : a.email));
|
|
if (!(a.bio || a.avatarUrl || Object.keys(socials).length || a.lineBannerUrl || a.lineTargetUrl || offers.length)) continue;
|
|
const who = a.username || a.code || '';
|
|
add({ type: 'profile', id: a.email, ownerEmail: a.email, title: (a.username ? '@' + a.username : a.email) + ' profile', created: a.created, status: 'live', live: true, url: who ? 'https://' + R.siteHost + '/wall/' + who : '', open: who ? '/wall/' + who : null,
|
|
detail: { bio: String(a.bio || '').slice(0, 600), avatarUrl: a.avatarUrl, socials, lineBannerUrl: a.lineBannerUrl, lineTargetUrl: a.lineTargetUrl, wallOffers: offers },
|
|
hosts: [hostOf(a.lineTargetUrl), socials.website ? hostOf(socials.website) : ''].concat(offers.map(o => hostOf(o.targetUrl))),
|
|
search: [a.bio, a.lineTargetUrl, a.lineBannerUrl].concat(Object.values(socials), offers.map(o => (o.title || '') + ' ' + o.targetUrl)) });
|
|
}
|
|
|
|
// uploads: page images (pages index knows the owner) + /uploads files (owner from the upload index or from what uses them)
|
|
for (const i of R.pages.adminImages()) add({ type: 'upload', id: i.id, ownerEmail: i.owner, title: 'Page image ' + i.id, created: i.ts, status: 'stored', live: true, url: i.path, open: i.path,
|
|
detail: { file: i.path, size: i.size, mime: i.type, store: 'Page images', image: true }, search: [i.path] });
|
|
try {
|
|
const camps = await R.ads.adminList(1000000);
|
|
for (const c of camps) { if (c.house) continue; const blob = JSON.stringify([c.imageUrl, c.body]); let m; UP_RE.lastIndex = 0; while ((m = UP_RE.exec(blob))) ref(m[1], c.owner, 'campaign #' + c.id + ' (' + c.type + ')'); }
|
|
} catch (e) {}
|
|
const idx = readIdx();
|
|
let files = []; try { files = fs.readdirSync(R.uploadsDir).filter(f => /^[a-z0-9]{24}\.(png|jpg|webp|gif|mp4|webm)$/i.test(f)); } catch (e) {}
|
|
const seenUp = new Set();
|
|
for (const f of files) {
|
|
let st = null; try { st = fs.statSync(path.join(R.uploadsDir, f)); } catch (e) { continue; }
|
|
const k = f.toLowerCase(); seenUp.add(k); const ix = idx[f] || {}; const rf = refs[k];
|
|
if (ix.who === 'admin' && !rf) continue; // house-ad creative the admin uploaded
|
|
const owner = ix.who && ix.who !== 'admin' ? ix.who : rf ? rf.email : '';
|
|
const isVid = /\.(mp4|webm)$/i.test(f);
|
|
add({ type: 'upload', id: f, ownerEmail: owner, title: (isVid ? 'Video ' : 'Image ') + f, created: ix.ts || st.mtimeMs, status: rf ? 'in use' : 'unused', live: !!rf, url: '/uploads/' + f, open: '/uploads/' + f,
|
|
detail: { file: '/uploads/' + f, size: st.size, mime: isVid ? 'video' : 'image', store: 'Uploads', image: !isVid, usedBy: rf ? rf.where : [], ownerGuess: !ix.who && !!rf },
|
|
search: [f].concat(rf ? rf.where : []) });
|
|
}
|
|
for (const [f, ix] of Object.entries(idx)) { // videos that went to Spaces (no local file)
|
|
if (seenUp.has(f.toLowerCase()) || !ix.url || !/^https?:/i.test(ix.url) || ix.who === 'admin') continue;
|
|
add({ type: 'upload', id: f, ownerEmail: ix.who, title: 'Video ' + f, created: ix.ts, status: 'stored', live: true, url: ix.url, open: ix.url, detail: { file: ix.url, size: ix.size, mime: 'video', store: 'Spaces', image: false }, search: [ix.url] });
|
|
}
|
|
|
|
// sponsor broadcasts (members writing to their line); system senders left out
|
|
try {
|
|
for (const b of await R.messages.adminBroadcasts(3000)) {
|
|
if (!b.fromEmail || b.fromEmail === admin || b.fromEmail === house) continue;
|
|
const body = strip(b.body);
|
|
add({ type: 'message', id: b.fromEmail + ':' + b.sent, ownerEmail: b.fromEmail, title: b.subject || '(no subject)', created: b.sent, status: 'sent', live: true, url: '', open: null,
|
|
detail: { body: body.slice(0, 600), recipients: b.recipients }, counts: { recipients: b.recipients }, hosts: urlsIn(b.body).map(hostOf), search: [body] });
|
|
}
|
|
} catch (e) { console.error('content broadcasts', e.message); }
|
|
|
|
// audiences made by hand
|
|
for (const a of R.audiences.adminAll()) add({ type: 'audience', id: a.id, ownerEmail: a.owner, title: a.name, created: a.created, status: 'live', live: true, url: '', open: null,
|
|
detail: { audienceId: a.id, pixel: '<script src="https://' + R.siteHost + '/p.js" data-aud="' + a.id + '"></script>' }, counts: { size30: a.size30, size7: a.size7 }, search: [a.id] });
|
|
|
|
// Video Maker renders (the company promo with the member's own end card)
|
|
for (const j of R.videomaker.adminJobs()) add({ type: 'video', id: j.id, ownerEmail: j.email, title: j.title, created: j.at, status: j.status, live: j.status === 'done', url: j.url || '', open: j.url || null,
|
|
detail: { slug: j.slug, username: j.username, error: j.error || '', doneAt: j.doneAt || 0 }, search: [j.slug, j.username] });
|
|
|
|
cache = { ts: Date.now(), rows }; return rows;
|
|
}
|
|
|
|
// -- the API: GET /api/admin/content?type=&q=&from=&to=&flagged=1&page=&per=&fresh=1
|
|
async function query(o) {
|
|
o = o || {};
|
|
const rows = await collect(!!o.fresh);
|
|
const totals = {}; for (const t of TYPES) totals[t.key] = { n: 0, live: 0, flagged: 0 };
|
|
let flaggedAll = 0; for (const r of rows) { const t = totals[r.type]; if (!t) continue; t.n++; if (r.live) t.live++; if (r.flags.length) { t.flagged++; flaggedAll++; } }
|
|
const type = TYPES.some(t => t.key === o.type) ? o.type : 'all';
|
|
const day = s => /^\d{4}-\d{2}-\d{2}$/.test(String(s || '')) ? String(s) : '';
|
|
const from = day(o.from), to = day(o.to);
|
|
const terms = String(o.q || '').toLowerCase().split(/\s+/).filter(Boolean).slice(0, 8);
|
|
let list = rows.filter(r => (type === 'all' || r.type === type) && (!o.flagged || r.flags.length) && (!from || (r.day && r.day >= from)) && (!to || (r.day && r.day <= to)) && terms.every(t => r.text.includes(t)));
|
|
list.sort((a, b) => (Number(b.created) || 0) - (Number(a.created) || 0));
|
|
const hc = {}; for (const r of list) for (const h of r.hosts) hc[h] = (hc[h] || 0) + 1;
|
|
const hosts = Object.entries(hc).sort((a, b) => b[1] - a[1]).slice(0, 15).map(([host, n]) => ({ host, n, burned: (() => { try { return !!R.domains.isBurned(host); } catch (e) { return false; } })() }));
|
|
const per = Math.max(10, Math.min(200, Number(o.per) || 50)); const pages = Math.max(1, Math.ceil(list.length / per));
|
|
const page = Math.max(1, Math.min(pages, Number(o.page) || 1));
|
|
const items = list.slice((page - 1) * per, page * per).map(r => { const x = Object.assign({}, r); delete x.text; return x; });
|
|
return { types: TYPES, type, totals, all: rows.length, flaggedAll, matched: list.length, page, pages, per, items, hosts, denyList: false, generated: cache ? cache.ts : Date.now() };
|
|
}
|
|
function invalidate() { cache = null; }
|
|
module.exports = { init, TYPES, query, collect, invalidate, noteUpload };
|