refactor: replace proxy-based analytics with static guild datasets
This commit is contained in:
19 files changed
+397
-178
No files matched your search
@@ -1,32 +0,0 @@
|
||||
// Shared by the local server and the optional Cloudflare Worker. No arbitrary upstream URLs.
|
||||
const API = 'https://api.albionbb.com/eu';
|
||||
export function upstreamUrl(requestUrl) {
|
||||
const input = new URL(requestUrl), path = input.pathname.replace(/^\/api\/albion/, '');
|
||||
const allowed = path === '/guilds/search' || path === '/battles' || path === '/battles/multi' || /^\/battles\/\d+$/.test(path);
|
||||
if (!input.pathname.startsWith('/api/albion/') || !allowed) throw Error('Unsupported API path');
|
||||
const url = new URL(API + path);
|
||||
const allowedKeys = path === '/guilds/search' ? ['search'] : path === '/battles' ? ['guildId','page','minPlayers','minGuildPlayers'] : path === '/battles/multi' ? ['ids'] : [];
|
||||
for (const [key, value] of input.searchParams) {
|
||||
if (!allowedKeys.includes(key) || value.length > 2000) throw Error('Invalid API parameter');
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
if (path === '/guilds/search' && (!url.searchParams.get('search')?.trim() || url.searchParams.get('search').length > 100)) throw Error('Invalid guild name');
|
||||
if (path === '/battles') {
|
||||
if (!/^[\w-]{1,64}$/.test(url.searchParams.get('guildId') || '')) throw Error('Invalid guild ID');
|
||||
for (const key of ['page','minPlayers','minGuildPlayers']) if (url.searchParams.has(key) && !/^\d{1,5}$/.test(url.searchParams.get(key))) throw Error('Invalid numeric parameter');
|
||||
}
|
||||
if (path === '/battles/multi' && !/^\d+(,\d+){1,99}$/.test(url.searchParams.get('ids') || '')) throw Error('Invalid battle IDs');
|
||||
return url;
|
||||
}
|
||||
export async function proxyAlbion(request, fetchImpl = fetch) {
|
||||
if (request.method !== 'GET') return Response.json({ error: 'Method not allowed' }, { status: 405, headers: { Allow: 'GET' } });
|
||||
let url;
|
||||
try { url = upstreamUrl(request.url); }
|
||||
catch { return Response.json({ error: 'Invalid Albion API request' }, { status: 400 }); }
|
||||
try {
|
||||
const result = await fetchImpl(url, { headers: { Accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(30_000) });
|
||||
if (!result.ok) return Response.json({ error: 'AlbionBB is temporarily unavailable', upstreamStatus: result.status }, { status: result.status === 429 ? 429 : 502 });
|
||||
const body = await result.json();
|
||||
return Response.json(body, { headers: { 'Cache-Control': 'public, max-age=120', 'X-Content-Type-Options': 'nosniff' } });
|
||||
} catch { return Response.json({ error: 'Unable to reach AlbionBB' }, { status: 502 }); }
|
||||
}
|
||||
+3
-4
@@ -13,7 +13,8 @@ const dist = new URL('../dist/', import.meta.url);
|
||||
await rm(dist, { recursive: true, force: true });
|
||||
await mkdir(new URL('assets/', dist), { recursive: true });
|
||||
for (const [from,to] of [['src/styles.css','styles.css'],['src/app.js','app.js']]) await cp(new URL(from,root),new URL(`assets/${to}`,dist));
|
||||
for (const name of ['intel.js','intel-core.js','intel-text.js','intel.css']) await cp(new URL(`src/${name}`,root),new URL(`assets/${name}`,dist));
|
||||
for (const name of ['intel.js','intel-core.js','intel-data.js','intel-text.js','intel.css']) await cp(new URL(`src/${name}`,root),new URL(`assets/${name}`,dist));
|
||||
try { await cp(new URL('public/data/',root),new URL('data/',dist),{recursive:true}); } catch(err) { if(err.code!=='ENOENT') throw err; }
|
||||
try { await cp(new URL('public/assets/',root),new URL('assets/',dist),{ recursive:true }); } catch(err) { if(err.code !== 'ENOENT') throw err; }
|
||||
await rm(new URL('assets/battles/previews.json',dist),{force:true});
|
||||
const faviconLogo=(await readFile(new URL('public/assets/logo.jpg',root))).toString('base64');
|
||||
@@ -84,9 +85,7 @@ for (const lang of ['en','fa']) {
|
||||
await mkdir(folder,{recursive:true}); await writeFile(new URL('index.html',folder),render(lang));
|
||||
const intelFolder=new URL('intel/',folder);
|
||||
await mkdir(intelFolder,{recursive:true});
|
||||
const apiBase=process.env.ONEUP_API_BASE_URL || '/api/albion';
|
||||
if (apiBase !== '/api/albion' && (!apiBase.startsWith('https://') || new URL(apiBase).search || new URL(apiBase).hash)) throw Error('ONEUP_API_BASE_URL must be an HTTPS API base URL');
|
||||
await writeFile(new URL('index.html',intelFolder),renderIntel(lang,origin,apiBase));
|
||||
await writeFile(new URL('index.html',intelFolder),renderIntel(lang,origin));
|
||||
}
|
||||
await Promise.all([
|
||||
writeFile(new URL('CNAME',dist),new URL(origin).hostname+'\n'),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { escapeHtml as e } from './lib.mjs';
|
||||
import { textFor } from '../src/intel-text.js';
|
||||
|
||||
export function renderIntel(lang, origin, apiBase = '/api/albion') {
|
||||
export function renderIntel(lang, origin) {
|
||||
const fa = lang === 'fa', t = textFor(lang), base = fa ? '../../' : '../';
|
||||
return `<!doctype html><html lang="${lang}" dir="${fa ? 'rtl' : 'ltr'}"><head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
@@ -10,15 +10,16 @@ export function renderIntel(lang, origin, apiBase = '/api/albion') {
|
||||
<link rel="icon" href="${base}assets/favicon.svg"><link rel="stylesheet" href="${base}assets/styles.css"><link rel="stylesheet" href="${base}assets/intel.css">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@500;600;700;800&family=Barlow:wght@400;500;600;700&family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<script type="module" src="${base}assets/intel.js"></script></head>
|
||||
<body class="intel-page" data-api-base="${e(apiBase)}">
|
||||
<body class="intel-page">
|
||||
<a class="skip-link" href="#intel-main">${fa ? 'رفتن به محتوا' : 'Skip to content'}</a>
|
||||
<header class="intel-header"><a class="brand" href="${base}${fa ? 'fa/' : ''}" aria-label="OneUP"><img src="${base}assets/logo.jpg" alt="" width="44" height="44"><span>ONE<span class="brand-up">UP</span><small>GUILD INTELLIGENCE</small></span></a>
|
||||
<a class="intel-back" href="${base}${fa ? 'fa/' : ''}">${e(t.back)} <span aria-hidden="true">↗</span></a>
|
||||
<div class="languages"><a href="${base}intel/" lang="en" data-intel-language ${!fa ? 'aria-current="page"' : ''}>EN</a><span>/</span><a href="${base}fa/intel/" lang="fa" data-intel-language ${fa ? 'aria-current="page"' : ''}>فا</a></div></header>
|
||||
<main id="intel-main" class="intel-main">
|
||||
<section class="intel-hero"><div><p class="eyebrow">${e(t.eyebrow)}</p><h1>${e(t.hero)}<br><span>${e(t.accent)}</span></h1><p class="intel-intro">${e(t.intro)}</p></div><div class="intel-signal" aria-hidden="true"><div class="signal-orbit"></div><div class="signal-orbit orbit-inner"></div><span class="signal-center">1<span>UP</span></span><i></i><b>EU / INTEL</b></div><div class="intel-source"><span class="live-dot"></span>${e(t.region)}<span class="source-divider">/</span>${e(t.live)}</div></section>
|
||||
<section class="intel-dataset"><div><span class="live-dot"></span><p id="snapshot-status" role="status">${e(t.loadingData)}</p></div><div id="available-guilds" aria-label="${e(t.availableGuilds)}"></div><p>${e(t.snapshotHelp)}</p></section>
|
||||
<section class="intel-controls" aria-label="${e(t.title)}"><form id="intel-form">
|
||||
<div class="intel-search"><label for="guild-name">${e(t.guild)}</label><div class="search-field"><span aria-hidden="true">⌕</span><input id="guild-name" name="guild" placeholder="${e(t.placeholder)}" dir="ltr" required minlength="2" maxlength="100" autocomplete="off" spellcheck="false"></div></div>
|
||||
<div class="intel-search"><label for="guild-name">${e(t.guild)}</label><div class="search-field"><span aria-hidden="true">⌕</span><input id="guild-name" name="guild" placeholder="${e(t.placeholder)}" dir="ltr" required minlength="2" maxlength="100" autocomplete="off" spellcheck="false" list="prepared-guilds"><datalist id="prepared-guilds"></datalist></div></div>
|
||||
<fieldset class="period-field"><legend>${e(t.period)}</legend><div class="period-options">${[7,30,60].map(days => `<label><input type="radio" name="days" value="${days}" ${days === 7 ? 'checked' : ''}><span>${days} <small>${e(t.days)}</small></span></label>`).join('')}</div></fieldset>
|
||||
<div class="minimum-field"><label for="min-members">${e(t.minimum)}</label><input id="min-members" name="minimum" type="number" min="1" max="1000" step="1" value="10" required aria-describedby="min-help"></div>
|
||||
<button class="button intel-submit" type="submit">${e(t.analyze)} <span aria-hidden="true">↗</span></button>
|
||||
@@ -29,6 +30,6 @@ export function renderIntel(lang, origin, apiBase = '/api/albion') {
|
||||
<div id="intel-results" hidden></div>
|
||||
<details class="intel-method"><summary>${e(t.methodology)} <span aria-hidden="true">+</span></summary><p>${e(t.caveat)}</p><p>${e(t.mergeHelp)}</p><p>${e(t.minimumHelp)}</p></details>
|
||||
</main><footer class="intel-footer"><span>ONE<span>UP</span> / INTELLIGENCE</span><p>${e(t.service)}</p><a href="https://europe.albionbb.com/" target="_blank" rel="noopener noreferrer">ALBIONBB ↗</a></footer>
|
||||
<noscript><p class="intel-error">${fa ? 'برای دریافت گزارش زنده، جاوااسکریپت مرورگر را فعال کن.' : 'Enable JavaScript to load live reports.'}</p></noscript>
|
||||
<noscript><p class="intel-error">${fa ? 'برای تحلیل گزارش، جاوااسکریپت مرورگر را فعال کن.' : 'Enable JavaScript to analyze reports.'}</p></noscript>
|
||||
</body></html>`;
|
||||
}
|
||||
+1
-7
@@ -2,18 +2,12 @@ import http from 'node:http';
|
||||
import { readFile, stat } from 'node:fs/promises';
|
||||
import { resolve, extname, sep } from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { proxyAlbion } from './albion-proxy.mjs';
|
||||
const built = spawnSync(process.execPath, ['scripts/build.mjs'], { stdio:'inherit' });
|
||||
if (built.status) process.exit(built.status);
|
||||
const root=resolve('dist');
|
||||
const types={'.html':'text/html; charset=utf-8','.css':'text/css','.js':'text/javascript','.jpg':'image/jpeg','.png':'image/png','.webp':'image/webp','.svg':'image/svg+xml','.xml':'application/xml','.txt':'text/plain'};
|
||||
const types={'.json':'application/json; charset=utf-8','.html':'text/html; charset=utf-8','.css':'text/css','.js':'text/javascript','.jpg':'image/jpeg','.png':'image/png','.webp':'image/webp','.svg':'image/svg+xml','.xml':'application/xml','.txt':'text/plain'};
|
||||
http.createServer(async(req,res)=>{
|
||||
try {
|
||||
if (new URL(req.url,'http://localhost').pathname.startsWith('/api/albion/')) {
|
||||
const response = await proxyAlbion(new Request(new URL(req.url,'http://localhost'), { method: req.method }));
|
||||
res.writeHead(response.status, Object.fromEntries(response.headers)).end(Buffer.from(await response.arrayBuffer()));
|
||||
return;
|
||||
}
|
||||
let path=resolve(root, '.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
|
||||
if(path!==root && !path.startsWith(root+sep)){res.writeHead(403).end();return;}
|
||||
if((await stat(path)).isDirectory()) path=resolve(path,'index.html');
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { readFile, writeFile, mkdir, rename, readdir, rm } from 'node:fs/promises';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { fetchJson } from './fetch-battles.mjs';
|
||||
import { groupReports, ownGuild, ownPlayers, normalizeName, selectBattles, scanListings, mapLimit } from '../src/intel-core.js';
|
||||
import { validateIndex } from '../src/intel-data.js';
|
||||
|
||||
const API = 'https://api.albionbb.com/eu';
|
||||
export const groupKey = ids => [...ids].map(Number).sort((a,b)=>a-b).join(',');
|
||||
export function compactBattle(raw, guildId) {
|
||||
const guild = ownGuild(raw,guildId);
|
||||
if (!guild || !Array.isArray(raw.players) || !Number.isFinite(Date.parse(raw.startedAt)) || !Number.isFinite(Date.parse(raw.finishedAt))) throw Error('Incomplete guild report');
|
||||
return {
|
||||
albionId:raw.albionId,startedAt:raw.startedAt,finishedAt:raw.finishedAt,
|
||||
totalFame:raw.totalFame,totalKills:raw.totalKills,totalPlayers:raw.totalPlayers,
|
||||
guilds:raw.guilds,players:ownPlayers(raw,guildId),
|
||||
};
|
||||
}
|
||||
export function requiredMultis(battles, guildId, asOf) {
|
||||
const needed = new Map(), until = Date.parse(asOf);
|
||||
// Every attendance value changes inclusion only at one of these boundaries.
|
||||
// Preload multi reports for ALL supported day windows and player thresholds.
|
||||
for (const days of [7,30,60]) {
|
||||
const rows = selectBattles(battles,guildId,{since:until-days*86_400_000,until,minPlayers:1});
|
||||
const thresholds = new Set([1,...rows.map(b=>b.totalPlayers+1)]);
|
||||
for (const minPlayers of thresholds) {
|
||||
for (const group of groupReports(rows.filter(b=>b.totalPlayers>=minPlayers),guildId)) {
|
||||
if (group.length>1) needed.set(groupKey(group.map(b=>b.albionId)),group);
|
||||
}
|
||||
}
|
||||
}
|
||||
return needed;
|
||||
}
|
||||
export async function collectGuild(name, previous, {request,asOf=new Date().toISOString(),log=()=>{}}) {
|
||||
const candidates = await request('/guilds/search',{search:name});
|
||||
const matches = candidates.filter(g=>normalizeName(g.Name)===normalizeName(name));
|
||||
if (matches.length!==1) throw Error(`Expected one exact Europe guild match for ${name}; found ${matches.length}`);
|
||||
const guild = matches[0], until = Date.parse(asOf), since = until-60*86_400_000;
|
||||
if (!/^[\w-]{1,64}$/.test(guild.Id)) throw Error('Invalid guild identity');
|
||||
const listings = await scanListings(request,guild.Id,since,undefined,(page,count)=>log(`${guild.Name}: history page ${page}, ${count} battles`));
|
||||
const cached = new Map((previous?.guild?.Id===guild.Id?previous.battles||[]:[]).map(b=>[b.albionId,b]));
|
||||
let done = 0;
|
||||
const battles = await mapLimit(listings.filter(b=>Date.parse(b.startedAt)<=until),3,async row=>{
|
||||
const old = cached.get(row.albionId);
|
||||
const raw = old && until-Date.parse(row.startedAt)>86_400_000 ? old : await request(`/battles/${row.albionId}`);
|
||||
if (raw.albionId!==row.albionId) throw Error('Mismatched battle ID');
|
||||
const detail = compactBattle(raw,guild.Id);
|
||||
if (++done%25===0 || done===listings.length) log(`${guild.Name}: details ${done}/${listings.length}`);
|
||||
return detail;
|
||||
});
|
||||
const required = requiredMultis(battles,guild.Id,asOf), multis = {};
|
||||
log(`${guild.Name}: ${required.size} unique combined reports across all filters`);
|
||||
done = 0;
|
||||
await mapLimit([...required],2,async([key,group])=>{
|
||||
const old = previous?.guild?.Id===guild.Id && previous.multis?.[key];
|
||||
const fresh = group.some(b=>until-Date.parse(b.startedAt)<86_400_000);
|
||||
const raw = old && !fresh ? old : await request('/battles/multi',{ids:key});
|
||||
const total = ownGuild(raw,guild.Id);
|
||||
for (const field of ['kills','deaths','killFame']) {
|
||||
if (total?.[field]!==group.reduce((sum,b)=>sum+(ownGuild(b,guild.Id)[field]||0),0)) throw Error(`Unverified multi ${key}: ${field}`);
|
||||
}
|
||||
multis[key] = compactBattle(raw,guild.Id);
|
||||
if (++done%10===0 || done===required.size) log(`${guild.Name}: combined reports ${done}/${required.size}`);
|
||||
});
|
||||
return {schemaVersion:1,guild,asOf,coverageDays:60,battles,multis};
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
|
||||
const directory = new URL('../public/data/intel/',import.meta.url);
|
||||
await mkdir(directory,{recursive:true});
|
||||
let manifest = {schemaVersion:1,guilds:[]};
|
||||
try { manifest=validateIndex(JSON.parse(await readFile(new URL('manifest.json',directory),'utf8'))); } catch(error) { if(error.code!=='ENOENT')throw error; }
|
||||
const configured = JSON.parse(await readFile(new URL('../content/intel-guilds.json',import.meta.url),'utf8'));
|
||||
const supplied = process.env.INTEL_GUILD_NAME?.trim();
|
||||
const names = [...new Map([...configured,...manifest.guilds.map(g=>g.Name),...(supplied?[supplied]:[])].map(name=>[normalizeName(name),name.trim()])).values()];
|
||||
let nextStart = 0;
|
||||
const request = async(path,query={})=>{
|
||||
const start = Math.max(Date.now(),nextStart); nextStart = start+220;
|
||||
await new Promise(resolve=>setTimeout(resolve,Math.max(0,start-Date.now())));
|
||||
const url = new URL(API+path);
|
||||
for (const [key,value] of Object.entries(query)) url.searchParams.set(key,value);
|
||||
return fetchJson(url);
|
||||
};
|
||||
const entries = [], asOf = new Date().toISOString();
|
||||
for (const name of names) {
|
||||
const old = manifest.guilds.find(g=>normalizeName(g.Name)===normalizeName(name));
|
||||
let previous;
|
||||
if (old) previous=JSON.parse(await readFile(new URL(old.file,directory),'utf8'));
|
||||
const snapshot = await collectGuild(name,previous,{request,asOf,log:console.log});
|
||||
const json = JSON.stringify(snapshot);
|
||||
const digest = createHash('sha256').update(json).digest('hex').slice(0,12);
|
||||
const file = `${snapshot.guild.Id}-${digest}.json`;
|
||||
await writeFile(new URL(file,directory),json+'\n');
|
||||
entries.push({...snapshot.guild,file,asOf,coverageDays:60,battleCount:snapshot.battles.length});
|
||||
}
|
||||
const result = {schemaVersion:1,updatedAt:asOf,guilds:entries};
|
||||
await writeFile(new URL('manifest.json.tmp',directory),JSON.stringify(result,null,2)+'\n');
|
||||
await rename(new URL('manifest.json.tmp',directory),new URL('manifest.json',directory));
|
||||
const retained = new Set(['manifest.json',...entries.map(g=>g.file)]);
|
||||
for (const file of await readdir(directory)) {
|
||||
if (/^[\w-]+\.json$/.test(file) && !retained.has(file)) await rm(new URL(file,directory));
|
||||
}
|
||||
console.log(`Published ${entries.length} complete guild datasets in public/data/intel/`);
|
||||
}
|
||||
Reference in new issue
Block a user