Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 19s
CI / Tests (Linux, race detector) (push) Successful in 35s
CI / Dependency audit (push) Successful in 16s
Release / ci (push) Successful in 35s
Release / Build image (arm64) (push) Successful in 51s
Release / Build image (amd64) (push) Successful in 1m11s
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Skipped
A new console interface (side rail, seven pages, opening sentence and active slice on every page, IP drawer, light and dark design tokens); a Geography page that drills from the world to a country's regions and cities; a Live page drawing attacks as arcs on a flat map or a globe. Backend: GET /api/v1/geo, GET /api/v1/live/recent, host/src/dst on live events, --location, a strict static file pattern, and live federation through GET /api/v1/peer/stream (peer token only, bounded and sanitized relay on the hub). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
681 lines
33 KiB
JavaScript
681 lines
33 KiB
JavaScript
/* Urutau - página Geografia: mapa coroplético, zoom em país, estados e cidades.
|
||
Todos os dados externos (cidade, região, AS) entram só via textContent. */
|
||
(function () {
|
||
'use strict';
|
||
var U = window.Urutau;
|
||
if (!U || typeof U.registerPage !== 'function') return;
|
||
|
||
// ---------------------------------------------------------------- i18n
|
||
U.registerI18n({
|
||
en: {
|
||
'geo.title': 'Geography',
|
||
'geo.world': 'World',
|
||
'geo.nav': 'Location path',
|
||
'geo.back': 'Back',
|
||
'geo.back.hint': 'Back (Esc)',
|
||
'geo.map.label': 'Map of attack origins. Use the list to choose a country.',
|
||
'geo.map.country.label': 'Map of {country} with the cities that attack the most',
|
||
'geo.lead.world': '{events} from {ips} across {countries}, in the last {range}; {top} leads with {pct}.',
|
||
'geo.lead.country': '{country} originated {events} from {ips} in the last {range}; {region} leads with {pct}.',
|
||
'geo.lead.country.flat': '{country} originated {events} from {ips} in the last {range}.',
|
||
'geo.lead.region': '{region} ({country}) originated {events} from {ips} in the last {range}; {city} leads with {pct}.',
|
||
'geo.lead.region.flat': '{region} ({country}) originated {events} from {ips} in the last {range}.',
|
||
'geo.lead.empty': 'No geolocated attacks in the last {range}.',
|
||
'geo.lead.empty.country': 'No attacks from {country} in the last {range}.',
|
||
'geo.u.events.one': '{n} event', 'geo.u.events.other': '{n} events',
|
||
'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs',
|
||
'geo.u.countries.one': '{n} country', 'geo.u.countries.other': '{n} countries',
|
||
'geo.range.1h': 'hour', 'geo.range.24h': '24 hours', 'geo.range.7d': '7 days',
|
||
'geo.legend': 'Events per country (log scale)',
|
||
'geo.tip.events': 'Events', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostile',
|
||
'geo.tip.region': 'Region',
|
||
'geo.countries': 'Countries',
|
||
'geo.regions': 'States / regions',
|
||
'geo.cities': 'Cities',
|
||
'geo.cats': 'Attack categories',
|
||
'geo.ips': 'Top IPs',
|
||
'geo.unknown': 'Unknown',
|
||
'geo.all_regions': 'All regions',
|
||
'geo.pick': 'Open {name}: {events}',
|
||
'geo.pick.region': 'Filter by {name}: {events}',
|
||
'geo.city.pick': 'Filter by region {name}',
|
||
'geo.nocoords.one': '{n} city has no coordinates and is not on the map.', 'geo.nocoords.other': '{n} cities have no coordinates and are not on the map.',
|
||
'geo.empty': 'Nothing to show for this range.',
|
||
'geo.empty.list': 'No data.',
|
||
'geo.loading': 'Loading…',
|
||
'geo.error': 'Could not load geography data.',
|
||
'geo.retry': 'Try again',
|
||
'geo.level.hostile': 'hostile', 'geo.level.suspicious': 'suspicious', 'geo.level.clean': 'clean', 'geo.level.low': 'low', 'geo.level.unknown': 'unknown',
|
||
'geo.score': 'score {n}',
|
||
'geo.open_ip': 'Open details of {ip}',
|
||
'geo.hostile_suspicious': '{h} hostile, {s} suspicious',
|
||
'geo.cat.notfound': 'not found', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'brute force',
|
||
'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'SSH failures', 'geo.cat.ssh-probe': 'SSH probe', 'geo.cat.ban': 'ban'
|
||
},
|
||
'pt-BR': {
|
||
'geo.title': 'Geografia',
|
||
'geo.world': 'Mundo',
|
||
'geo.nav': 'Caminho da localização',
|
||
'geo.back': 'Voltar',
|
||
'geo.back.hint': 'Voltar (Esc)',
|
||
'geo.map.label': 'Mapa das origens dos ataques. Use a lista para escolher um país.',
|
||
'geo.map.country.label': 'Mapa de {country} com as cidades que mais atacam',
|
||
'geo.lead.world': '{events} de {ips} em {countries}, nas últimas {range}; {top} lidera com {pct}.',
|
||
'geo.lead.country': '{country} originou {events} de {ips} nas últimas {range}; {region} lidera com {pct}.',
|
||
'geo.lead.country.flat': '{country} originou {events} de {ips} nas últimas {range}.',
|
||
'geo.lead.region': '{region} ({country}) originou {events} de {ips} nas últimas {range}; {city} lidera com {pct}.',
|
||
'geo.lead.region.flat': '{region} ({country}) originou {events} de {ips} nas últimas {range}.',
|
||
'geo.lead.empty': 'Nenhum ataque geolocalizado nas últimas {range}.',
|
||
'geo.lead.empty.country': 'Nenhum ataque de {country} nas últimas {range}.',
|
||
'geo.u.events.one': '{n} evento', 'geo.u.events.other': '{n} eventos',
|
||
'geo.u.ips.one': '{n} IP', 'geo.u.ips.other': '{n} IPs',
|
||
'geo.u.countries.one': '{n} país', 'geo.u.countries.other': '{n} países',
|
||
'geo.range.1h': 'hora', 'geo.range.24h': '24 horas', 'geo.range.7d': '7 dias',
|
||
'geo.legend': 'Eventos por país (escala log)',
|
||
'geo.tip.events': 'Eventos', 'geo.tip.ips': 'IPs', 'geo.tip.hostile': 'Hostis',
|
||
'geo.tip.region': 'Região',
|
||
'geo.countries': 'Países',
|
||
'geo.regions': 'Estados / regiões',
|
||
'geo.cities': 'Cidades',
|
||
'geo.cats': 'Categorias de ataque',
|
||
'geo.ips': 'IPs que mais atacam',
|
||
'geo.unknown': 'Desconhecido',
|
||
'geo.all_regions': 'Todas as regiões',
|
||
'geo.pick': 'Abrir {name}: {events}',
|
||
'geo.pick.region': 'Filtrar por {name}: {events}',
|
||
'geo.city.pick': 'Filtrar pela região {name}',
|
||
'geo.nocoords.one': '{n} cidade sem coordenadas não aparece no mapa.', 'geo.nocoords.other': '{n} cidades sem coordenadas não aparecem no mapa.',
|
||
'geo.empty': 'Nada para mostrar neste período.',
|
||
'geo.empty.list': 'Sem dados.',
|
||
'geo.loading': 'Carregando…',
|
||
'geo.error': 'Não foi possível carregar os dados de geografia.',
|
||
'geo.retry': 'Tentar de novo',
|
||
'geo.level.hostile': 'hostil', 'geo.level.suspicious': 'suspeito', 'geo.level.clean': 'limpo', 'geo.level.low': 'baixo', 'geo.level.unknown': 'desconhecido',
|
||
'geo.score': 'pontuação {n}',
|
||
'geo.open_ip': 'Abrir detalhes de {ip}',
|
||
'geo.hostile_suspicious': '{h} hostis, {s} suspeitos',
|
||
'geo.cat.notfound': 'não encontrado', 'geo.cat.scanner': 'scanner', 'geo.cat.bruteforce': 'força bruta',
|
||
'geo.cat.exploit': 'exploit', 'geo.cat.ssh-fail': 'falhas SSH', 'geo.cat.ssh-probe': 'sondagem SSH', 'geo.cat.ban': 'banimento'
|
||
}
|
||
});
|
||
|
||
// ---------------------------------------------------------------- helpers
|
||
var NS = 'http://www.w3.org/2000/svg';
|
||
var CAT_CLASS = { notfound: 1, scanner: 1, bruteforce: 1, exploit: 1, 'ssh-fail': 1, 'ssh-probe': 1, ban: 1 };
|
||
var LEVELS = { hostile: 1, suspicious: 1, clean: 1, low: 1, unknown: 1 };
|
||
var RANGES = { '1h': 1, '24h': 1, '7d': 1 };
|
||
var LAT_TOP = 84, LAT_SPAN = 142;
|
||
|
||
function t(k, v) { return U.t(k, v); }
|
||
function h(tag, cls, text) {
|
||
var e = document.createElement(tag);
|
||
if (cls) e.className = cls;
|
||
if (text != null) e.textContent = text;
|
||
return e;
|
||
}
|
||
function sv(tag, attrs) {
|
||
var e = document.createElementNS(NS, tag);
|
||
if (attrs) for (var k in attrs) e.setAttribute(k, attrs[k]);
|
||
return e;
|
||
}
|
||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||
function nf(n) {
|
||
try { if (U.fmt && U.fmt.num) return U.fmt.num(n); } catch (e) { /* fallback */ }
|
||
return new Intl.NumberFormat(lang).format(n);
|
||
}
|
||
function pct(x) { return Math.round(x * 100) + '%'; }
|
||
function unit(kind, n) { return t('geo.u.' + kind + (n === 1 ? '.one' : '.other'), { n: nf(n) }); }
|
||
function flagOf(cc) { try { return (U.fmt && U.fmt.flag && U.fmt.flag(cc)) || ''; } catch (e) { return ''; } }
|
||
var dn = null, dnLang = '';
|
||
function countryName(cc) {
|
||
try {
|
||
if (!dn || dnLang !== lang) { dn = new Intl.DisplayNames([lang], { type: 'region' }); dnLang = lang; }
|
||
return dn.of(cc) || cc;
|
||
} catch (e) { return cc; }
|
||
}
|
||
function regionName(r) { return r ? r : t('geo.unknown'); }
|
||
function catLabel(c) { var k = 'geo.cat.' + c, v = t(k); return v && v !== k ? v : c; }
|
||
function catCls(c) { return CAT_CLASS[c] ? 'geo-c-' + c : 'geo-c-other'; }
|
||
function rangeLabel(r) { return t('geo.range.' + (RANGES[r] ? r : '24h')); }
|
||
function sum(o) { var s = 0; for (var k in o) s += o[k]; return s; }
|
||
|
||
// ---------------------------------------------------------------- geometry
|
||
var world = null, bboxCache = {};
|
||
function projX(lon) { return (lon + 180) / 360 * world.w; }
|
||
function projY(lat) { return (LAT_TOP - lat) / LAT_SPAN * world.h; }
|
||
|
||
// Bbox of a country's path: main land masses only (drops far-away small islands).
|
||
function bboxOf(cc) {
|
||
if (bboxCache[cc]) return bboxCache[cc];
|
||
var d = world.paths[cc];
|
||
if (!d) return null;
|
||
var re = /([MmLlzZ])|(-?\d+(?:\.\d+)?)/g, m, cmd = '', nums = [], subs = [], cur = null, cx = 0, cy = 0, sx = 0, sy = 0;
|
||
function flush() {
|
||
for (var i = 0; i + 1 < nums.length; i += 2) {
|
||
if (cmd === 'M' && i === 0) { cx = nums[i]; cy = nums[i + 1]; sx = cx; sy = cy; cur = [cx, cy, cx, cy]; subs.push(cur); }
|
||
else { if (cmd === 'l' || cmd === 'm') { cx += nums[i]; cy += nums[i + 1]; } else { cx = nums[i]; cy = nums[i + 1]; }
|
||
if (cur) { if (cx < cur[0]) cur[0] = cx; if (cy < cur[1]) cur[1] = cy; if (cx > cur[2]) cur[2] = cx; if (cy > cur[3]) cur[3] = cy; } }
|
||
}
|
||
nums = [];
|
||
}
|
||
while ((m = re.exec(d))) {
|
||
if (m[1]) { flush(); cmd = m[1]; if (cmd === 'z' || cmd === 'Z') { cx = sx; cy = sy; } }
|
||
else nums.push(parseFloat(m[2]));
|
||
}
|
||
flush();
|
||
var maxA = 0;
|
||
subs.forEach(function (b) { var a = (b[2] - b[0]) * (b[3] - b[1]); if (a > maxA) maxA = a; });
|
||
var out = null;
|
||
subs.forEach(function (b) {
|
||
var a = (b[2] - b[0]) * (b[3] - b[1]);
|
||
if (a < maxA * 0.12 && subs.length > 1) return;
|
||
if (!out) out = b.slice();
|
||
else { out[0] = Math.min(out[0], b[0]); out[1] = Math.min(out[1], b[1]); out[2] = Math.max(out[2], b[2]); out[3] = Math.max(out[3], b[3]); }
|
||
});
|
||
bboxCache[cc] = out;
|
||
return out;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- state
|
||
var lang = 'en', ctx = null, root = null, ui = null, alive = false;
|
||
var S = { cc: '', region: '' };
|
||
var data = { world: null, country: null, full: null, error: false, loading: false };
|
||
var seq = 0, cache = {}, view = null, anim = 0, cityEls = [], ro = null;
|
||
|
||
function parseHash() {
|
||
var m = /^#\/geo(?:\/([A-Za-z]{2})(?:\/(.*))?)?$/.exec(location.hash || '');
|
||
var cc = '', region = '';
|
||
if (m && m[1]) {
|
||
cc = m[1].toUpperCase();
|
||
if (m[2]) { try { region = decodeURIComponent(m[2]); } catch (e) { region = ''; } }
|
||
}
|
||
return { cc: cc, region: region };
|
||
}
|
||
function writeHash() {
|
||
var hsh = '#/geo' + (S.cc ? '/' + S.cc + (S.region ? '/' + encodeURIComponent(S.region) : '') : '');
|
||
if (location.hash !== hsh) { try { history.pushState(null, '', hsh); } catch (e) { location.hash = hsh; } }
|
||
}
|
||
function go(cc, region, focus) {
|
||
if (world && cc && !world.paths[cc]) cc = '';
|
||
S.cc = cc || '';
|
||
S.region = cc ? (region || '') : '';
|
||
writeHash();
|
||
load(true);
|
||
if (focus && ui) setTimeout(function () { try { ui.lead.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0);
|
||
}
|
||
function goBack() {
|
||
if (S.region) go(S.cc, '', true);
|
||
else if (S.cc) go('', '', true);
|
||
}
|
||
function onHash() {
|
||
if (!alive) return;
|
||
var p = parseHash();
|
||
if (p.cc === S.cc && p.region === S.region) return;
|
||
S.cc = p.cc; S.region = p.region;
|
||
load(true);
|
||
}
|
||
function onKey(e) {
|
||
if (!alive || e.key !== 'Escape' || e.defaultPrevented) return;
|
||
var tg = e.target && e.target.tagName;
|
||
if (tg === 'INPUT' || tg === 'SELECT' || tg === 'TEXTAREA') return;
|
||
if (S.cc) { e.preventDefault(); goBack(); }
|
||
}
|
||
|
||
// ---------------------------------------------------------------- data
|
||
function key(extra) { return [ctx.range, ctx.host || '', extra || ''].join('|'); }
|
||
function fetchJSON(params) {
|
||
var p = { range: ctx.range };
|
||
if (ctx.host) p.host = ctx.host;
|
||
for (var k in params) p[k] = params[k];
|
||
return Promise.resolve(U.api('/api/v1/geo', p));
|
||
}
|
||
function cached(k, params) {
|
||
if (cache[k]) return Promise.resolve(cache[k]);
|
||
return fetchJSON(params).then(function (d) { cache[k] = d; return d; });
|
||
}
|
||
function load(refit) {
|
||
var my = ++seq;
|
||
data.loading = true; data.error = false;
|
||
paintState();
|
||
var cc = S.cc, region = S.region;
|
||
var jobs = [cached(key('w'), {})];
|
||
if (cc) {
|
||
jobs.push(cached(key('c:' + cc), { cc: cc }));
|
||
jobs.push(region ? cached(key('r:' + cc + ':' + region), { cc: cc, region: region }) : null);
|
||
}
|
||
Promise.all(jobs).then(function (r) {
|
||
if (my !== seq || !alive) return;
|
||
data.world = r[0];
|
||
data.full = cc ? r[1] : null;
|
||
data.country = cc ? (region ? r[2] : r[1]) : null;
|
||
data.loading = false;
|
||
render(refit);
|
||
}).catch(function () {
|
||
if (my !== seq || !alive) return;
|
||
data.loading = false; data.error = true;
|
||
render(false);
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------- build
|
||
function build(el) {
|
||
clear(el);
|
||
root = h('div', 'geo');
|
||
var top = h('div', 'geo-top');
|
||
var nav = h('nav', 'geo-crumbs'); nav.setAttribute('aria-label', t('geo.nav'));
|
||
var back = h('button', 'geo-back', '‹ ' + t('geo.back')); back.type = 'button';
|
||
back.title = t('geo.back.hint'); back.addEventListener('click', goBack);
|
||
top.appendChild(nav); top.appendChild(back);
|
||
var lead = h('h2', 'geo-lead'); lead.tabIndex = -1; lead.setAttribute('aria-live', 'polite');
|
||
var leadBox = h('div', 'lead geo-leadbox'); leadBox.appendChild(lead);
|
||
var err = h('div', 'geo-err'); err.setAttribute('role', 'alert'); err.hidden = true;
|
||
var errMsg = h('span', '', t('geo.error')), retry = h('button', 'geo-retry', t('geo.retry')); retry.type = 'button';
|
||
retry.addEventListener('click', function () { cache = {}; load(false); });
|
||
err.appendChild(errMsg); err.appendChild(retry);
|
||
|
||
var main = h('div', 'geo-main');
|
||
var mapPanel = h('section', 'geo-panel geo-mappanel');
|
||
var box = h('div', 'geo-map');
|
||
var svg = sv('svg', { 'class': 'geo-svg', role: 'img', preserveAspectRatio: 'xMidYMid meet' });
|
||
var gC = sv('g', { 'class': 'geo-countries' }), gCity = sv('g', { 'class': 'geo-cities' });
|
||
svg.appendChild(gC); svg.appendChild(gCity);
|
||
var paths = {};
|
||
Object.keys(world.paths).forEach(function (cc) {
|
||
var p = sv('path', { d: world.paths[cc], 'class': 'geo-cn', 'data-cc': cc });
|
||
paths[cc] = p; gC.appendChild(p);
|
||
});
|
||
var tip = h('div', 'geo-tip'); tip.hidden = true; tip.setAttribute('role', 'presentation');
|
||
var ld = h('div', 'geo-loading', t('geo.loading')); ld.hidden = true;
|
||
box.appendChild(svg); box.appendChild(tip); box.appendChild(ld);
|
||
var legend = h('div', 'geo-legend');
|
||
var lg = h('div', 'geo-legend-bar'); lg.setAttribute('aria-hidden', 'true');
|
||
var lmin = h('span', '', '1'), lmax = h('span', '', ''), ltx = h('span', 'geo-legend-t', t('geo.legend'));
|
||
legend.appendChild(lmin); legend.appendChild(lg); legend.appendChild(lmax); legend.appendChild(ltx);
|
||
mapPanel.appendChild(box); mapPanel.appendChild(legend);
|
||
|
||
var side = h('section', 'geo-panel geo-side');
|
||
var sideH = h('h2', '', ''); sideH.tabIndex = -1;
|
||
var sideList = h('div', 'geo-list');
|
||
side.appendChild(sideH); side.appendChild(sideList);
|
||
main.appendChild(mapPanel); main.appendChild(side);
|
||
|
||
var detail = h('div', 'geo-detail');
|
||
function panel(title) {
|
||
var p = h('section', 'geo-panel'), hd = h('h2', '', title), body = h('div', 'geo-body');
|
||
p.appendChild(hd); p.appendChild(body); detail.appendChild(p);
|
||
return { p: p, h: hd, body: body };
|
||
}
|
||
var pCities = panel(''), pCats = panel(''), pIps = panel('');
|
||
|
||
root.appendChild(top); root.appendChild(leadBox); root.appendChild(err); root.appendChild(main); root.appendChild(detail);
|
||
el.appendChild(root);
|
||
ui = { nav: nav, back: back, lead: lead, err: err, errMsg: errMsg, retry: retry, svg: svg, gCity: gCity, paths: paths, box: box,
|
||
tip: tip, loading: ld, legendMax: lmax, legend: legend, legendBar: lg, side: side, sideH: sideH, sideList: sideList, detail: detail,
|
||
pCities: pCities, pCats: pCats, pIps: pIps };
|
||
|
||
gC.addEventListener('click', function (e) {
|
||
var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc');
|
||
if (cc && hit(cc)) go(cc, '', true);
|
||
});
|
||
gC.addEventListener('mousemove', function (e) {
|
||
var cc = e.target && e.target.getAttribute && e.target.getAttribute('data-cc');
|
||
var r = cc && hit(cc);
|
||
if (!r) { ui.tip.hidden = true; return; }
|
||
showTip(e, [[flagOf(cc) + ' ' + countryName(cc), ''], [t('geo.tip.events'), nf(r.events)], [t('geo.tip.ips'), nf(r.ips)], [t('geo.tip.hostile'), nf(r.hostile || 0)]]);
|
||
});
|
||
gC.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||
gCity.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||
if (window.ResizeObserver) {
|
||
ro = new ResizeObserver(function () { if (alive && data.world && !data.error && !anim) { fitNow(); drawCities(); } });
|
||
ro.observe(box);
|
||
}
|
||
}
|
||
|
||
function hit(cc) {
|
||
var cs = data.world && data.world.countries;
|
||
if (!cs) return null;
|
||
for (var i = 0; i < cs.length; i++) if (cs[i].cc === cc) return cs[i];
|
||
return null;
|
||
}
|
||
function showTip(e, rows) {
|
||
var tip = ui.tip;
|
||
clear(tip);
|
||
rows.forEach(function (r, i) {
|
||
var d = h('div', i === 0 ? 'geo-tip-h' : 'geo-tip-r');
|
||
d.appendChild(h('span', '', r[0]));
|
||
if (r[1] !== '') d.appendChild(h('b', '', r[1]));
|
||
tip.appendChild(d);
|
||
});
|
||
tip.hidden = false;
|
||
var b = ui.box.getBoundingClientRect();
|
||
var x = e.clientX - b.left + 14, y = e.clientY - b.top + 14;
|
||
var w = tip.offsetWidth, hh = tip.offsetHeight;
|
||
if (x + w > b.width - 4) x = Math.max(4, e.clientX - b.left - w - 14);
|
||
if (y + hh > b.height - 4) y = Math.max(4, e.clientY - b.top - hh - 14);
|
||
tip.style.left = x + 'px'; tip.style.top = y + 'px';
|
||
}
|
||
|
||
// ---------------------------------------------------------------- map view
|
||
function boxSize() {
|
||
var r = ui.box.getBoundingClientRect();
|
||
return { w: r.width || 800, h: r.height || 360 };
|
||
}
|
||
function targetView() {
|
||
var sz = boxSize(), asp = sz.w / sz.h, bb, margin = 1.22;
|
||
if (!S.cc) { bb = [0, 0, world.w, world.h]; margin = 1; }
|
||
else {
|
||
bb = bboxOf(S.cc) || [0, 0, world.w, world.h];
|
||
var cs = data.country && data.country.cities;
|
||
if (S.region && cs) {
|
||
var pts = cs.filter(function (c) { return isNum(c.lat) && isNum(c.lon); });
|
||
if (pts.length) {
|
||
var x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
|
||
pts.forEach(function (c) { var x = projX(c.lon), y = projY(c.lat); x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); });
|
||
bb = [x0, y0, x1, y1]; margin = 1.5;
|
||
}
|
||
}
|
||
}
|
||
var bw = Math.max(bb[2] - bb[0], 36), bh = Math.max(bb[3] - bb[1], 36 / asp);
|
||
var vw = Math.max(bw * margin, bh * margin * asp);
|
||
var vh = vw / asp;
|
||
var cx = (bb[0] + bb[2]) / 2, cy = (bb[1] + bb[3]) / 2;
|
||
return [cx - vw / 2, cy - vh / 2, vw, vh];
|
||
}
|
||
function setView(v) { if (!(v[2] > 0 && v[3] > 0)) return; view = v; ui.svg.setAttribute('viewBox', v.map(function (n) { return n.toFixed(2); }).join(' ')); }
|
||
function fitNow() { setView(targetView()); }
|
||
function reduced() { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) { return false; } }
|
||
function animateTo(to, done) {
|
||
cancelAnimationFrame(anim); anim = 0;
|
||
if (!view || reduced()) { setView(to); done(); return; }
|
||
var from = view.slice(), t0 = performance.now(), dur = 420;
|
||
(function step(now) {
|
||
var k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
|
||
setView(from.map(function (f, i) { return f + (to[i] - f) * e; }));
|
||
if (k < 1) anim = requestAnimationFrame(step); else { anim = 0; done(); }
|
||
})(t0);
|
||
}
|
||
// O contrato repete a chave "ips" (contagem e lista); aceita os dois formatos.
|
||
function ipList(d) { return Array.isArray(d.top_ips) ? d.top_ips : (Array.isArray(d.ips) ? d.ips : []); }
|
||
function ipCount(d) {
|
||
if (isNum(d.ips)) return d.ips;
|
||
var k = ['ip_count', 'ips_total', 'unique_ips', 'ips_count'];
|
||
for (var i = 0; i < k.length; i++) if (isNum(d[k[i]])) return d[k[i]];
|
||
if (S.region && data.full) { var rs = data.full.regions || []; for (var j = 0; j < rs.length; j++) if (rs[j].name === S.region) return rs[j].ips; }
|
||
var w = hit(S.cc); if (w && !S.region) return w.ips;
|
||
return (d.cities || []).reduce(function (a, c) { return a + (c.ips || 0); }, 0);
|
||
}
|
||
function isNum(n) { return typeof n === 'number' && isFinite(n); }
|
||
|
||
function drawCities() {
|
||
clear(ui.gCity); cityEls = [];
|
||
var d = data.country;
|
||
if (!S.cc || !d || !d.cities || !view) return;
|
||
var sz = boxSize(), upp = view[2] / sz.w, max = 1;
|
||
d.cities.forEach(function (c) { if (c.events > max) max = c.events; });
|
||
var rmax = sz.w < 560 ? 16 : 26;
|
||
d.cities.forEach(function (c, i) {
|
||
if (!isNum(c.lat) || !isNum(c.lon)) return;
|
||
var x = projX(c.lon), y = projY(c.lat);
|
||
if (x < view[0] - 20 || x > view[0] + view[2] + 20 || y < view[1] - 20 || y > view[1] + view[3] + 20) return;
|
||
var r = Math.max(3, rmax * Math.sqrt(c.events / max)) * upp;
|
||
var el = sv('circle', { cx: x.toFixed(2), cy: y.toFixed(2), r: r.toFixed(2), 'class': 'geo-city' });
|
||
el.addEventListener('mousemove', function (e) {
|
||
var rows = [[c.name || t('geo.unknown'), '']];
|
||
if (c.region) rows.push([t('geo.tip.region'), c.region]);
|
||
rows.push([t('geo.tip.events'), nf(c.events)], [t('geo.tip.ips'), nf(c.ips)]);
|
||
showTip(e, rows);
|
||
});
|
||
el.addEventListener('mouseleave', function () { ui.tip.hidden = true; });
|
||
if (c.region && !S.region) {
|
||
el.addEventListener('click', function () { go(S.cc, c.region, true); });
|
||
el.classList.add('geo-city-click');
|
||
}
|
||
cityEls[i] = el; ui.gCity.appendChild(el);
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------- render
|
||
function paintState() {
|
||
if (!ui) return;
|
||
ui.loading.hidden = !data.loading || !!data.world;
|
||
root.classList.toggle('is-busy', data.loading);
|
||
}
|
||
|
||
function crumbs() {
|
||
var nav = ui.nav; clear(nav);
|
||
function sep() { var s = h('span', 'geo-sep', '›'); s.setAttribute('aria-hidden', 'true'); nav.appendChild(s); }
|
||
var parts = [{ txt: t('geo.world'), act: S.cc ? function () { go('', '', true); } : null }];
|
||
if (S.cc) parts.push({ txt: flagOf(S.cc) + ' ' + countryName(S.cc), act: S.region ? function () { go(S.cc, '', true); } : null });
|
||
if (S.region) parts.push({ txt: regionName(S.region), act: null });
|
||
parts.forEach(function (p, i) {
|
||
if (i) sep();
|
||
var n;
|
||
if (p.act) { n = h('button', 'geo-crumb', p.txt); n.type = 'button'; n.addEventListener('click', p.act); }
|
||
else { n = h('span', 'geo-crumb cur', p.txt); n.setAttribute('aria-current', 'page'); }
|
||
nav.appendChild(n);
|
||
});
|
||
ui.back.hidden = !S.cc;
|
||
}
|
||
|
||
function lead() {
|
||
var rl = rangeLabel(ctx.range), L = ui.lead;
|
||
if (data.error || !data.world) { L.textContent = ''; return; }
|
||
var cs = data.world.countries || [];
|
||
if (!S.cc) {
|
||
var tot = 0, ips = 0;
|
||
cs.forEach(function (c) { tot += c.events; ips += c.ips; });
|
||
if (!cs.length) { L.textContent = t('geo.lead.empty', { range: rl }); return; }
|
||
var top = cs.slice().sort(function (a, b) { return b.events - a.events; })[0];
|
||
L.textContent = t('geo.lead.world', { events: unit('events', tot), ips: unit('ips', ips), countries: unit('countries', cs.length),
|
||
range: rl, top: countryName(top.cc), pct: pct(top.events / tot) });
|
||
return;
|
||
}
|
||
var d = data.country, cn = countryName(S.cc);
|
||
if (!d || !d.events) { L.textContent = t('geo.lead.empty.country', { country: cn, range: rl }); return; }
|
||
var base = { country: cn, events: unit('events', d.events), ips: unit('ips', ipCount(d)), range: rl };
|
||
if (S.region) {
|
||
var c0 = (d.cities || [])[0];
|
||
base.region = regionName(S.region);
|
||
if (c0 && c0.name) { base.city = c0.name; base.pct = pct(c0.events / d.events); L.textContent = t('geo.lead.region', base); }
|
||
else L.textContent = t('geo.lead.region.flat', base);
|
||
return;
|
||
}
|
||
var r0 = ((d.regions || []).filter(function (r) { return r.name; })[0]);
|
||
if (r0 && d.regions.length > 1) { base.region = r0.name; base.pct = pct(r0.events / d.events); L.textContent = t('geo.lead.country', base); }
|
||
else L.textContent = t('geo.lead.country.flat', base);
|
||
}
|
||
|
||
function colorize() {
|
||
var cs = (data.world && data.world.countries) || [], max = 1, by = {};
|
||
cs.forEach(function (c) { by[c.cc] = c; if (c.events > max) max = c.events; });
|
||
var lm = Math.log(1 + max);
|
||
ui.legendMax.textContent = nf(max);
|
||
var zoomed = !!S.cc;
|
||
ui.svg.setAttribute('class', 'geo-svg' + (zoomed ? ' zoomed' : ''));
|
||
Object.keys(ui.paths).forEach(function (cc) {
|
||
var p = ui.paths[cc], c = by[cc], cls = 'geo-cn';
|
||
if (c) {
|
||
cls += ' hit';
|
||
p.style.fillOpacity = (0.2 + 0.8 * Math.log(1 + c.events) / lm).toFixed(3);
|
||
} else p.style.fillOpacity = '';
|
||
if (cc === S.cc) cls += ' sel';
|
||
p.setAttribute('class', cls);
|
||
});
|
||
ui.legend.hidden = zoomed;
|
||
if (S.cc) ui.svg.setAttribute('aria-label', t('geo.map.country.label', { country: countryName(S.cc) }));
|
||
else ui.svg.setAttribute('aria-label', t('geo.map.label'));
|
||
}
|
||
|
||
function emptyNote(txt) { return h('div', 'geo-empty', txt); }
|
||
|
||
function row(opts) {
|
||
// opts: name, sub, n, frac, onClick, label, pressed, rank, cls
|
||
var r = h(opts.onClick ? 'button' : 'div', 'geo-row' + (opts.cls ? ' ' + opts.cls : ''));
|
||
if (opts.onClick) {
|
||
r.type = 'button'; r.addEventListener('click', opts.onClick);
|
||
if (opts.label) r.setAttribute('aria-label', opts.label);
|
||
if (opts.pressed != null) r.setAttribute('aria-pressed', opts.pressed ? 'true' : 'false');
|
||
}
|
||
var top = h('span', 'geo-row-top');
|
||
if (opts.rank) top.appendChild(h('span', 'geo-rank', String(opts.rank)));
|
||
var nm = h('span', 'geo-name', opts.name); top.appendChild(nm);
|
||
if (opts.sub) top.appendChild(h('span', 'geo-sub', opts.sub));
|
||
top.appendChild(h('span', 'geo-num', nf(opts.n)));
|
||
r.appendChild(top);
|
||
var bar = h('span', 'geo-bar'), i = h('i'); i.style.width = Math.max(2, opts.frac * 100) + '%';
|
||
bar.appendChild(i); r.appendChild(bar);
|
||
return r;
|
||
}
|
||
|
||
function renderSide() {
|
||
var L = ui.sideList; clear(L);
|
||
if (!S.cc) {
|
||
ui.sideH.textContent = t('geo.countries');
|
||
var cs = ((data.world && data.world.countries) || []).slice().sort(function (a, b) { return b.events - a.events; });
|
||
if (!cs.length) { L.appendChild(emptyNote(t('geo.empty'))); return; }
|
||
var max = cs[0].events || 1;
|
||
cs.forEach(function (c, i) {
|
||
var nm = countryName(c.cc);
|
||
L.appendChild(row({ rank: i + 1, name: flagOf(c.cc) + ' ' + nm, n: c.events, frac: c.events / max,
|
||
label: t('geo.pick', { name: nm, events: unit('events', c.events) }), onClick: function () { go(c.cc, '', true); } }));
|
||
});
|
||
return;
|
||
}
|
||
ui.sideH.textContent = t('geo.regions');
|
||
var d = data.full;
|
||
var rs = (d && d.regions) || [];
|
||
if (!rs.length) { L.appendChild(emptyNote(t('geo.empty.list'))); return; }
|
||
if (S.region) {
|
||
var all = h('button', 'geo-chip', t('geo.all_regions')); all.type = 'button';
|
||
all.addEventListener('click', function () { go(S.cc, '', true); });
|
||
L.appendChild(all);
|
||
}
|
||
var mx = rs[0].events || 1;
|
||
rs.forEach(function (r, i) {
|
||
var can = !!r.name;
|
||
L.appendChild(row({ rank: i + 1, name: regionName(r.name), sub: unit('ips', r.ips), n: r.events, frac: r.events / mx,
|
||
cls: S.region === r.name && can ? 'on' : '',
|
||
pressed: can ? S.region === r.name : null,
|
||
label: can ? t('geo.pick.region', { name: r.name, events: unit('events', r.events) }) : '',
|
||
onClick: can ? function () { go(S.cc, S.region === r.name ? '' : r.name, true); } : null }));
|
||
});
|
||
}
|
||
|
||
function renderDetail() {
|
||
var show = !!S.cc && !!data.country;
|
||
ui.detail.hidden = !show;
|
||
if (!show) return;
|
||
var d = data.country;
|
||
// cities
|
||
ui.pCities.h.textContent = t('geo.cities');
|
||
var B = ui.pCities.body; clear(B);
|
||
var cs = d.cities || [];
|
||
if (!cs.length) B.appendChild(emptyNote(t('geo.empty.list')));
|
||
else {
|
||
var mx = cs[0].events || 1, nocoord = 0;
|
||
cs.slice(0, 15).forEach(function (c, i) {
|
||
var can = !!c.region && !S.region;
|
||
var r = row({ rank: i + 1, name: c.name || t('geo.unknown'), sub: c.region || '', n: c.events, frac: c.events / mx,
|
||
label: can ? t('geo.city.pick', { name: c.region }) : '', onClick: can ? function () { go(S.cc, c.region, true); } : null });
|
||
r.addEventListener('mouseenter', function () { if (cityEls[i]) cityEls[i].classList.add('hl'); });
|
||
r.addEventListener('mouseleave', function () { if (cityEls[i]) cityEls[i].classList.remove('hl'); });
|
||
B.appendChild(r);
|
||
});
|
||
cs.forEach(function (c) { if (!isNum(c.lat) || !isNum(c.lon)) nocoord++; });
|
||
if (nocoord) B.appendChild(h('div', 'geo-note', t(nocoord === 1 ? 'geo.nocoords.one' : 'geo.nocoords.other', { n: nf(nocoord) })));
|
||
}
|
||
// categories
|
||
ui.pCats.h.textContent = t('geo.cats');
|
||
B = ui.pCats.body; clear(B);
|
||
var cats = d.cats || {}, keys = Object.keys(cats).sort(function (a, b) { return cats[b] - cats[a]; }), tot = sum(cats);
|
||
if (!keys.length || !tot) B.appendChild(emptyNote(t('geo.empty.list')));
|
||
else {
|
||
var st = h('div', 'geo-stack'); st.setAttribute('aria-hidden', 'true');
|
||
keys.forEach(function (k) { var s = h('span', catCls(k)); s.style.flexGrow = String(cats[k]); st.appendChild(s); });
|
||
B.appendChild(st);
|
||
var ul = h('ul', 'geo-chips');
|
||
keys.forEach(function (k) {
|
||
var li = h('li', 'geo-chipcat'), dot = h('i', catCls(k)); dot.setAttribute('aria-hidden', 'true');
|
||
li.appendChild(dot); li.appendChild(h('span', '', catLabel(k))); li.appendChild(h('b', '', nf(cats[k]) + ' · ' + pct(cats[k] / tot)));
|
||
ul.appendChild(li);
|
||
});
|
||
B.appendChild(ul);
|
||
if (d.hostile || d.suspicious) B.appendChild(h('div', 'geo-note', t('geo.hostile_suspicious', { h: nf(d.hostile || 0), s: nf(d.suspicious || 0) })));
|
||
}
|
||
// ips
|
||
ui.pIps.h.textContent = t('geo.ips');
|
||
B = ui.pIps.body; clear(B);
|
||
var ips = ipList(d);
|
||
if (!ips.length) B.appendChild(emptyNote(t('geo.empty.list')));
|
||
else ips.slice(0, 12).forEach(function (x) {
|
||
var b = h('button', 'geo-ip'); b.type = 'button';
|
||
b.setAttribute('aria-label', t('geo.open_ip', { ip: x.ip }));
|
||
b.addEventListener('click', function () { U.openIP(x.ip); });
|
||
var l1 = h('span', 'geo-ip-l1');
|
||
l1.appendChild(h('code', '', x.ip));
|
||
var lv = LEVELS[x.level] ? x.level : 'unknown';
|
||
l1.appendChild(h('span', 'geo-lv geo-lv-' + lv, t('geo.level.' + lv)));
|
||
if (isNum(x.score)) l1.appendChild(h('span', 'geo-score', t('geo.score', { n: nf(x.score) })));
|
||
b.appendChild(l1);
|
||
var where = [x.city, x.region].filter(Boolean).join(', '), who = [x.asn, x.as_org].filter(Boolean).join(' ');
|
||
var l2 = h('span', 'geo-ip-l2', [where, who].filter(Boolean).join(' · '));
|
||
b.appendChild(l2);
|
||
if (x.last) { var ago = ''; try { ago = U.fmt.ago(x.last); } catch (e) { ago = ''; } if (ago) b.appendChild(h('span', 'geo-ip-l3', String(ago))); }
|
||
B.appendChild(b);
|
||
});
|
||
}
|
||
|
||
function render(refit) {
|
||
if (!ui) return;
|
||
paintState();
|
||
ui.err.hidden = !data.error;
|
||
ui.loading.hidden = true;
|
||
crumbs();
|
||
if (data.error || !data.world) { lead(); ui.detail.hidden = true; clear(ui.sideList); clear(ui.gCity); ui.legend.hidden = true;
|
||
ui.svg.setAttribute('class', 'geo-svg'); setView(targetView());
|
||
Object.keys(ui.paths).forEach(function (cc) { ui.paths[cc].style.fillOpacity = ''; ui.paths[cc].setAttribute('class', 'geo-cn'); });
|
||
return; }
|
||
colorize(); lead(); renderSide(); renderDetail();
|
||
clear(ui.gCity); cityEls = [];
|
||
var to = targetView();
|
||
if (refit === false) { setView(to); drawCities(); }
|
||
else animateTo(to, drawCities);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- page
|
||
U.registerPage({
|
||
id: 'geo',
|
||
icon: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.2 3 14.8 0 18M12 3c-3 3.2-3 14.8 0 18"/></svg>',
|
||
titleKey: 'geo.title',
|
||
mount: function (el, c) {
|
||
ctx = c; lang = c.lang || 'en';
|
||
world = U.world || window.URUTAU_WORLD;
|
||
alive = true; cache = {}; view = null;
|
||
if (!world || !world.paths) { clear(el); el.appendChild(h('div', 'geo-empty', t('geo.error'))); return; }
|
||
var p = parseHash(); S.cc = world.paths[p.cc] ? p.cc : ''; S.region = S.cc ? p.region : '';
|
||
build(el);
|
||
window.addEventListener('hashchange', onHash);
|
||
window.addEventListener('popstate', onHash);
|
||
document.addEventListener('keydown', onKey);
|
||
load(false);
|
||
},
|
||
update: function (c) {
|
||
var langChanged = (c.lang || 'en') !== lang;
|
||
ctx = c; lang = c.lang || 'en';
|
||
if (!alive || !ui) return;
|
||
cache = {};
|
||
if (langChanged) { var el = root.parentNode; build(el); }
|
||
load(false);
|
||
},
|
||
unmount: function () {
|
||
alive = false; seq++;
|
||
cancelAnimationFrame(anim); anim = 0;
|
||
window.removeEventListener('hashchange', onHash);
|
||
window.removeEventListener('popstate', onHash);
|
||
document.removeEventListener('keydown', onKey);
|
||
if (ro) { ro.disconnect(); ro = null; }
|
||
ui = null; root = null;
|
||
}
|
||
});
|
||
})();
|