feat: add bilingual guild analytics with battle filters and composition insights
This commit is contained in:
13 files changed
+730
-2
No files matched your search
@@ -24,6 +24,8 @@ jobs:
|
||||
run: npm run sync:battles
|
||||
- name: Build static pages
|
||||
run: npm run build
|
||||
env:
|
||||
ONEUP_API_BASE_URL: ${{ vars.ONEUP_API_BASE_URL }}
|
||||
- uses: actions/upload-pages-artifact@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
with:
|
||||
|
||||
@@ -56,3 +56,53 @@ The build emits canonical and language alternate links, social metadata, organiz
|
||||
YouTube uses thumbnails and a privacy-enhanced player loaded on request. Direct video URLs use the native video element. AlbionBB previews are cached at build time; explicit image URLs and Europe single/combined battle preview URLs also work without a local cache. Fonts are served by Google Fonts, with system fallbacks.
|
||||
|
||||
The GitHub Actions workflow validates pull requests. Pushes to `main` or `master` also synchronize battle previews, build, and deploy the static artifact to GitHub Pages. Generated output is not tracked.
|
||||
|
||||
## Guild intelligence
|
||||
|
||||
Open `/intel/` or `/fa/intel/` to analyze any Europe guild by its exact full name.
|
||||
The live report includes exact kill/death fame, K/D, recorded attendance and IP,
|
||||
daily fame, roles, weapons, player rankings, expandable encounter compositions,
|
||||
source links, and CSV export. Filters and guild name are shareable in the URL.
|
||||
|
||||
- Time windows are rolling 7, 30 or 60 days. Battle times use UTC.
|
||||
- Minimum players means **all players from all guilds in each original battle**.
|
||||
For example, 40 includes a 40-player fight even if only four belong to the searched
|
||||
guild. Filtering happens before merging and applies to every reported statistic.
|
||||
- Optional grouping uses the archive's continuity criteria: a maximum 20-minute
|
||||
gap, at least three and 50% overlapping guild members, at least three and 50%
|
||||
overlap in other teams, and at most a 90-minute encounter span. Each new battle
|
||||
must match both the first and most recent battle in the group.
|
||||
- Combined groups are requested from AlbionBB's `/battles/multi` API and their
|
||||
kill, death and kill-fame totals are verified against the original reports.
|
||||
End timestamps are taken from the original reports because the multi response
|
||||
does not reliably contain the latest finish time.
|
||||
- Composition counts recorded player appearances, once per encounter. The same
|
||||
member is counted again in another encounter. Zero/missing IP is excluded from
|
||||
the recorded-IP average. Role/weapon snapshots are not complete movement,
|
||||
equipment-switch or in-game attendance telemetry.
|
||||
- Every history page in the time range is scanned. Errors stop the analysis;
|
||||
partial results are never labelled as a complete report. Retry and cancellation
|
||||
are available. Requests use bounded concurrency and a short in-page cache.
|
||||
|
||||
### Live API hosting
|
||||
|
||||
AlbionBB allows browser requests only from its own origin. Live reports therefore
|
||||
require a small server-side read proxy; a GitHub Pages static artifact alone
|
||||
cannot provide this endpoint. No API key is required.
|
||||
|
||||
`npm run dev` provides `/api/albion/*` automatically. For production there are two options:
|
||||
|
||||
1. Build with `npm run build`, then deploy `worker.mjs` and `dist/` to Cloudflare
|
||||
Workers using the included `wrangler.jsonc` (e.g. `npx wrangler deploy`). This
|
||||
serves both the existing site and the same-origin API. Deployment is a separate
|
||||
operator action; the existing GitHub Pages workflow is unchanged.
|
||||
2. Keep GitHub Pages and host the Worker separately. Set the Worker's `SITE_ORIGIN`
|
||||
variable to the exact site origin (for this project, `https://oneup.megh.dad`).
|
||||
Build the static site with
|
||||
`ONEUP_API_BASE_URL=https://YOUR-WORKER.workers.dev/api/albion npm run build`.
|
||||
For the existing CI workflow, set the repository variable `ONEUP_API_BASE_URL`
|
||||
to that URL. Only the configured origin receives cross-origin access.
|
||||
|
||||
The proxy permits GET requests to a fixed Europe upstream and a small allowlist
|
||||
of public report routes and parameters. It does not forward cookies or credentials.
|
||||
Upstream timeouts and rate limits produce a visible error with a retry option.
|
||||
@@ -0,0 +1,32 @@
|
||||
// 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 }); }
|
||||
}
|
||||
+9
-2
@@ -1,6 +1,7 @@
|
||||
import { readFile, writeFile, mkdir, rm, cp, access } from 'node:fs/promises';
|
||||
import { escapeHtml as e, localized, youtubeId, validate } from './lib.mjs';
|
||||
import { renderBattleCards } from './render-battles.mjs';
|
||||
import { renderIntel } from './render-intel.mjs';
|
||||
|
||||
const read = async name => JSON.parse(await readFile(new URL(`../content/${name}.json`, import.meta.url), 'utf8'));
|
||||
const [site, rewards, translations] = await Promise.all(['site','rewards','translations'].map(read));
|
||||
@@ -12,6 +13,7 @@ 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));
|
||||
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');
|
||||
@@ -63,7 +65,7 @@ function render(lang) {
|
||||
<body id="top" data-lang="${lang}" data-video-error="${e(t.videoError)}">${glyphs}<a class="skip-link" href="#main">${e(t.skip)}</a>
|
||||
<header class="site-header"><div class="header-inner"><a class="brand" href="${base}" aria-label="OneUP"><img src="${asset('assets/logo.jpg')}" alt="" width="44" height="44"><span>ONE<span class="brand-up">UP</span><small>${e(t.guild)}</small></span></a>
|
||||
<button class="menu-toggle" aria-expanded="false" aria-controls="navigation" aria-label="${e(t.menu)}"><span></span><span></span></button>
|
||||
<nav id="navigation" aria-label="${fa?'منوی اصلی':'Main navigation'}">${['guild','chronicles','battles','rewards'].map((id,i)=>`<a href="#${id}">${e(t.nav[i])}</a>`).join('')}</nav>
|
||||
<nav id="navigation" aria-label="${fa?'منوی اصلی':'Main navigation'}">${['guild','chronicles','battles','rewards'].map((id,i)=>`<a href="#${id}">${e(t.nav[i])}</a>`).join('')}<a href="${base}${fa?'fa/':''}intel/">${fa?'تحلیل گیلد':'Guild intel'}</a></nav>
|
||||
<div class="header-actions"><div class="languages" aria-label="Language"><a href="${base}?lang=en" lang="en" data-language="en" ${!fa?'aria-current="page"':''}>EN</a><span>/</span><a href="${base}fa/?lang=fa" lang="fa" data-language="fa" ${fa?'aria-current="page"':''}>فا</a></div><a class="button button-small" href="#community">${e(t.join)}${icon('diagonal')}</a></div></div></header>
|
||||
<main id="main"><section class="hero" aria-labelledby="hero-title"><div class="hero-art" aria-hidden="true"><div class="orbit orbit-one"></div><div class="orbit orbit-two"></div><img src="${asset('assets/logo.jpg')}" alt="" width="640" height="640" fetchpriority="high"><span class="art-caption">ONEUP / ALBION ONLINE</span></div><div class="hero-inner"><div class="status"><span></span>${e(site.recruiting?t.recruiting:t.closed)}</div><p class="eyebrow hero-eyebrow">${e(t.eyebrow)}</p><h1 id="hero-title">${e(t.hero1)}<br><span>${e(t.hero2)}</span></h1><p class="hero-copy">${e(t.intro)}</p><div class="hero-buttons"><a class="button" href="#community">${e(t.join)}${icon('diagonal')}</a><a class="text-button" href="#chronicles"><span class="small-play">${icon('play')}</span>${e(t.watch)}</a></div><div class="hero-proof"><strong dir="ltr">${e(site.members)}</strong><span>${e(t.memberLabel)}</span><div class="proof-line"></div>${icon('shield')}</div></div><a class="scroll-cue" href="#guild"><span>↓</span>${e(t.scroll)}</a><span class="hero-coordinate" aria-hidden="true">EST. IN UNITY / FORGED IN BATTLE</span></section>
|
||||
<div class="motto-strip" aria-hidden="true"><span>ONE UNITED POWER</span><b>✦</b><span>ONE BANNER. ONE GUILD.</span><b>✦</b><span>ONE UNITED POWER</span><b>✦</b><span>ONE BANNER. ONE GUILD.</span></div>
|
||||
@@ -80,12 +82,17 @@ function render(lang) {
|
||||
for (const lang of ['en','fa']) {
|
||||
const folder=lang==='en'?dist:new URL('fa/',dist);
|
||||
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 Promise.all([
|
||||
writeFile(new URL('CNAME',dist),new URL(origin).hostname+'\n'),
|
||||
writeFile(new URL('.nojekyll',dist),''),
|
||||
writeFile(new URL('robots.txt',dist),`User-agent: *\nAllow: /\nSitemap: ${origin}/sitemap.xml\n`),
|
||||
writeFile(new URL('sitemap.xml',dist),`<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${['/','/fa/'].map(p=>`<url><loc>${origin}${p}</loc><xhtml:link rel="alternate" hreflang="en" href="${origin}/"/><xhtml:link rel="alternate" hreflang="fa" href="${origin}/fa/"/></url>`).join('')}</urlset>`),
|
||||
writeFile(new URL('sitemap.xml',dist),`<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">${['/','/fa/','/intel/','/fa/intel/'].map(p=>`<url><loc>${origin}${p}</loc><xhtml:link rel="alternate" hreflang="en" href="${origin}/${p.includes('intel')?'intel/':''}"/><xhtml:link rel="alternate" hreflang="fa" href="${origin}/fa/${p.includes('intel')?'intel/':''}"/></url>`).join('')}</urlset>`),
|
||||
writeFile(new URL('404.html',dist),`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Lost in the Outlands | OneUP</title><link rel="stylesheet" href="/assets/styles.css"><main class="not-found"><p class="eyebrow">404 / BEYOND THE FRONT LINE</p><h1>Lost in the<br><span>Outlands.</span></h1><p>The banner is this way.</p><a class="button" href="/">Return to OneUP →</a><a href="/fa/" lang="fa">بازگشت به وانآپ</a></main></html>`)
|
||||
]);
|
||||
console.log(`Built English and Persian pages in dist/ for ${origin}`);
|
||||
@@ -0,0 +1,34 @@
|
||||
import { escapeHtml as e } from './lib.mjs';
|
||||
import { textFor } from '../src/intel-text.js';
|
||||
|
||||
export function renderIntel(lang, origin, apiBase = '/api/albion') {
|
||||
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">
|
||||
<title>${e(t.title)} | OneUP</title><meta name="description" content="${e(t.intro)}"><meta name="theme-color" content="#101111"><meta name="color-scheme" content="dark">
|
||||
<link rel="canonical" href="${origin}/${fa ? 'fa/' : ''}intel/"><link rel="alternate" hreflang="en" href="${origin}/intel/"><link rel="alternate" hreflang="fa" href="${origin}/fa/intel/">
|
||||
<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)}">
|
||||
<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-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>
|
||||
<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>
|
||||
<div class="intel-control-bottom"><label class="merge-control"><input type="checkbox" name="merge" checked><span class="switch" aria-hidden="true"></span>${e(t.merge)}</label><p id="min-help">${e(t.minimumHelp)}</p></div></form></section>
|
||||
<div id="intel-status" class="intel-status" role="status" aria-live="polite"><span class="status-mark"></span><span id="status-text">${e(t.ready)}</span><button id="intel-cancel" type="button" hidden>${e(t.cancel)}</button></div>
|
||||
<section id="intel-empty" class="intel-empty"><div class="empty-crosshair" aria-hidden="true">✦</div><p class="eyebrow">GUILD / BATTLE / COMPOSITION</p><h2>${e(t.idleTitle)}</h2><p>${e(t.idleCopy)}</p><div class="intel-steps">${[t.step1,t.step2,t.step3].map((x,i) => `<span><b>0${i+1}</b>${e(x)}</span>`).join('')}</div></section>
|
||||
<section id="intel-error" class="intel-error" hidden role="alert"><h2>${fa ? 'گزارش آماده نشد' : 'Report unavailable'}</h2><p id="error-text"></p><div id="guild-choices"></div><button class="button" type="button" id="intel-retry">${e(t.retry)}</button></section>
|
||||
<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>
|
||||
</body></html>`;
|
||||
}
|
||||
@@ -2,12 +2,18 @@ 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'};
|
||||
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,127 @@
|
||||
// Pure report logic shared by the browser and the verification suite.
|
||||
export const ROLES = ['tank', 'healer', 'support', 'range', 'melee', 'battlemount', 'unknown'];
|
||||
export const normalizeName = value => String(value ?? '').normalize('NFKC').trim().toLocaleLowerCase('en-US');
|
||||
export const ownGuild = (battle, guildId) => battle.guilds?.find(g => g.albionId === guildId);
|
||||
export const ownPlayers = (battle, guildId) => {
|
||||
const guild = ownGuild(battle, guildId);
|
||||
return (battle.players || []).filter(p => guild && normalizeName(p.guildName) === normalizeName(guild.name));
|
||||
};
|
||||
const millis = value => Date.parse(value);
|
||||
const overlap = (a, b) => {
|
||||
const shared = [...a].reduce((sum, [key, count]) => sum + Math.min(count, b.get(key) || 0), 0);
|
||||
const smaller = Math.min(...[a, b].map(m => [...m.values()].reduce((sum, n) => sum + n, 0)));
|
||||
return { shared, ratio: smaller ? shared / smaller : 0 };
|
||||
};
|
||||
function otherTeams(battle, guildId) {
|
||||
const guild = ownGuild(battle, guildId), teams = new Map();
|
||||
for (const g of battle.guilds || []) {
|
||||
if (g.albionId === guildId || (guild?.alliance && guild.alliance === g.alliance)) continue;
|
||||
const key = g.alliance ? `alliance:${g.alliance}` : `guild:${g.albionId}`;
|
||||
teams.set(key, (teams.get(key) || 0) + g.players);
|
||||
}
|
||||
return teams;
|
||||
}
|
||||
export function compatible(a, b, guildId) {
|
||||
const roster = overlap(...[a, b].map(x => new Map(ownPlayers(x, guildId).map(p => [p.name, 1]))));
|
||||
const teams = overlap(otherTeams(a, guildId), otherTeams(b, guildId));
|
||||
return roster.shared >= 3 && roster.ratio >= .5 && teams.shared >= 3 && teams.ratio >= .5;
|
||||
}
|
||||
export function groupReports(battles, guildId, merge = true) {
|
||||
const sorted = [...new Map(battles.map(b => [b.albionId, b])).values()]
|
||||
.sort((a, b) => millis(a.startedAt) - millis(b.startedAt) || a.albionId - b.albionId);
|
||||
const groups = [];
|
||||
for (const battle of sorted) {
|
||||
const candidates = merge ? groups.filter(group => {
|
||||
const last = group.at(-1);
|
||||
const end = Math.max(...[...group, battle].map(b => millis(b.finishedAt || b.startedAt)));
|
||||
return millis(battle.startedAt) - millis(last.finishedAt || last.startedAt) <= 20 * 60_000 &&
|
||||
end - millis(group[0].startedAt) <= 90 * 60_000 &&
|
||||
compatible(last, battle, guildId) && compatible(group[0], battle, guildId);
|
||||
}) : [];
|
||||
candidates.sort((a, b) => millis(b.at(-1).finishedAt) - millis(a.at(-1).finishedAt));
|
||||
if (candidates.length) candidates[0].push(battle); else groups.push([battle]);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
export function selectBattles(battles, guildId, { since, until, minPlayers }) {
|
||||
return battles.filter(b => millis(b.startedAt) >= since && millis(b.startedAt) <= until &&
|
||||
ownGuild(b, guildId) && b.totalPlayers >= minPlayers);
|
||||
}
|
||||
export function makeReport(group, combined, guildId) {
|
||||
const battle = combined || group[0];
|
||||
if (!ownGuild(battle, guildId) || !Array.isArray(battle.players)) throw Error('Invalid guild report');
|
||||
return {
|
||||
ids: group.map(b => b.albionId), battle, guild: ownGuild(battle, guildId),
|
||||
players: ownPlayers(battle, guildId),
|
||||
startedAt: new Date(Math.min(...group.map(b => millis(b.startedAt)))).toISOString(),
|
||||
// The multi API's end timestamp is not reliably the maximum end time.
|
||||
finishedAt: new Date(Math.max(...group.map(b => millis(b.finishedAt || b.startedAt)))).toISOString(),
|
||||
url: `https://europe.albionbb.com/battles/${group.length > 1 ? `multi?ids=${group.map(b => b.albionId).join(',')}` : group[0].albionId}`,
|
||||
};
|
||||
}
|
||||
export function summarize(reports) {
|
||||
const summary = { kills: 0, deaths: 0, killFame: 0, deathFame: 0, attendance: 0, ip: 0, ipCount: 0,
|
||||
roles: Object.fromEntries(ROLES.map(r => [r, 0])), weapons: new Map(), players: new Map(), daily: new Map() };
|
||||
for (const report of reports) {
|
||||
const guild = report.guild;
|
||||
summary.kills += guild.kills || 0; summary.deaths += guild.deaths || 0;
|
||||
summary.killFame += guild.killFame || 0; summary.attendance += guild.players || 0;
|
||||
const date = report.startedAt.slice(0, 10);
|
||||
summary.daily.set(date, (summary.daily.get(date) || 0) + (guild.killFame || 0));
|
||||
for (const p of report.players) {
|
||||
const role = ROLES.includes(p.role) ? p.role : 'unknown';
|
||||
summary.roles[role]++;
|
||||
summary.deathFame += p.deathFame || 0;
|
||||
if (p.ip > 0) { summary.ip += p.ip; summary.ipCount++; }
|
||||
const equipment = role === 'battlemount' && typeof p.mount === 'string'
|
||||
? { name: p.mount, type: p.mount, quality: 1 } : p.weapon;
|
||||
if (equipment?.name) {
|
||||
const key = `${role}:${equipment.name}`;
|
||||
const weapon = summary.weapons.get(key) || { ...equipment, role, count: 0 };
|
||||
weapon.count++; summary.weapons.set(key, weapon);
|
||||
}
|
||||
const player = summary.players.get(p.name) || { name: p.name, kills: 0, deaths: 0, killFame: 0, attendance: 0, heal: 0, damage: 0 };
|
||||
for (const key of ['kills', 'deaths', 'killFame', 'heal', 'damage']) player[key] += p[key] || 0;
|
||||
player.attendance++; summary.players.set(p.name, player);
|
||||
}
|
||||
}
|
||||
summary.averageAttendance = reports.length ? summary.attendance / reports.length : 0;
|
||||
summary.averageIp = summary.ipCount ? summary.ip / summary.ipCount : 0;
|
||||
return summary;
|
||||
}
|
||||
|
||||
export async function mapLimit(items, limit, task) {
|
||||
const results = new Array(items.length);
|
||||
let next = 0, failed = false;
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (!failed) {
|
||||
const index = next++;
|
||||
if (index >= items.length) return;
|
||||
try { results[index] = await task(items[index], index); }
|
||||
catch (error) { failed = true; throw error; }
|
||||
}
|
||||
}));
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function scanListings(api, guildId, since, signal, progress = () => {}, minPlayers = 1) {
|
||||
const found = new Map();
|
||||
// Fetch every page in range; do not present a fixed first-page sample as a full history.
|
||||
for (let page = 1; page <= 1000; page++) {
|
||||
signal?.throwIfAborted();
|
||||
const rows = await api('/battles', { guildId, minPlayers, minGuildPlayers: 1, page }, signal);
|
||||
if (!Array.isArray(rows)) throw Error('Invalid battle listing');
|
||||
let added = 0;
|
||||
for (const row of rows) {
|
||||
if (!Number.isSafeInteger(row.albionId) || !Number.isFinite(millis(row.startedAt))) throw Error('Invalid battle listing');
|
||||
if (!found.has(row.albionId)) added++;
|
||||
found.set(row.albionId, row);
|
||||
}
|
||||
progress(page, found.size);
|
||||
if (rows.length < 20 || rows.every(b => millis(b.startedAt) < since)) {
|
||||
return [...found.values()].filter(b => millis(b.startedAt) >= since);
|
||||
}
|
||||
if (!added) throw Error('Pagination stopped advancing');
|
||||
}
|
||||
throw Error('History scan exceeded 1000 pages; narrow the date range.');
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
const messages = {
|
||||
title: ['Guild intelligence', 'مرکز تحلیل گیلد'],
|
||||
back: ['Back to OneUP', 'بازگشت به وانآپ'],
|
||||
eyebrow: ['ONEUP / BATTLE INTELLIGENCE', 'ONEUP / تحلیل میدان نبرد'],
|
||||
hero: ['Every battle.', 'هر نبرد،'],
|
||||
accent: ['A clearer picture.', 'تصویری روشنتر.'],
|
||||
intro: ['Read the guild behind the numbers. Explore its kill fame, fighting strength and the compositions it brings to battle.', 'پشت هر عدد، یک گیلد است. فیم بهدستآمده، قدرت حضور و ترکیب نیروهایش را در نبردها بررسی کن.'],
|
||||
region: ['EUROPE SERVER', 'سرور اروپا'],
|
||||
live: ['LIVE REPORTS', 'گزارشهای زنده'],
|
||||
guild: ['Full guild name', 'نام کامل گیلد'],
|
||||
placeholder: ['e.g. OneUP', 'مثلاً OneUP'],
|
||||
period: ['Time window', 'بازهٔ زمانی'],
|
||||
days: ['days', 'روز'],
|
||||
minimum: ['Minimum total battle players', 'حداقل کل بازیکنان بتل'],
|
||||
minimumHelp: ['All guilds combined, before merging. 40 excludes every original battle with fewer than 40 total participants.', 'مجموع بازیکنان همهٔ گیلدها، پیش از ادغام. عدد ۴۰ هر بتلی با کمتر از ۴۰ شرکتکننده در مجموع را حذف میکند.'],
|
||||
merge: ['Combine related battles', 'ادغام بتلهای مرتبط'],
|
||||
mergeHelp: ['Up to 20 minutes apart, with at least 50% shared guild roster and similar other teams. Maximum combined span: 90 minutes.', 'فاصله تا ۲۰ دقیقه، حداقل ۵۰٪ اشتراک اعضای گیلد و ترکیب مشابه سایر تیمها؛ طول هر درگیری حداکثر ۹۰ دقیقه.'],
|
||||
analyze: ['Analyze guild', 'تحلیل گیلد'],
|
||||
cancel: ['Cancel', 'لغو'],
|
||||
idleTitle: ['Your next opponent. Your own guild.', 'رقیب بعدیات؛ یا گیلد خودت.'],
|
||||
idleCopy: ['Enter an exact guild name to build a report from real AlbionBB battle data.', 'نام کامل یک گیلد را وارد کن تا گزارش آن از دادههای واقعی AlbionBB ساخته شود.'],
|
||||
step1: ['Find the guild', 'پیدا کردن گیلد'],
|
||||
step2: ['Connect the battles', 'کنار هم گذاشتن نبردها'],
|
||||
step3: ['Read the composition', 'شناخت ترکیب نیروها'],
|
||||
ready: ['Ready when you are', 'آمادهٔ تحلیل'],
|
||||
finding: ['Finding the exact guild…', 'در حال یافتن گیلد با نام دقیق…'],
|
||||
scanning: ['Scanning battle history', 'در حال خواندن تاریخچهٔ بتلها'],
|
||||
page: ['page', 'صفحه'],
|
||||
battles: ['battles', 'بتل'],
|
||||
details: ['Loading battle details', 'در حال دریافت جزئیات بتلها'],
|
||||
merging: ['Building combined reports', 'در حال ساخت گزارشهای ادغامشده'],
|
||||
notFound: ['No exact match. Check the full guild name on the Europe server.', 'گیلدی با این نام دقیق پیدا نشد. نام کامل گیلد را در سرور اروپا بررسی کن.'],
|
||||
ambiguous: ['Several guilds have this name. Select the intended guild:', 'چند گیلد با این نام پیدا شد. گیلد موردنظر را انتخاب کن:'],
|
||||
error: ['The report could not be completed. Check your connection and try again. No incomplete totals are shown.', 'گزارش کامل نشد. اتصال را بررسی کن و دوباره تلاش کن. آمار ناقص بهعنوان نتیجه نمایش داده نمیشود.'],
|
||||
proxyError: ['The report service is unavailable. On static hosting, configure the Albion API Worker described in the project README.', 'سرویس گزارش در دسترس نیست. برای میزبانی استاتیک، واسط API توضیحدادهشده در README پروژه باید فعال باشد.'],
|
||||
retry: ['Try again', 'تلاش دوباره'],
|
||||
cancelled: ['Analysis cancelled. Adjust the filters and try again.', 'تحلیل لغو شد. فیلترها را تنظیم کن و دوباره شروع کن.'],
|
||||
emptyTitle: ['No battles in this window.', 'در این بازه بتلی پیدا نشد.'],
|
||||
emptyCopy: ['Try a longer time window or lower the minimum total battle players.', 'بازهٔ زمانی را بیشتر کن یا حداقل تعداد کل بازیکنان بتل را کاهش بده.'],
|
||||
overview: ['Performance overview', 'نمای کلی عملکرد'],
|
||||
encounters: ['Encounters', 'درگیری'],
|
||||
original: ['Original battles', 'بتل اصلی'],
|
||||
killFame: ['Kill fame earned', 'کیل فیم کسبشده'],
|
||||
deathFame: ['Death fame', 'فیم تلفات'],
|
||||
netFame: ['Net fame', 'خالص فیم'],
|
||||
kills: ['Kills', 'کیل'],
|
||||
deaths: ['Deaths', 'مرگ'],
|
||||
kd: ['Kill / death ratio', 'نسبت کیل به مرگ'],
|
||||
attendance: ['Avg. guild attendance', 'میانگین حضور گیلد'],
|
||||
players: ['members', 'نفر'],
|
||||
totalPlayers: ['total battle players', 'بازیکن در کل بتل'],
|
||||
guildPlayers: ['guild members', 'عضو گیلد'],
|
||||
unique: ['Unique members', 'اعضای یکتا'],
|
||||
avgIp: ['Avg. recorded IP', 'میانگین IP ثبتشده'],
|
||||
trend: ['Fame across the campaign', 'روند فیم در این بازه'],
|
||||
trendHint: ['Kill fame per day · UTC', 'کیل فیم روزانه · زمان UTC'],
|
||||
composition: ['Anatomy of the guild', 'ترکیب نیروهای گیلد'],
|
||||
compositionHint: ['Role distribution across included encounters', 'سهم نقشها در درگیریهای انتخابشده'],
|
||||
appearances: ['member appearances', 'حضور بازیکن'],
|
||||
tanks: ['Tanks', 'تانک'], healers: ['Healers', 'هیلر'], supports: ['Supports', 'ساپورت'],
|
||||
ranges: ['Ranged DPS', 'رنج'], melees: ['Melee DPS', 'میلی'], battlemounts: ['Battle mounts', 'بتلمانت'], unknowns: ['Unknown', 'نامشخص'],
|
||||
weapons: ['Weapons of choice', 'سلاحهای منتخب'],
|
||||
weaponHint: ['Frequency in recorded compositions', 'دفعات حضور در composition ثبتشده'],
|
||||
allRoles: ['All roles', 'همهٔ نقشها'],
|
||||
noWeapons: ['No recorded weapons for this role.', 'برای این نقش سلاحی ثبت نشده است.'],
|
||||
leaderboard: ['People behind the performance', 'بازیکنان اثرگذار'],
|
||||
name: ['Player', 'بازیکن'], presence: ['Attendance', 'حضور'], heal: ['Healing', 'هیل'], damage: ['Damage', 'دمیج'],
|
||||
ledger: ['The battle ledger', 'دفتر نبردها'],
|
||||
ledgerHint: ['Open an encounter to inspect its composition.', 'هر درگیری را باز کن تا ترکیب نیروهایش را ببینی.'],
|
||||
searchBattle: ['Filter by other guild or battle ID', 'فیلتر نام گیلد دیگر یا شناسهٔ بتل'],
|
||||
recent: ['Most recent', 'جدیدترین'], mostFame: ['Highest kill fame', 'بیشترین کیل فیم'], mostPlayers: ['Largest guild attendance', 'بیشترین حضور گیلد'],
|
||||
report: ['Full report', 'گزارش کامل'], merged: ['combined', 'ادغامشده'], single: ['Single battle', 'تکبتل'],
|
||||
otherGuilds: ['Other guilds', 'سایر گیلدها'],
|
||||
methodology: ['How to read this report', 'راهنمای خواندن گزارش'],
|
||||
caveat: ['Attendance and composition reflect players recorded by AlbionBB, not a complete in-game mass. Composition is counted once per player per encounter; a member appearing in several encounters is counted in each. Weapon swaps during a fight may not all be represented. Kill fame alone does not establish victory or tactical quality.', 'حضور و ترکیب نیروها مربوط به بازیکنان ثبتشده در AlbionBB است و لزوماً تمام مس بازی نیست. در هر درگیری، هر بازیکن یکبار در composition شمرده میشود؛ حضور در چند درگیری چند بار محاسبه میشود. همهٔ تعویض سلاحها لزوماً در گزارش دیده نمیشوند. کیل فیم بهتنهایی معیار پیروزی یا کیفیت تاکتیکی نیست.'],
|
||||
filtered: ['Filters apply to every statistic below.', 'همهٔ آمار زیر بر اساس فیلترهای انتخابی است.'],
|
||||
loaded: ['Updated', 'دریافت داده'],
|
||||
partial: ['Some reports were unavailable. Retry to build a complete analysis.', 'بعضی گزارشها در دسترس نبودند. برای تحلیل کامل دوباره تلاش کن.'],
|
||||
export: ['Download CSV', 'دانلود CSV'],
|
||||
noMatch: ['No encounters match this search.', 'درگیری مطابق این جستوجو پیدا نشد.'],
|
||||
more: ['Show more encounters', 'نمایش درگیریهای بیشتر'],
|
||||
service: ['Source: AlbionBB · Europe · All battle times in UTC', 'منبع: AlbionBB · اروپا · تمام زمانهای بتل به UTC'],
|
||||
};
|
||||
export const textFor = lang => Object.fromEntries(Object.entries(messages).map(([key, pair]) => [key, pair[lang === 'fa' ? 1 : 0]]));
|
||||
@@ -0,0 +1,11 @@
|
||||
.intel-page{background:#101111;background-image:radial-gradient(ellipse at 95% 0,#78202d17,transparent 38%);--positive:#75c6a8;--negative:#ee8590}
|
||||
.intel-page button,.intel-page input,.intel-page select{font:inherit}.intel-page input,.intel-page select{color:var(--text);background:#111314;border:1px solid #ffffff25;border-radius:5px;min-height:46px;padding:10px 14px;outline:none}.intel-page input:focus,.intel-page select:focus{border-color:var(--accent);box-shadow:0 0 0 3px #e3485014}.intel-page input::placeholder{color:#747b7d}.intel-page select{font-size:12px;max-width:100%}.intel-page button:disabled{opacity:.5;cursor:wait}.intel-header{max-width:1380px;margin:auto;padding:25px 4%;display:flex;align-items:center;gap:36px;border-bottom:1px solid var(--line)}.intel-header .brand{margin-inline-end:auto}.intel-header .brand small{font-size:7px;letter-spacing:2px}.intel-back{font-size:12px;color:var(--muted)}.intel-back span{color:var(--accent);margin-inline-start:8px}.intel-main{max-width:1280px;margin:auto;padding:0 4% 70px}.intel-hero{position:relative;min-height:315px;padding:58px 0 50px;overflow:hidden}.intel-hero .eyebrow{margin-bottom:18px;font-size:9px}.intel-hero h1{font:600 clamp(58px,6.3vw,88px)/.97 var(--display);letter-spacing:-1.5px;margin:0}.intel-hero h1>span{color:#d65362}.intel-intro{max-width:510px;font-size:13px;color:var(--muted);line-height:1.9;margin:22px 0 8px}.intel-source{position:absolute;inset-inline-end:0;bottom:40px;display:flex;align-items:center;gap:9px;font-size:8px;letter-spacing:1.5px;color:#aaa6a0}.live-dot{width:5px;height:5px;background:#75c6a8;border-radius:50%;box-shadow:0 0 12px #75c6a855}.source-divider{margin:0 6px;color:#4a4a49}.intel-signal{position:absolute;inset-inline-end:6%;top:15px;width:275px;height:275px;display:grid;place-items:center;opacity:.8;pointer-events:none}.signal-orbit{position:absolute;inset:0;border:1px solid #df596024;border-radius:50%;background:repeating-conic-gradient(from 0deg,transparent 0deg 29.7deg,#c34c591c 29.7deg 30deg);mask-image:radial-gradient(transparent 0 46%,#000 47%)}.signal-orbit:after{content:'';position:absolute;width:10px;height:10px;border:1px solid #e34850;top:35px;right:33px;transform:rotate(45deg);box-shadow:0 0 20px #e3485060}.orbit-inner{inset:40px;border-style:dashed;transform:rotate(20deg)}.signal-center{font:700 100px/.8 var(--display);letter-spacing:-7px;color:#e8e1da}.signal-center>span{font-size:45px;letter-spacing:-2px;color:#d94d5a}.intel-signal>i{position:absolute;width:320px;height:1px;background:linear-gradient(90deg,transparent,#e3485050,transparent);transform:rotate(-35deg)}.intel-signal>b{position:absolute;bottom:66px;font-size:7px;letter-spacing:4px;color:#a47279;font-weight:400}.intel-controls{border:1px solid #ffffff26;border-top:2px solid #b13a47;background:linear-gradient(120deg,#1b1a1c,#151718);border-radius:8px;padding:24px 25px 0;box-shadow:0 20px 60px #0002}.intel-controls form{display:grid;grid-template-columns:1.5fr 1.05fr 1fr auto;gap:22px;align-items:end}.intel-controls label,.intel-controls legend{display:block;color:#c0bdb8;font-size:11px;margin-bottom:8px}.intel-controls input{width:100%}.search-field{position:relative}.search-field>span{position:absolute;left:13px;top:0;font:34px/46px var(--body);color:#8b6c72}.search-field input{padding-left:43px;font-size:15px}.period-field{padding:0;border:0;margin:0;min-width:0}.period-options{display:flex;gap:4px;border:1px solid #ffffff25;border-radius:5px;padding:4px;background:#111314;height:46px}.period-options label{position:relative;margin:0;flex:1;cursor:pointer}.period-options input{position:absolute;opacity:0;inset:0;min-height:0;cursor:pointer}.period-options span{display:block;text-align:center;border-radius:3px;font-size:15px;line-height:36px;color:#939696;white-space:nowrap}.period-options small{font-size:10px}.period-options input:checked+span{background:#543039;color:#ffe5e7;box-shadow:inset 0 0 0 1px #c55b6b40}.period-options input:focus-visible+span{outline:2px solid var(--accent)}.intel-submit{white-space:nowrap;border-radius:5px;gap:22px;min-height:46px;font-size:12px;padding:10px 20px}.intel-control-bottom{grid-column:1/-1;display:flex;align-items:center;gap:24px;border-top:1px solid var(--line);padding:15px 0;margin-top:0}.intel-controls .merge-control{display:flex;align-items:center;gap:9px;white-space:nowrap;font-size:10px;margin:0;cursor:pointer;position:relative}.merge-control input{position:absolute;opacity:0;width:30px;height:20px;min-height:0}.switch{width:28px;height:16px;border-radius:10px;background:#45474b;border:1px solid #ffffff20;position:relative}.switch:after{content:'';position:absolute;width:10px;height:10px;border-radius:50%;background:#cdc7c7;left:2px;top:2px;transition:transform .2s}.merge-control input:checked+.switch{background:#9d3543}.merge-control input:checked+.switch:after{transform:translateX(12px);background:#fff1f1}.merge-control input:focus-visible+.switch{outline:2px solid var(--accent)}.intel-control-bottom p{font-size:10px;line-height:1.7;color:#93918e;margin:0;border-inline-start:1px solid var(--line);padding-inline-start:20px}.intel-stLine truncated
|
||||
[dir=rtl] .intel-hero h1{font-family:'Vazirmatn',sans-serif;font-size:clamp(39px,4.3vw,60px);font-weight:800;line-height:1.65;letter-spacing:-2px}[dir=rtl] .intel-hero{padding-block:44px 55px}[dir=rtl] .intel-hero .eyebrow{margin-bottom:8px}[dir=rtl] .intel-source{letter-spacing:0}[dir=rtl] .intel-result-heading h2{font-size:43px;font-family:'Barlow Condensed','Vazirmatn',sans-serif}[dir=rtl] .intel-empty h2{font-family:'Vazirmatn',sans-serif;font-size:26px;line-height:1.9}[dir=rtl] .panel-heading h3{font-family:'Vazirmatn',sans-serif;font-size:19px;line-height:1.8}[dir=rtl] .intel-ledger>.panel-heading h3{font-size:24px}[dir=rtl] .intel-metric strong{text-align:end}[dir=rtl] .intel-header .brand{direction:ltr}[dir=rtl] .intel-metric>span{font-size:10px}[dir=rtl] .intel-status,[dir=rtl] .intel-control-bottom p{font-size:10px;line-height:2}
|
||||
@keyframes intel-pulse{50%{opacity:.35;box-shadow:0 0 15px #e3485077}}@media(prefers-reduced-motion:reduce){.intel-page *{animation:none!important;transition:none!important}}
|
||||
@media(min-width:1400px){.intel-main{padding-inline:0}.intel-header{padding-inline:3%}}
|
||||
@media(max-width:1080px){.intel-metrics{grid-template-columns:repeat(3,1fr)}.intel-analysis-grid{grid-template-columns:1fr 1fr}.intel-controls form{grid-template-columns:1.3fr 1fr 1fr}.intel-submit{grid-column:1/-1;justify-content:center}.intel-controls form{gap:18px}.intel-control-bottom{margin-top:-3px}.composition-body{gap:15px;flex-direction:column}.role-legend{width:100%}.role-legend>div{padding-block:5px}.fame-chart svg{height:300px}.intel-signal{inset-inline-end:0;width:240px;height:240px}.intel-intro{max-width:60%}.encounter>summary{grid-template-columns:75px 1fr 90px 60px 75px 15px;gap:15px}.intel-detail-grid{grid-template-columns:1fr 1.1fr}}
|
||||
@media(max-width:760px){.intel-header{padding:18px 5%;gap:15px}.intel-header .brand img{width:35px;height:35px}.intel-header .brand{gap:8px}.intel-back{font-size:10px}.intel-header .languages{font-size:10px}.intel-main{padding-inline:5%;padding-bottom:35px}.intel-hero{padding:37px 0 55px;min-height:0}.intel-hero h1{font-size:55px}.intel-intro{max-width:100%;font-size:12px}.intel-signal{display:none}.intel-source{position:static;margin-top:22px;font-size:7px}.intel-controls{padding:20px 18px 0}.intel-controls form{grid-template-columns:1fr 1fr;gap:18px 12px}.intel-search{grid-column:1/-1}.intel-controls label,.intel-controls legend{font-size:10px}.minimum-field input{height:46px}.intel-submit{font-size:12px}.intel-control-bottom{flex-direction:column;align-items:flex-start;gap:12px;padding-block:16px}.intel-control-bottom p{border:0;padding:0;font-size:10px}.intel-status{min-height:65px;font-size:9px}.intel-empty{padding:37px 20px}.intel-empty h2{font-size:29px}.intel-empty>p:not(.eyebrow){font-size:11px}.intel-steps{gap:14px;flex-wrap:wrap}.intel-steps span{font-size:9px}.intel-result-heading h2{font-size:36px}.intel-result-heading{align-items:flex-start;margin-top:12px}.intel-download{font-size:9px;padding:7px 9px}.intel-result-heading p:not(.eyebrow){font-size:10px}.intel-metrics{grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.intel-metric{padding:16px}.intel-metric strong{font-size:36px}.intel-analysis-grid,.intel-detail-grid{grid-template-columns:1fr;gap:16px}.intel-panel{padding:20px}.composition-body{flex-direction:row;gap:24px;min-height:190px}.role-donut{width:145px}.role-donut>div{inset:14px}.role-legend>div{font-size:10px}.role-legend small{font-size:8px;min-width:30px}.fame-chart svg{height:190px}.chart-scale{padding-bottom:25px}.chart-key{font-size:7px}.panel-heading h3{font-size:26px}.intel-footer{padding:20px 5%;flex-wrap:wrap;gap:8px 18px}.intel-footer p{flex-basis:100%;order:3;font-size:9px}.intel-footer a{margin-inline-start:auto}.encounter>summary{grid-template-columns:65px 1fr 85px 18px;gap:12px;padding:16px}.encounter-stat:not(.encounter-kd){grid-row:2}.encounter-stat:nth-child(3){grid-column:2}.encounter-stat:nth-child(4){grid-column:3}.encounter-kd{grid-column:3;grid-row:1;text-align:end}.encounter-expand{grid-column:4;grid-row:1}.encounter-date{grid-row:1/3}.encounter-name{grid-column:2;grid-row:1}.encounter-name h4{font-size:11px}.encounter-stat strong{font-size:23px}.encounter-stat small{font-size:8px}.encounter-type{font-size:7px}.encounter-weapons{grid-template-columns:repeat(2,minmax(0,1fr));gap:0 16px}.encounter-body{padding:16px}.ledger-controls select{min-width:120px;font-size:10px}.ledger-controls input{font-size:10px}.intel-detail-grid{margin-bottom:30px}[dir=rtl] .intel-hero h1{font-size:39px;letter-spacing:-1.5px;line-height:1.65}[dir=rtl] .intel-hero{padding-block:30px 35px}[dir=rtl] .intel-empty h2{font-size:22px}[dir=rtl] .panel-heading h3{font-size:18px}}
|
||||
@media(max-width:390px){.intel-back{display:none}.intel-controls form{grid-template-columns:1fr}.period-field,.minimum-field{grid-column:1/-1}.composition-body{gap:15px}.role-donut{width:120px}.role-donut>div{inset:12px}.role-donut strong{font-size:30px}.role-donut span{font-size:7px}.role-legend>div{font-size:9px}.intel-metric>span{font-size:9px}.intel-download{max-width:90px}.encounter-weapons{grid-template-columns:1fr}}
|
||||
|
||||
/* Keep branding anchored in both writing directions and numerical units together. */
|
||||
.intel-header .brand{margin-inline-end:0}.intel-back{margin-inline-start:auto}.intel-metric strong{white-space:nowrap;font-variant-numeric:tabular-nums}.intel-table td:nth-child(3){white-space:nowrap}.encounter-stat strong{unicode-bidi:plaintext}.encounter-detail-top{flex-wrap:wrap}@media(max-width:390px){.intel-header .languages{margin-inline-start:auto}}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
import { ROLES, normalizeName, ownGuild, groupReports, selectBattles, makeReport, summarize, mapLimit, scanListings } from './intel-core.js';
|
||||
import { textFor } from './intel-text.js';
|
||||
|
||||
const fa = document.documentElement.lang === 'fa', t = textFor(fa ? 'fa' : 'en');
|
||||
const locale = fa ? 'fa-IR' : 'en-GB', form = document.querySelector('#intel-form');
|
||||
const results = document.querySelector('#intel-results'), empty = document.querySelector('#intel-empty');
|
||||
const errorBox = document.querySelector('#intel-error'), status = document.querySelector('#intel-status');
|
||||
const cancel = document.querySelector('#intel-cancel'), cache = new Map();
|
||||
const apiBase = document.body.dataset.apiBase.replace(/\/$/, '');
|
||||
const e = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"', "'":''' }[c]));
|
||||
const number = (value, decimals = 0) => new Intl.NumberFormat(locale, { maximumFractionDigits: decimals }).format(value);
|
||||
const compact = value => {
|
||||
const unit = value >= 1e9 ? [1e9,'B'] : value >= 1e6 ? [1e6,'M'] : value >= 1e3 ? [1e3,'K'] : [1,''];
|
||||
return `${number(value / unit[0], unit[0] === 1 ? 0 : 1)}${unit[1]}`;
|
||||
};
|
||||
const full = value => new Intl.NumberFormat(locale).format(value);
|
||||
const date = value => new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric', timeZone: 'UTC' }).format(new Date(value));
|
||||
const clock = value => new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' }).format(new Date(value));
|
||||
const roleLabel = role => t[`${role}s`] || t.unknowns;
|
||||
const roleColor = { tank:'#d5a65c', healer:'#6ac5a3', support:'#9d8de2', range:'#71a8d8', melee:'#ed727c', battlemount:'#b8b6a7', unknown:'#646c73' };
|
||||
let controller, generation = 0, loaded, forcedGuild;
|
||||
|
||||
class ReportError extends Error {}
|
||||
async function api(path, query = {}, signal) {
|
||||
const url = `${apiBase}${path}${Object.keys(query).length ? `?${new URLSearchParams(query)}` : ''}`;
|
||||
const cached = cache.get(url);
|
||||
if (cached && Date.now() - cached.at < 120_000) return cached.data;
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
signal?.throwIfAborted();
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, { signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(35_000)]), headers: { Accept:'application/json' } });
|
||||
if (response.status === 404 || !response.headers.get('content-type')?.includes('application/json')) throw new ReportError(t.proxyError);
|
||||
if (!response.ok) throw Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
cache.set(url, { at:Date.now(), data });
|
||||
if (cache.size > 2500) cache.delete(cache.keys().next().value);
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (signal?.aborted || error instanceof ReportError || attempt === 2) throw error;
|
||||
await new Promise((resolve, reject) => {
|
||||
const done = () => { signal?.removeEventListener('abort', abort); resolve(); };
|
||||
const timer = setTimeout(done, 700 * (attempt + 1));
|
||||
const abort = () => { clearTimeout(timer); reject(signal.reason); };
|
||||
signal?.addEventListener('abort', abort, { once:true });
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
function progress(message, run) {
|
||||
if (run !== generation) return;
|
||||
document.querySelector('#status-text').textContent = message;
|
||||
}
|
||||
function saveQuery(config) {
|
||||
const query = new URLSearchParams({ guild:config.name, days:config.days, minimum:config.minimum, merge:config.merge ? '1' : '0' });
|
||||
history.replaceState(null, '', `${location.pathname}?${query}`);
|
||||
document.querySelectorAll('[data-intel-language]').forEach(a => { a.search = query.toString(); });
|
||||
}
|
||||
function showError(message) {
|
||||
errorBox.hidden = false;
|
||||
document.querySelector('#error-text').textContent = message;
|
||||
}
|
||||
async function analyze(event) {
|
||||
event?.preventDefault();
|
||||
if (!form.reportValidity()) return;
|
||||
controller?.abort();
|
||||
const run = ++generation;
|
||||
controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
const config = { name:form.elements.guild.value.trim(), days:Number(form.elements.days.value), minimum:Number(form.elements.minimum.value), merge:form.elements.merge.checked };
|
||||
saveQuery(config);
|
||||
results.hidden = true; empty.hidden = true; errorBox.hidden = true;
|
||||
document.querySelector('#guild-choices').replaceChildren();
|
||||
form.querySelector('[type=submit]').disabled = true;
|
||||
cancel.hidden = false; status.classList.add('is-loading');
|
||||
results.setAttribute('aria-busy','true');
|
||||
progress(t.finding, run);
|
||||
try {
|
||||
const candidates = await api('/guilds/search', { search:config.name }, signal);
|
||||
if (!Array.isArray(candidates)) throw Error('Invalid guild search');
|
||||
const exact = candidates.filter(g => normalizeName(g.Name) === normalizeName(config.name));
|
||||
if (!exact.length) throw new ReportError(t.notFound);
|
||||
if (forcedGuild && !exact.some(g => g.Id === forcedGuild)) forcedGuild = undefined;
|
||||
if (exact.length > 1 && !forcedGuild) {
|
||||
showError(t.ambiguous);
|
||||
document.querySelector('#intel-retry').hidden = true;
|
||||
const choices = document.querySelector('#guild-choices');
|
||||
for (const guild of exact) {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'guild-choice'; button.type = 'button'; button.textContent = `${guild.Name} · ${guild.Id}`;
|
||||
button.addEventListener('click', () => { forcedGuild = guild.Id; analyze(); }); choices.append(button);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const guild = exact.find(g => g.Id === forcedGuild) || exact[0];
|
||||
const until = Date.now(), since = until - config.days * 86_400_000;
|
||||
const listings = await scanListings(api, guild.Id, since, signal,
|
||||
(page, count) => progress(`${t.scanning} · ${t.page} ${number(page)} · ${number(count)} ${t.battles}`, run), config.minimum);
|
||||
let count = 0;
|
||||
const battles = await mapLimit(listings, 4, async row => {
|
||||
const detail = await api(`/battles/${row.albionId}`, {}, signal);
|
||||
if (detail.albionId !== row.albionId || !ownGuild(detail, guild.Id) || !Array.isArray(detail.players)) throw new ReportError(t.partial);
|
||||
progress(`${t.details} · ${number(++count)} / ${number(listings.length)}`, run);
|
||||
return detail;
|
||||
});
|
||||
const selected = selectBattles(battles, guild.Id, { since, until, minPlayers:config.minimum });
|
||||
const groups = groupReports(selected, guild.Id, config.merge);
|
||||
count = 0;
|
||||
const reports = await mapLimit(groups, 2, async group => {
|
||||
const combined = group.length > 1 ? await api('/battles/multi', { ids:group.map(b => b.albionId).join(',') }, signal) : null;
|
||||
if (combined) {
|
||||
const guildTotal = ownGuild(combined, guild.Id);
|
||||
for (const key of ['kills', 'deaths', 'killFame']) {
|
||||
if (guildTotal?.[key] !== group.reduce((sum, b) => sum + (ownGuild(b, guild.Id)[key] || 0), 0)) throw new ReportError(t.partial);
|
||||
}
|
||||
}
|
||||
progress(`${t.merging} · ${number(++count)} / ${number(groups.length)}`, run);
|
||||
return makeReport(group, combined, guild.Id);
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
if (run !== generation) return;
|
||||
loaded = { guild, config, reports, since, until, originalCount:selected.length };
|
||||
render(loaded);
|
||||
progress(`${guild.Name} · ${number(reports.length)} ${t.encounters} · ${t.loaded} ${clock(until)} UTC`, run);
|
||||
} catch (error) {
|
||||
if (run !== generation) return;
|
||||
controller.abort();
|
||||
const cancelled = error?.name === 'AbortError';
|
||||
if (cancelled) {
|
||||
empty.hidden = false; progress(t.cancelled, run);
|
||||
} else {
|
||||
showError(error instanceof ReportError ? error.message : t.error);
|
||||
progress(t.error, run);
|
||||
}
|
||||
} finally {
|
||||
if (run === generation) {
|
||||
status.classList.remove('is-loading'); cancel.hidden = true;
|
||||
form.querySelector('[type=submit]').disabled = false;
|
||||
results.setAttribute('aria-busy','false');
|
||||
if (!document.querySelector('#guild-choices').children.length) document.querySelector('#intel-retry').hidden = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function metric(label, value, foot = '', featured = false, exact) {
|
||||
return `<article class="intel-metric ${featured ? 'featured-metric' : ''}"><span>${e(label)}</span><strong dir="ltr" ${exact !== undefined ? `title="${e(full(exact))}"` : ''}>${e(value)}</strong><small>${foot}</small></article>`;
|
||||
}
|
||||
function render(data) {
|
||||
const { reports, guild, config } = data;
|
||||
if (!reports.length) {
|
||||
results.innerHTML = `<section class="intel-no-results"><p class="eyebrow">${e(guild.Name)} / ${config.days} ${e(t.days)}</p><h2>${e(t.emptyTitle)}</h2><p>${e(t.emptyCopy)}</p></section>`;
|
||||
results.hidden = false; return;
|
||||
}
|
||||
const s = summarize(reports);
|
||||
const roleTotal = Object.values(s.roles).reduce((sum, n) => sum + n, 0);
|
||||
const delta = s.killFame - s.deathFame;
|
||||
results.innerHTML = `
|
||||
<div class="intel-result-heading"><div><p class="eyebrow">${e(t.overview)}</p><h2><bdi>${e(guild.Name)}</bdi><span class="guild-region">EU</span></h2><p>${e(date(data.since))} — ${e(date(data.until))} · ${number(config.days)} ${e(t.days)} · ${number(config.minimum)}+ ${e(t.totalPlayers)}<br><span>${e(t.filtered)}</span></p></div><button class="intel-download" id="export-csv" type="button">↓ ${e(t.export)}</button></div>
|
||||
<div class="intel-metrics">
|
||||
${metric(t.killFame, compact(s.killFame), `${e(t.netFame)} <bdi class="${delta >= 0 ? 'positive' : 'negative'}">${delta >= 0 ? '+' : '−'}${e(compact(Math.abs(delta)))}</bdi>`, true, s.killFame)}
|
||||
${metric(t.encounters, number(reports.length), `${number(data.originalCount)} ${e(t.original)}`)}
|
||||
${metric(t.kd, s.deaths ? number(s.kills/s.deaths, 2) : s.kills ? '∞' : '—', `<span class="positive">${number(s.kills)}</span> ${e(t.kills)} / <span class="negative">${number(s.deaths)}</span> ${e(t.deaths)}`)}
|
||||
${metric(t.attendance, number(s.averageAttendance, 1), `${number(s.players.size)} ${e(t.unique)}`)}
|
||||
${metric(t.deathFame, compact(s.deathFame), `${number(s.deaths)} ${e(t.deaths)}`, false, s.deathFame)}
|
||||
${metric(t.avgIp, s.averageIp ? number(s.averageIp) : '—', `${number(s.ipCount)} ${e(t.appearances)}`)}
|
||||
</div>
|
||||
<div class="intel-analysis-grid"><section class="intel-panel trend-panel"><div class="panel-heading"><div><p class="eyebrow">01 / MOMENTUM</p><h3>${e(t.trend)}</h3><p>${e(t.trendHint)}</p></div><span class="chart-key"><i></i> ${e(t.killFame)}</span></div>${trend(s, data)}</section>
|
||||
<section class="intel-panel composition-panel"><div class="panel-heading"><div><p class="eyebrow">02 / COMPOSITION</p><h3>${e(t.composition)}</h3><p>${e(t.compositionHint)}</p></div></div><div class="composition-body">${donut(s.roles)}<div class="role-legend">${ROLES.filter(r => s.roles[r]).map(r => `<div><i style="--role:${roleColor[r]}"></i><span>${e(roleLabel(r))}</span><b>${number(s.roles[r])}</b><small>${number(s.roles[r]/roleTotal*100,1)}%</small></div>`).join('')}</div></div></section></div>
|
||||
<div class="intel-detail-grid"><section class="intel-panel weapons-panel"><div class="panel-heading"><div><p class="eyebrow">03 / ARSENAL</p><h3>${e(t.weapons)}</h3><p>${e(t.weaponHint)}</p></div><select id="weapon-role" aria-label="${e(t.allRoles)}"><option value="all">${e(t.allRoles)}</option>${ROLES.filter(r => r !== 'unknown').map(r => `<option value="${r}">${e(roleLabel(r))}</option>`).join('')}</select></div><div id="weapons-list"></div></section>
|
||||
<section class="intel-panel players-panel"><div class="panel-heading"><div><p class="eyebrow">04 / PEOPLE</p><h3>${e(t.leaderboard)}</h3></div><select id="player-sort" aria-label="${e(t.leaderboard)}">${['killFame','kills','attendance','heal','damage'].map(key => `<option value="${key}">${e(t[key === 'killFame' ? 'killFame' : key === 'attendance' ? 'presence' : key])}</option>`).join('')}</select></div><div id="player-list" class="intel-table-wrap"></div></section></div>
|
||||
<section class="intel-ledger"><div class="panel-heading"><div><p class="eyebrow">05 / ENCOUNTERS</p><h3>${e(t.ledger)}</h3><p>${e(t.ledgerHint)}</p></div><span class="ledger-count">${number(reports.length)}</span></div>
|
||||
<div class="ledger-controls"><input id="battle-search" type="search" placeholder="${e(t.searchBattle)}" aria-label="${e(t.searchBattle)}"><select id="battle-sort" aria-label="${e(t.ledger)}"><option value="recent">${e(t.recent)}</option><option value="fame">${e(t.mostFame)}</option><option value="players">${e(t.mostPlayers)}</option></select></div><div id="battle-list"></div><button type="button" id="more-battles" class="intel-more" hidden>${e(t.more)} ↓</button></section>`;
|
||||
results.hidden = false;
|
||||
const weaponSelect = document.querySelector('#weapon-role'), playerSelect = document.querySelector('#player-sort');
|
||||
const updateWeapons = () => { document.querySelector('#weapons-list').innerHTML = weaponList([...s.weapons.values()], weaponSelect.value); };
|
||||
weaponSelect.addEventListener('change', updateWeapons); updateWeapons();
|
||||
const updatePlayers = () => { document.querySelector('#player-list').innerHTML = playersTable([...s.players.values()], playerSelect.value); };
|
||||
playerSelect.addEventListener('change', updatePlayers); updatePlayers();
|
||||
let visible = 20;
|
||||
const updateBattles = () => {
|
||||
const search = normalizeName(document.querySelector('#battle-search').value);
|
||||
const sort = document.querySelector('#battle-sort').value;
|
||||
const filtered = reports.filter(r => !search || r.ids.some(id => String(id).includes(search)) || r.battle.guilds.some(g => normalizeName(g.name).includes(search)));
|
||||
filtered.sort((a,b) => sort === 'fame' ? b.guild.killFame - a.guild.killFame : sort === 'players' ? b.guild.players - a.guild.players : Date.parse(b.startedAt) - Date.parse(a.startedAt));
|
||||
document.querySelector('#battle-list').innerHTML = filtered.length ? filtered.slice(0,visible).map(r => battleRow(r, guild.Id)).join('') : `<p class="list-empty">${e(t.noMatch)}</p>`;
|
||||
document.querySelector('#more-battles').hidden = visible >= filtered.length;
|
||||
};
|
||||
for (const id of ['battle-search','battle-sort']) document.querySelector(`#${id}`).addEventListener(id === 'battle-search' ? 'input' : 'change', () => { visible = 20; updateBattles(); });
|
||||
document.querySelector('#more-battles').addEventListener('click', () => { visible += 20; updateBattles(); }); updateBattles();
|
||||
document.querySelector('#export-csv').addEventListener('click', exportCsv);
|
||||
}
|
||||
function trend(s, data) {
|
||||
const dates = [];
|
||||
for (let day = Date.parse(new Date(data.since).toISOString().slice(0,10)); day <= data.until; day += 86_400_000) dates.push(new Date(day).toISOString().slice(0,10));
|
||||
const max = Math.max(...s.daily.values(), 1), width = 800, height = 195, gap = 3, unit = width / dates.length;
|
||||
return `<div class="fame-chart"><div class="chart-scale"><span>${e(compact(max))}</span><span>${e(compact(max/2))}</span><span>0</span></div><svg viewBox="0 0 ${width} ${height+30}" role="img" aria-label="${e(t.trend)}"><defs><linearGradient id="fame-fill" x1="0" y1="0" x2="0" y2="1"><stop stop-color="#ed727c"/><stop offset="1" stop-color="#a42a39" stop-opacity=".35"/></linearGradient></defs>${[0,.5,1].map(f => `<line x1="0" y1="${f*height}" x2="800" y2="${f*height}" stroke="#ffffff12" stroke-dasharray="3 5"/>`).join('')}${dates.map((day,i) => {
|
||||
const value = s.daily.get(day) || 0, h = value / max * (height-12);
|
||||
return `<rect class="fame-bar" tabindex="0" role="img" aria-label="${e(date(day))}: ${e(full(value))}" x="${i*unit+gap/2}" y="${height-Math.max(h,2)}" width="${Math.max(unit-gap,2)}" height="${Math.max(h,2)}" rx="2" fill="${value ? 'url(#fame-fill)' : '#ffffff0a'}"><title>${e(date(day))} · ${e(full(value))} ${e(t.killFame)}</title></rect>`;
|
||||
}).join('')}<text x="0" y="220" fill="#a5a59d" font-size="13">${e(date(dates[0]))}</text><text x="800" y="220" text-anchor="end" fill="#a5a59d" font-size="13">${e(date(dates.at(-1)))}</text></svg></div>`;
|
||||
}
|
||||
function donut(roles) {
|
||||
const total = Object.values(roles).reduce((n,v) => n+v,0); let start = 0;
|
||||
const stops = ROLES.filter(r => roles[r]).map(r => { const end = start + roles[r]/total*100; const stop = `${roleColor[r]} ${start}% ${end}%`; start = end; return stop; });
|
||||
return `<div class="role-donut" style="background:conic-gradient(${stops.join(',') || '#333 0% 100%'})" role="img" aria-label="${e(t.compositionHint)}"><div><strong>${number(total)}</strong><span>${e(t.appearances)}</span></div></div>`;
|
||||
}
|
||||
const weaponNames = {
|
||||
'2H_MACE':'Heavy Mace', 'MAIN_MACE':'Mace', 'MAIN_MACE_CRYSTAL':'Dreadstorm Monarch', '2H_MACE_MORGANA':'Camlann Mace', '2H_DUALMACE_AVALON':'Oathkeepers',
|
||||
'MAIN_HAMMER':'Hammer', '2H_HAMMER':'Great Hammer', '2H_HAMMER_UNDEAD':'Tombhammer', '2H_HAMMER_AVALON':'Hand of Justice',
|
||||
'MAIN_NATURESTAFF':'Nature Staff', '2H_NATURESTAFF':'Great Nature Staff', '2H_NATURESTAFF_HELL':'Blight Staff', 'MAIN_NATURESTAFF_AVALON':'Ironroot Staff',
|
||||
'MAIN_HOLYSTAFF':'Holy Staff', 'MAIN_HOLYSTAFF_AVALON':'Hallowfall', '2H_HOLYSTAFF':'Great Holy Staff', '2H_HOLYSTAFF_HELL':'Fallen Staff',
|
||||
'2H_LONGBOW':'Longbow', '2H_BOW_AVALON':'Mistpiercer', '2H_CROSSBOW_CANNON_AVALON':'Energy Shaper', 'MAIN_DAGGER_HELL':'Demonfang',
|
||||
'2H_DUALSCIMITAR_UNDEAD':'Galatine Pair', '2H_FIRE_RINGPAIR_AVALON':'Dawnsong', '2H_HALBERD':'Halberd', '2H_AXE_AVALON':'Realmbreaker',
|
||||
'2H_KNUCKLES_SET3':'Spiked Gauntlets', '2H_KNUCKLES_HELL':'Hellfire Hands', '2H_SHAPESHIFTER_KEEPER':'Primal Staff', '2H_SHAPESHIFTER_AVALON':'Lightcaller',
|
||||
'2H_ENIGMATICSTAFF':'Enigmatic Staff', '2H_ARCANESTAFF_HELL':'Occult Staff', '2H_ARCANESTAFF':'Great Arcane Staff', 'MAIN_ARCANESTAFF':'Arcane Staff',
|
||||
};
|
||||
function weaponName(name) { return weaponNames[name] || name.replace(/^T\d+_/, '').replace(/^(MAIN_|2H_|MOUNT_)/, '').replaceAll('_',' ').toLowerCase().replace(/\b\w/g, c => c.toUpperCase()); }
|
||||
function weaponList(weapons, role = 'all', limit = 12) {
|
||||
const items = weapons.filter(w => role === 'all' || w.role === role).sort((a,b) => b.count-a.count).slice(0,limit);
|
||||
const max = Math.max(...items.map(w => w.count),1);
|
||||
return items.length ? items.map(w => `<div class="weapon-row"><img src="https://render.albiononline.com/v1/item/${encodeURIComponent(w.type)}.png?quality=${Number(w.quality)||1}&size=80" width="42" height="42" alt="" loading="lazy"><div><div class="weapon-label"><span dir="ltr">${e(weaponName(w.name))}</span><strong>${number(w.count)}</strong></div><div class="weapon-track"><i style="width:${w.count/max*100}%;--role:${roleColor[w.role] || roleColor.unknown}"></i></div><small>${e(roleLabel(w.role))}</small></div></div>`).join('') : `<p class="list-empty">${e(t.noWeapons)}</p>`;
|
||||
}
|
||||
function playersTable(players, sort = 'killFame') {
|
||||
const metricLabel = sort === 'attendance' ? t.presence : t[sort];
|
||||
return `<table class="intel-table"><thead><tr><th>#</th><th>${e(t.name)}</th><th>${e(metricLabel)}</th><th>${e(t.kills)} / ${e(t.deaths)}</th></tr></thead><tbody>${players.sort((a,b) => b[sort]-a[sort] || a.name.localeCompare(b.name)).slice(0,10).map((p,i) => `<tr><td>${new Intl.NumberFormat(locale,{minimumIntegerDigits:2}).format(i+1)}</td><td><bdi>${e(p.name)}</bdi><small>${number(p.attendance)} ${e(t.encounters)}</small></td><td title="${e(full(p[sort]))}"><bdi>${e(['attendance','kills'].includes(sort) ? number(p[sort]) : compact(p[sort]))}</bdi></td><td><span class="positive">${number(p.kills)}</span> <span class="muted">/</span> ${number(p.deaths)}</td></tr>`).join('')}</tbody></table>`;
|
||||
}
|
||||
function battleRow(report, guildId) {
|
||||
const other = report.battle.guilds.filter(g => g.albionId !== guildId).sort((a,b) => b.players-a.players);
|
||||
const opponents = other.slice(0,3).map(g => g.name).join(' / ');
|
||||
const s = summarize([report]);
|
||||
return `<details class="encounter"><summary><div class="encounter-date"><strong>${e(date(report.startedAt))}</strong><small dir="ltr">${clock(report.startedAt)} UTC</small></div><div class="encounter-name"><span class="encounter-type ${report.ids.length > 1 ? 'is-merged' : ''}">${report.ids.length > 1 ? `${number(report.ids.length)} ${e(t.merged)}` : e(t.single)}</span><h4><bdi>${e(opponents || '—')}</bdi></h4><small>${e(t.otherGuilds)}</small></div><div class="encounter-stat"><strong title="${e(full(report.guild.killFame))}">${e(compact(report.guild.killFame))}</strong><small>${e(t.killFame)}</small></div><div class="encounter-stat"><strong>${number(report.guild.players)}</strong><small>${e(t.guildPlayers)}</small></div><div class="encounter-stat encounter-kd"><strong><span class="positive">${number(report.guild.kills)}</span><span class="muted"> / </span>${number(report.guild.deaths)}</strong><small>${e(t.kills)} / ${e(t.deaths)}</small></div><span class="encounter-expand" aria-hidden="true">+</span></summary><div class="encounter-body"><div class="encounter-detail-top"><span dir="ltr">${clock(report.startedAt)} — ${clock(report.finishedAt)} UTC</span><span>${number(report.battle.totalPlayers)} ${e(t.totalPlayers)}</span><a href="${e(report.url)}" target="_blank" rel="noopener noreferrer">${e(t.report)} ↗</a></div><div class="encounter-role-strip">${ROLES.filter(r => s.roles[r]).map(r => `<span><i style="--role:${roleColor[r]}"></i>${e(roleLabel(r))}<b>${number(s.roles[r])}</b></span>`).join('')}</div><div class="encounter-weapons">${weaponList([...s.weapons.values()], 'all', 100)}</div><div class="encounter-ids">${report.ids.map(id => `<a href="https://europe.albionbb.com/battles/${id}" target="_blank" rel="noopener noreferrer">#${id} ↗</a>`).join('')}</div></div></details>`;
|
||||
}
|
||||
function exportCsv() {
|
||||
if (!loaded) return;
|
||||
const escape = value => `"${String(value ?? '').replace(/^[=+@\-\t\r]/, "'$&").replaceAll('"','""')}"`;
|
||||
const rows = [['Guild','Start UTC','End UTC','Battle IDs','Guild members','Kills','Deaths','Kill fame','Death fame','Report'], ...loaded.reports.map(r => [loaded.guild.Name,r.startedAt,r.finishedAt,r.ids.join(','),r.guild.players,r.guild.kills,r.guild.deaths,r.guild.killFame,r.players.reduce((sum,p) => sum+(p.deathFame||0),0),r.url])];
|
||||
const blob = new Blob(['\uFEFF', rows.map(row => row.map(escape).join(',')).join('\r\n')], { type:'text/csv;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob), a = document.createElement('a');
|
||||
a.href = url; a.download = `guild-intelligence-${loaded.config.days}d.csv`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
form.addEventListener('submit', analyze);
|
||||
cancel.addEventListener('click', () => controller?.abort());
|
||||
document.querySelector('#intel-retry').addEventListener('click', () => analyze());
|
||||
const query = new URLSearchParams(location.search);
|
||||
form.elements.guild.value = query.get('guild') || '';
|
||||
if (['7','30','60'].includes(query.get('days'))) form.elements.days.value = query.get('days');
|
||||
if (/^\d+$/.test(query.get('minimum') || '') && Number(query.get('minimum')) >= 1 && Number(query.get('minimum')) <= 1000) form.elements.minimum.value = query.get('minimum');
|
||||
if (query.get('merge') === '0') form.elements.merge.checked = false;
|
||||
document.querySelectorAll('[data-intel-language]').forEach(a => { a.search = query.toString(); });
|
||||
if (form.elements.guild.value) analyze();
|
||||
@@ -0,0 +1,100 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { selectBattles, groupReports, makeReport, summarize, scanListings, mapLimit, normalizeName } from '../src/intel-core.js';
|
||||
import { proxyAlbion, upstreamUrl } from '../scripts/albion-proxy.mjs';
|
||||
import { renderIntel } from '../scripts/render-intel.mjs';
|
||||
|
||||
const battle = (id, minute = 0, options = {}) => ({
|
||||
albionId:id, startedAt:new Date(Date.UTC(2026,9,20,10,minute)).toISOString(), finishedAt:new Date(Date.UTC(2026,9,20,10,minute+2)).toISOString(),
|
||||
totalPlayers:options.total ?? 40,
|
||||
guilds:[{ albionId:'guild', name:'OneUP', players:4, kills:2, deaths:1, killFame:1000 }, { albionId:options.enemy || 'enemy', name:'Enemy', players:36 }],
|
||||
players:['a','b','c','d'].map(name => ({ name,guildName:'OneUP',role:'healer',kills:0,deaths:0,killFame:250,deathFame:50,ip:1500,weapon:{name:'MAIN_HOLYSTAFF',type:'T6_MAIN_HOLYSTAFF'} })),
|
||||
});
|
||||
test('minimum attendance is ALL players, inclusive, and applied before merging', () => {
|
||||
const rows = [battle(1,0,{total:39}),battle(2,1,{total:40}),battle(3,2,{total:41})];
|
||||
const chosen = selectBattles(rows,'guild',{since:Date.UTC(2026,9,20),until:Date.UTC(2026,9,21),minPlayers:40});
|
||||
assert.deepEqual(chosen.map(b => b.albionId),[2,3]);
|
||||
assert.equal(chosen[0].guilds[0].players,4);
|
||||
assert.deepEqual(groupReports(chosen,'guild')[0].map(b=>b.albionId),[2,3]);
|
||||
});
|
||||
test('rolling date boundaries include the exact start and exclude older or future records', () => {
|
||||
const row = battle(1), since = Date.parse(row.startedAt), until = since+1000;
|
||||
const before = {...row,albionId:2,startedAt:new Date(since-1).toISOString()};
|
||||
const future = {...row,albionId:3,startedAt:new Date(until+1).toISOString()};
|
||||
assert.deepEqual(selectBattles([before,row,future],'guild',{since,until,minPlayers:1}),[row]);
|
||||
});
|
||||
test('merge requires time, roster AND other-team continuity and supports disabled merging', () => {
|
||||
const a=battle(1),b=battle(2,10),c=battle(3,15,{enemy:'unrelated'}),d=battle(4,40);
|
||||
assert.deepEqual(groupReports([d,b,c,a,a],'guild').map(g=>g.map(b=>b.albionId)),[[1,2],[3],[4]]);
|
||||
assert.equal(groupReports([a,b],'guild',false).length,2);
|
||||
b.players=b.players.map(p=>({...p,name:`other-${p.name}`}));
|
||||
assert.equal(groupReports([a,b],'guild').length,2);
|
||||
});
|
||||
test('summary uses merged roster once, maintains exact fame and recovers end time from originals', () => {
|
||||
const a=battle(1),b=battle(2,10),combined=battle(1);
|
||||
combined.finishedAt=a.finishedAt;
|
||||
combined.guilds[0]={...combined.guilds[0],kills:4,deaths:2,killFame:2000};
|
||||
const report=makeReport([a,b],combined,'guild');
|
||||
assert.equal(report.finishedAt,b.finishedAt);
|
||||
assert.match(report.url,/multi\?ids=1,2/);
|
||||
const s=summarize([report]);
|
||||
assert.equal(s.roles.healer,4);assert.equal(s.killFame,2000);assert.equal(s.deathFame,200);
|
||||
assert.equal(s.averageAttendance,4);assert.equal(s.averageIp,1500);assert.equal(s.players.size,4);
|
||||
assert.equal([...s.weapons.values()][0].count,4);
|
||||
combined.players[0].ip=0;
|
||||
assert.equal(summarize([report]).averageIp,1500);
|
||||
});
|
||||
test('scan paginates through a date boundary and sends total-player filter to API', async () => {
|
||||
const recent=Array.from({length:20},(_,i)=>battle(i+1,i));
|
||||
const old={...battle(21),startedAt:'2026-01-01T00:00:00Z'};
|
||||
const calls=[];
|
||||
const rows=await scanListings(async(path,query)=>{
|
||||
calls.push(query);assert.equal(path,'/battles');assert.equal(query.minPlayers,40);assert.equal(query.minGuildPlayers,1);
|
||||
return query.page===1?recent:[old];
|
||||
},'guild',Date.UTC(2026,9,19),undefined,()=>{},40);
|
||||
assert.equal(calls.length,2);assert.equal(rows.length,20);
|
||||
await assert.rejects(scanListings(async()=>recent,'guild',0),/Pagination stopped advancing/);
|
||||
});
|
||||
test('battle-mount composition counts the mount instead of the rider weapon', () => {
|
||||
const b=battle(1);
|
||||
b.players[0]={...b.players[0],role:'battlemount',mount:'T8_MOUNT_MAMMOTH_BATTLE'};
|
||||
const s=summarize([makeReport([b],null,'guild')]);
|
||||
assert.equal(s.roles.battlemount,1);
|
||||
assert.equal(s.weapons.get('battlemount:T8_MOUNT_MAMMOTH_BATTLE').count,1);
|
||||
assert.equal(s.weapons.get('healer:MAIN_HOLYSTAFF').count,3);
|
||||
});
|
||||
test('bounded concurrency preserves order and propagates failures', async () => {
|
||||
let active=0,peak=0;
|
||||
const out=await mapLimit([1,2,3,4,5],2,async n=>{
|
||||
peak=Math.max(peak,++active);await new Promise(resolve=>setTimeout(resolve,5));active--;return n*2;
|
||||
});
|
||||
assert.deepEqual(out,[2,4,6,8,10]);assert.equal(peak,2);
|
||||
await assert.rejects(mapLimit([1,2],1,async()=>{throw Error('failed report');}),/failed report/);
|
||||
});
|
||||
test('proxy only permits public whitelisted read endpoints and strips browser headers', async () => {
|
||||
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/https://evil.test'));
|
||||
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles?url=https://evil.test'));
|
||||
assert.throws(()=>upstreamUrl('https://oneup.test/api/albion/battles/multi?ids=1,evil'));
|
||||
assert.equal(upstreamUrl('https://oneup.test/api/albion/guilds/search?search=OneUP').hostname,'api.albionbb.com');
|
||||
const request=new Request('https://oneup.test/api/albion/battles/123',{headers:{Authorization:'private',Cookie:'private'}});
|
||||
const result=await proxyAlbion(request,async(url,options)=>{
|
||||
assert.equal(url.href,'https://api.albionbb.com/eu/battles/123');
|
||||
assert.deepEqual(options.headers,{Accept:'application/json'});
|
||||
return Response.json({albionId:123});
|
||||
});
|
||||
assert.deepEqual(await result.json(),{albionId:123});
|
||||
assert.equal((await proxyAlbion(new Request(request.url,{method:'POST'}))).status,405);
|
||||
assert.equal((await proxyAlbion(request,async()=>new Response('',{status:429}))).status,429);
|
||||
});
|
||||
test('bilingual page has accessible filters, correct total-player copy and escaped configuration', () => {
|
||||
assert.equal(normalizeName(' OneUP '),'oneup');
|
||||
for(const lang of ['en','fa']){
|
||||
const html=renderIntel(lang,'https://oneup.test','/api/albion');
|
||||
assert.match(html,new RegExp(`<html lang="${lang}" dir="${lang==='fa'?'rtl':'ltr'}">`));
|
||||
assert.match(html,/value="7" checked/);assert.match(html,/value="30"/);assert.match(html,/value="60"/);
|
||||
assert.match(html,/aria-live="polite"/);assert.match(html,/id="min-help"/);
|
||||
assert.ok(!html.includes('undefined'));
|
||||
}
|
||||
assert.match(renderIntel('en','https://oneup.test'),/All guilds combined, before merging/);
|
||||
assert.match(renderIntel('fa','https://oneup.test'),/مجموع بازیکنان همهٔ گیلدها/);
|
||||
});
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { proxyAlbion } from './scripts/albion-proxy.mjs';
|
||||
|
||||
export default {
|
||||
async fetch(request, env) {
|
||||
const url = new URL(request.url);
|
||||
if (url.pathname.startsWith('/api/albion/')) {
|
||||
// An optional separately hosted API only shares public reports with the configured site.
|
||||
const origin = request.headers.get('Origin');
|
||||
const allowed = !origin || origin === url.origin || origin === env.SITE_ORIGIN;
|
||||
if (!allowed) return new Response('Forbidden', { status: 403 });
|
||||
const response = await proxyAlbion(request);
|
||||
if (origin && origin === env.SITE_ORIGIN) {
|
||||
response.headers.set('Access-Control-Allow-Origin', origin);
|
||||
response.headers.set('Vary', 'Origin');
|
||||
}
|
||||
return response;
|
||||
}
|
||||
return env.ASSETS.fetch(request);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "oneup-guild",
|
||||
"main": "worker.mjs",
|
||||
"compatibility_date": "2026-10-20",
|
||||
"assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/albion/*"] }
|
||||
}
|
||||
Reference in new issue
Block a user