refactor: scrape AlbionBB HTML pages for guild analytics data
This commit is contained in:
8 files changed
+241
-28
No files matched your search
@@ -5,6 +5,11 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
|
refresh_analytics:
|
||||||
|
description: 'Refresh analytics by scraping AlbionBB pages (requires source-site access)'
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
guild:
|
guild:
|
||||||
description: 'Optional full Europe guild name to add to the static analytics data'
|
description: 'Optional full Europe guild name to add to the static analytics data'
|
||||||
required: false
|
required: false
|
||||||
@@ -22,20 +27,20 @@ jobs:
|
|||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '24'
|
node-version: '24'
|
||||||
- name: Verify content and behavior
|
|
||||||
run: npm test
|
|
||||||
- name: Restore published analytics datasets
|
- name: Restore published analytics datasets
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name == 'workflow_dispatch' && (inputs.refresh_analytics || inputs.guild != '')
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
with:
|
with:
|
||||||
path: public/data/intel
|
path: public/data/intel
|
||||||
key: intel-data-${{ github.run_id }}
|
key: intel-data-${{ github.run_id }}-${{ github.run_attempt }}
|
||||||
restore-keys: intel-data-
|
restore-keys: intel-data-
|
||||||
- name: Refresh static guild analytics
|
- name: Refresh static guild analytics
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name == 'workflow_dispatch' && (inputs.refresh_analytics || inputs.guild != '')
|
||||||
run: npm run sync:intel
|
run: npm run sync:intel
|
||||||
env:
|
env:
|
||||||
INTEL_GUILD_NAME: ${{ inputs.guild }}
|
INTEL_GUILD_NAME: ${{ inputs.guild }}
|
||||||
|
- name: Verify content and behavior
|
||||||
|
run: npm test
|
||||||
- name: Download battle preview images
|
- name: Download battle preview images
|
||||||
if: github.event_name != 'pull_request'
|
if: github.event_name != 'pull_request'
|
||||||
run: npm run sync:battles
|
run: npm run sync:battles
|
||||||
|
|||||||
@@ -107,14 +107,14 @@ npm run build
|
|||||||
|
|
||||||
`content/intel-guilds.json` lists full Europe guild names to prepare (initially
|
`content/intel-guilds.json` lists full Europe guild names to prepare (initially
|
||||||
OneUP). Add a name there, or use `INTEL_GUILD_NAME="Full Guild Name" npm run sync:intel`.
|
OneUP). Add a name there, or use `INTEL_GUILD_NAME="Full Guild Name" npm run sync:intel`.
|
||||||
The collector searches for an exact match, exhausts the history pages in the
|
The collector reads public AlbionBB HTML pages, finds an exact guild match, exhausts the history pages in the
|
||||||
60-day window and saves full guild detail, including recorded roles and weapons.
|
60-day window and saves full guild detail, including recorded roles and weapons.
|
||||||
It retains other guilds' aggregate stats for grouping, but omits their player
|
It retains other guilds' aggregate stats for grouping, but omits their player
|
||||||
rosters to keep files small. Raw files contain only public game data.
|
rosters to keep files small. Raw files contain only public game data.
|
||||||
|
|
||||||
For all 7/30/60-day windows, the collector prepares the multi reports needed for
|
For all 7/30/60-day windows, the collector prepares the multi reports needed for
|
||||||
**every distinct total-player threshold**, not just a few preset values. Each is
|
**every distinct total-player threshold**, not just a few preset values. Each is
|
||||||
fetched from AlbionBB's multi endpoint and its kill, death and fame totals are
|
extracted from AlbionBB's public `battles/multi` HTML pages and its kill, death and fame totals are
|
||||||
verified against the originals. Browser grouping uses the same rules and reads
|
verified against the originals. Browser grouping uses the same rules and reads
|
||||||
the corresponding saved multi. Failed or missing data is an error; no silently
|
the corresponding saved multi. Failed or missing data is an error; no silently
|
||||||
approximated merged composition is presented.
|
approximated merged composition is presented.
|
||||||
@@ -124,13 +124,35 @@ and normal build work offline. Subsequent refreshes reuse historical raw reports
|
|||||||
and verified multi files. The manifest is replaced only after all requested guilds
|
and verified multi files. The manifest is replaced only after all requested guilds
|
||||||
have been collected successfully. New files have content hashes in their names.
|
have been collected successfully. New files have content hashes in their names.
|
||||||
|
|
||||||
The existing GitHub Pages workflow now refreshes datasets before publishing on
|
Normal GitHub Pages deployments publish the committed datasets without contacting
|
||||||
push or manual runs. Its optional **guild** input adds another prepared guild.
|
the source website. This keeps deployment independent of AlbionBB availability and
|
||||||
The Actions cache retains previously prepared guilds and reports for subsequent
|
its IP restrictions; the direct API previously returned HTTP 403 on GitHub runners.
|
||||||
runs. No runtime server is deployed and no new service subscription is required.
|
Plain manual deployments also use committed data.
|
||||||
There is no scheduled refresh: the timestamp advances on the next publication.
|
|
||||||
|
|
||||||
Data collection uses the same public AlbionBB API as the battle importer. This
|
To explicitly request a remote refresh, enable **refresh_analytics** in Run workflow,
|
||||||
happens on the maintainer's computer or in CI, where browser CORS does not apply.
|
or provide the optional **guild** input to add a prepared guild. Only those runs
|
||||||
All analysis still happens in the visitor's browser. The normal `npm run build`
|
restore the Actions data cache and call the collector. Validation runs afterward,
|
||||||
does not fetch anything from the network.
|
against the actual data being published. A requested refresh still fails visibly
|
||||||
|
if AlbionBB blocks the runner; a stale or incomplete refresh is not reported as
|
||||||
|
successful. In that case run `npm run sync:intel` locally and commit the resulting
|
||||||
|
`public/data/intel/` files before pushing. No runtime server is deployed.
|
||||||
|
|
||||||
|
There is no scheduled refresh. Ordinary deployments preserve the dataset timestamp;
|
||||||
|
it advances only after a successful explicit collection.
|
||||||
|
|
||||||
|
Analytics collection now scrapes public pages on `https://europe.albionbb.com`:
|
||||||
|
guild battle lists, individual reports, search results and combined reports. The
|
||||||
|
site embeds complete server-rendered report data in its HTML. The scraper parses
|
||||||
|
that JSON reference graph without executing remote JavaScript and without calling
|
||||||
|
`api.albionbb.com`. It retains exact fame, player roles, weapons and roster data.
|
||||||
|
The separate legacy battle importer still uses the API.
|
||||||
|
|
||||||
|
Scraping runs on the maintainer's computer or in CI, where browser CORS does not
|
||||||
|
apply. The source site itself still obtains its data internally; this project
|
||||||
|
reads its published pages. A source-site block, rate limit, or HTML format change
|
||||||
|
stops collection, and the previous complete dataset remains usable. Successful
|
||||||
|
local scraping does not guarantee that GitHub's IP addresses are allowed.
|
||||||
|
|
||||||
|
All analysis still happens in the visitor's browser. Scraping another domain from
|
||||||
|
client JavaScript would still require CORS permission, so the browser reads only
|
||||||
|
the published same-origin JSON. The normal `npm run build` stays offline.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"schemaVersion":1,"source":"albionbb-html","guild":{"Id":"SF2Zf4PrRsmdBAL5PaBV_A","Name":"OneUP"},"asOf":"2026-10-20T13:55:53.871Z","coverageDays":60,"battles":[{"albionId":450607051,"startedAt":"2026-10-20T13:40:57.679Z","finishedAt":"2026-10-20T13:42:31.681Z","totalFame":306251,"totalKills":4,"totalPlayers":9,"guilds":[{"albionId":"7JZANN-BTH6QK5uSiCsQ1A","name":"Stability","kills":4,"deaths":0,"killFame":306245,"players":5,"ip":1447},{"albionId":"0cRX7Xt9RDuyyQQ-m-CbGw","name":"Kiss or Spank","alliance":"KD","kills":0,"deaths":3,"killFame":0,"players":3,"ip":1311},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1022}],"players":[{"name":"RezGhoulSG","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":52721,"ip":1022,"heal":0,"damage":0,"role":"melee","weapon":{"name":"2H_KNUCKLES_SET2","type":"T4_2H_KNUCKLES_SET2@2","quality":4}}]},{"albionId":450551865,"startedAt":"2026-10-20T10:59:11.72Z","finishedAt":"2026-10-20T11:00:53.44Z","totalFame":1005326,"totalKills":3,"totalPlayers":10,"guilds":[{"albionId":"zhgXCDFoQFS_IVosoGsxUA","name":"Utopia","alliance":"7UP","kills":1,"deaths":2,"killFame":492120,"players":7,"ip":1404},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":342136,"players":2,"ip":1403},{"albionId":"bE4mUn7HQMqvtT9NaFsA9A","name":"not really X","kills":1,"deaths":1,"killFame":171068,"players":1,"ip":1342}],"players":[{"name":"GODpori","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":0,"killFame":171068,"deathFame":0,"ip":0,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T5_2H_IRONCLADEDSTAFF@2","quality":2}},{"name":"AliSorena","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":171068,"deathFame":0,"ip":1403,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T6_2H_IRONCLADEDSTAFF@1","quality":4}}]},{"albionId":450546118,"startedAt":"2026-10-20T10:33:06.52Z","finishedAt":"2026-10-20T10:34:52.685Z","totalFame":1728,"totalKills":3,"totalPlayers":7,"guilds":[{"albionId":"AQF3L97hRoSZrWh-23AGUQ","name":"Undead Outlaws","kills":0,"deaths":2,"killFame":1152,"players":2,"ip":1279},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1334},{"albionId":"-CsKqlyeTLeKzakW2tKUyg","name":"Legio Potens","alliance":"Halal","kills":0,"deaths":0,"killFame":0,"players":1,"ip":1349}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":1728,"ip":1334,"heal":0,"damage":0,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450534048,"startedAt":"2026-10-20T09:19:55.622Z","finishedAt":"2026-10-20T09:20:16.005Z","totalFame":29790,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"ITaSge20T_6P7UVLBfe6ew","name":"AllianceOfScurletRoseAndCross","alliance":"Depth","kills":1,"deaths":0,"killFame":9930,"players":1,"ip":1362},{"albionId":"GlQrOQwEQAOWBrLhF7ZIhw","name":"EQMS","alliance":"MASS","kills":0,"deaths":0,"killFame":9930,"players":1,"ip":1351},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":2,"deaths":0,"killFame":9930,"players":1,"ip":1334},{"albionId":"6qu76pd6QCWueWE8FO856Q","name":"SkoZirys","alliance":"BLS","kills":0,"deaths":3,"killFame":0,"players":3,"ip":1244}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":2,"deaths":0,"killFame":9930,"deathFame":0,"ip":1334,"heal":0,"damage":16010,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450507553,"startedAt":"2026-10-20T07:12:31.324Z","finishedAt":"2026-10-20T07:12:56.134Z","totalFame":5832,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"b24VSOcoTs-q6eUoVnvfbQ","name":"Enjoyers","alliance":"ASR","kills":2,"deaths":0,"killFame":1944,"players":1,"ip":1330},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":1944,"players":1,"ip":1334},{"albionId":"MJlWe-zCQ9aQY8x3OUi5sA","name":"MYDAKI","alliance":"ZOUZ","kills":0,"deaths":2,"killFame":0,"players":2,"ip":1332}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":1944,"deathFame":0,"ip":1334,"heal":0,"damage":7543,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450506733,"startedAt":"2026-10-20T07:07:30.518Z","finishedAt":"2026-10-20T07:08:01.052Z","totalFame":42120,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"_MWi7UZQRzyXPdbJsgKzyg","name":"The Night","kills":2,"deaths":0,"killFame":18072,"players":1,"ip":1291},{"albionId":"e7CUFl8hSRq2Pg6pdSxhJA","name":"AQUAMARINE","alliance":"LOVER","kills":1,"deaths":0,"killFame":18072,"players":1,"ip":133Line truncated
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"schemaVersion":1,"guild":{"Id":"SF2Zf4PrRsmdBAL5PaBV_A","Name":"OneUP"},"asOf":"2026-10-20T12:59:30.574Z","coverageDays":60,"battles":[{"albionId":450551865,"startedAt":"2026-10-20T10:59:11.72Z","finishedAt":"2026-10-20T11:00:53.44Z","totalFame":1005326,"totalKills":3,"totalPlayers":10,"guilds":[{"albionId":"zhgXCDFoQFS_IVosoGsxUA","name":"Utopia","alliance":"7UP","kills":1,"deaths":2,"killFame":492120,"players":7,"ip":1404},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":342136,"players":2,"ip":1403},{"albionId":"bE4mUn7HQMqvtT9NaFsA9A","name":"not really X","kills":1,"deaths":1,"killFame":171068,"players":1,"ip":1342}],"players":[{"name":"GODpori","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":0,"killFame":171068,"deathFame":0,"ip":0,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T5_2H_IRONCLADEDSTAFF@2","quality":2}},{"name":"AliSorena","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":171068,"deathFame":0,"ip":1403,"heal":0,"damage":0,"role":"tank","weapon":{"name":"2H_IRONCLADEDSTAFF","type":"T6_2H_IRONCLADEDSTAFF@1","quality":4}}]},{"albionId":450546118,"startedAt":"2026-10-20T10:33:06.52Z","finishedAt":"2026-10-20T10:34:52.685Z","totalFame":1728,"totalKills":3,"totalPlayers":7,"guilds":[{"albionId":"AQF3L97hRoSZrWh-23AGUQ","name":"Undead Outlaws","kills":0,"deaths":2,"killFame":1152,"players":2,"ip":1279},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1334},{"albionId":"-CsKqlyeTLeKzakW2tKUyg","name":"Legio Potens","alliance":"Halal","kills":0,"deaths":0,"killFame":0,"players":1,"ip":1349}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":1728,"ip":1334,"heal":0,"damage":0,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450534048,"startedAt":"2026-10-20T09:19:55.622Z","finishedAt":"2026-10-20T09:20:16.005Z","totalFame":29790,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"ITaSge20T_6P7UVLBfe6ew","name":"AllianceOfScurletRoseAndCross","alliance":"Depth","kills":1,"deaths":0,"killFame":9930,"players":1,"ip":1362},{"albionId":"GlQrOQwEQAOWBrLhF7ZIhw","name":"EQMS","alliance":"MASS","kills":0,"deaths":0,"killFame":9930,"players":1,"ip":1351},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":2,"deaths":0,"killFame":9930,"players":1,"ip":1334},{"albionId":"6qu76pd6QCWueWE8FO856Q","name":"SkoZirys","alliance":"BLS","kills":0,"deaths":3,"killFame":0,"players":3,"ip":1244}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":2,"deaths":0,"killFame":9930,"deathFame":0,"ip":1334,"heal":0,"damage":16010,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450507553,"startedAt":"2026-10-20T07:12:31.324Z","finishedAt":"2026-10-20T07:12:56.134Z","totalFame":5832,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"b24VSOcoTs-q6eUoVnvfbQ","name":"Enjoyers","alliance":"ASR","kills":2,"deaths":0,"killFame":1944,"players":1,"ip":1330},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":1,"deaths":0,"killFame":1944,"players":1,"ip":1334},{"albionId":"MJlWe-zCQ9aQY8x3OUi5sA","name":"MYDAKI","alliance":"ZOUZ","kills":0,"deaths":2,"killFame":0,"players":2,"ip":1332}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":1,"deaths":0,"killFame":1944,"deathFame":0,"ip":1334,"heal":0,"damage":7543,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450506733,"startedAt":"2026-10-20T07:07:30.518Z","finishedAt":"2026-10-20T07:08:01.052Z","totalFame":42120,"totalKills":3,"totalPlayers":6,"guilds":[{"albionId":"_MWi7UZQRzyXPdbJsgKzyg","name":"The Night","kills":2,"deaths":0,"killFame":18072,"players":1,"ip":1291},{"albionId":"e7CUFl8hSRq2Pg6pdSxhJA","name":"AQUAMARINE","alliance":"LOVER","kills":1,"deaths":0,"killFame":18072,"players":1,"ip":1330},{"albionId":"b24VSOcoTs-q6eUoVnvfbQ","name":"Enjoyers","alliance":"ASR","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1330},{"albionId":"SF2Zf4PrRsmdBAL5PaBV_A","name":"OneUP","alliance":"CRSE","kills":0,"deaths":1,"killFame":0,"players":1,"ip":1334}],"players":[{"name":"Xuv","guildName":"OneUP","allianceName":"CRSE","kills":0,"deaths":1,"killFame":0,"deathFame":15336,"ip":1334,"heal":0,"damage":0,"role":"range","weapon":{"name":"MAIN_ARCANESTAFF_UNDEAD","type":"T4_MAIN_ARCANESTAFF_UNDEAD@4","quality":4}}]},{"albionId":450502504,"startedAt":"2026-10-20T06:38:41.954Z","finishedAt":"2026-10-20T06:39:50.791Z","totalFame":578314,"totalKills":4,"totalPlayers":5,"guilds":[{"albionId":"qZbvq5VrQdWDbWB_-LHfmQ","name":"Forge of Battles","kills":4,"deaths":0,"killFame":578314,"players":1,"ip":1460},{"albionId":Line truncated
|
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"updatedAt": "2026-10-20T12:59:30.574Z",
|
"updatedAt": "2026-10-20T13:55:53.871Z",
|
||||||
"guilds": [
|
"guilds": [
|
||||||
{
|
{
|
||||||
"Id": "SF2Zf4PrRsmdBAL5PaBV_A",
|
"Id": "SF2Zf4PrRsmdBAL5PaBV_A",
|
||||||
"Name": "OneUP",
|
"Name": "OneUP",
|
||||||
"file": "SF2Zf4PrRsmdBAL5PaBV_A-c3428e12a5db.json",
|
"file": "SF2Zf4PrRsmdBAL5PaBV_A-2f4f79516aa7.json",
|
||||||
"asOf": "2026-10-20T12:59:30.574Z",
|
"asOf": "2026-10-20T13:55:53.871Z",
|
||||||
"coverageDays": 60,
|
"coverageDays": 60,
|
||||||
"battleCount": 2020
|
"battleCount": 2021
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { normalizeName } from '../src/intel-core.js';
|
||||||
|
|
||||||
|
const SITE = 'https://europe.albionbb.com';
|
||||||
|
const REFS = new Set(['Reactive','ShallowReactive','Ref','ShallowRef']);
|
||||||
|
|
||||||
|
// Nuxt serializes its server-rendered page data as a flattened reference graph.
|
||||||
|
// Decode JSON only; never evaluate scripts downloaded from the source site.
|
||||||
|
export function readPageData(html) {
|
||||||
|
const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];
|
||||||
|
const script = scripts.find(([,attrs]) => /type\s*=\s*["']application\/json["']/i.test(attrs) && /data-nuxt-data|__NUXT_DATA__/i.test(attrs));
|
||||||
|
if (!script) throw Error('AlbionBB page does not contain server-rendered data');
|
||||||
|
const values = JSON.parse(script[2]);
|
||||||
|
if (!Array.isArray(values) || !values.length) throw Error('Invalid AlbionBB page payload');
|
||||||
|
const seen = new Map();
|
||||||
|
function decode(index, depth = 0) {
|
||||||
|
if (depth>200 || !Number.isInteger(index)) throw Error('Invalid payload reference');
|
||||||
|
if (index<0) {
|
||||||
|
if (index===-1 || index===-2) return undefined;
|
||||||
|
if (index===-3) return NaN;
|
||||||
|
if (index===-4) return Infinity;
|
||||||
|
if (index===-5) return -Infinity;
|
||||||
|
if (index===-6) return -0;
|
||||||
|
throw Error('Unknown payload reference');
|
||||||
|
}
|
||||||
|
if (index>=values.length) throw Error('Payload reference out of bounds');
|
||||||
|
if (seen.has(index)) return seen.get(index);
|
||||||
|
const value = values[index];
|
||||||
|
if (!value || typeof value!=='object') return value;
|
||||||
|
if (Array.isArray(value) && typeof value[0]==='string') {
|
||||||
|
if (REFS.has(value[0])) return decode(value[1],depth+1);
|
||||||
|
if (value[0]==='Date') return new Date(value[1]).toISOString();
|
||||||
|
if (value[0]==='EmptyRef' || value[0]==='EmptyShallowRef') return undefined;
|
||||||
|
throw Error(`Unsupported page data type: ${value[0]}`);
|
||||||
|
}
|
||||||
|
const result = Array.isArray(value)?[]:{};
|
||||||
|
seen.set(index,result);
|
||||||
|
for (const [key,ref] of Object.entries(value)) {
|
||||||
|
Object.defineProperty(result,key,{value:decode(ref,depth+1),enumerable:true,writable:true,configurable:true});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
let root = 0;
|
||||||
|
const visited = new Set();
|
||||||
|
while (Array.isArray(values[root]) && REFS.has(values[root][0])) {
|
||||||
|
if (visited.has(root)) throw Error('Cyclic root payload');
|
||||||
|
visited.add(root);root=values[root][1];
|
||||||
|
}
|
||||||
|
if (typeof values[root]?.data!=='number') throw Error('Missing page data root');
|
||||||
|
const data = decode(values[root].data);
|
||||||
|
if (!data || typeof data!=='object' || Array.isArray(data)) throw Error('Invalid page data root');
|
||||||
|
return Object.values(data);
|
||||||
|
}
|
||||||
|
export function readBattlePage(html) {
|
||||||
|
const battle = readPageData(html).find(value => value && !Array.isArray(value) && Number.isSafeInteger(value.albionId) && Array.isArray(value.guilds) && Array.isArray(value.players));
|
||||||
|
if (!battle) throw Error('Battle data missing from AlbionBB HTML');
|
||||||
|
return battle;
|
||||||
|
}
|
||||||
|
export function readListingPage(html) {
|
||||||
|
const rows = readPageData(html).find(value => Array.isArray(value) && value.every(b=>Number.isSafeInteger(b?.albionId) && typeof b.startedAt==='string' && Array.isArray(b.guilds)));
|
||||||
|
if (!rows) throw Error('Battle listing missing from AlbionBB HTML');
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
export function createPageClient({ fetchPage, knownGuilds=[] }) {
|
||||||
|
const battles = new Map();
|
||||||
|
async function detail(id) {
|
||||||
|
if (!/^\d+$/.test(String(id))) throw Error('Invalid battle ID');
|
||||||
|
if (!battles.has(Number(id))) {
|
||||||
|
const battle = readBattlePage(await fetchPage(new URL(`/battles/${id}`,SITE)));
|
||||||
|
if (battle.albionId!==Number(id)) throw Error('Unexpected battle page');
|
||||||
|
battles.set(Number(id),battle);
|
||||||
|
}
|
||||||
|
return battles.get(Number(id));
|
||||||
|
}
|
||||||
|
return async function request(path,query={}) {
|
||||||
|
if (path==='/guilds/search') {
|
||||||
|
const known = knownGuilds.filter(g=>normalizeName(g.Name)===normalizeName(query.search));
|
||||||
|
if (known.length) return known.map(g=>({Id:g.Id,Name:g.Name}));
|
||||||
|
// Public search pages list matching fights; the detail pages identify guild IDs.
|
||||||
|
const url = new URL('/',SITE);
|
||||||
|
url.search = new URLSearchParams({search:query.search,minPlayers:1,page:1}).toString();
|
||||||
|
const rows = readListingPage(await fetchPage(url));
|
||||||
|
const matches = new Map();
|
||||||
|
for (const row of rows) {
|
||||||
|
if (!row.guilds.some(g=>normalizeName(g.name)===normalizeName(query.search))) continue;
|
||||||
|
const battle = await detail(row.albionId);
|
||||||
|
for (const guild of battle.guilds) if (normalizeName(guild.name)===normalizeName(query.search)) matches.set(guild.albionId,{Id:guild.albionId,Name:guild.name});
|
||||||
|
if (matches.size) break;
|
||||||
|
}
|
||||||
|
return [...matches.values()];
|
||||||
|
}
|
||||||
|
if (path==='/battles') {
|
||||||
|
if (!/^[\w-]{1,64}$/.test(query.guildId)) throw Error('Invalid guild ID');
|
||||||
|
const url = new URL(`/guilds/${query.guildId}/battles`,SITE);
|
||||||
|
url.search = new URLSearchParams({minPlayers:query.minPlayers??1,minGuildPlayers:query.minGuildPlayers??1,page:query.page??1}).toString();
|
||||||
|
return readListingPage(await fetchPage(url));
|
||||||
|
}
|
||||||
|
if (path==='/battles/multi') {
|
||||||
|
if (!/^\d+(,\d+)+$/.test(query.ids)) throw Error('Invalid combined battle IDs');
|
||||||
|
const url = new URL('/battles/multi',SITE);url.searchParams.set('ids',query.ids);
|
||||||
|
return readBattlePage(await fetchPage(url));
|
||||||
|
}
|
||||||
|
if (/^\/battles\/\d+$/.test(path)) return detail(path.split('/').at(-1));
|
||||||
|
throw Error('Unsupported page request');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPublicPage(url,fetchImpl=fetch) {
|
||||||
|
if (url.origin!==SITE) throw Error('Unsupported page origin');
|
||||||
|
for (let attempt=0;attempt<3;attempt++) {
|
||||||
|
try {
|
||||||
|
const response = await fetchImpl(url,{headers:{Accept:'text/html'},redirect:'error',signal:AbortSignal.timeout(30_000)});
|
||||||
|
if (!response.ok) throw Error(`AlbionBB page returned HTTP ${response.status}: ${url}`);
|
||||||
|
const html = await response.text();
|
||||||
|
if (html.length>20_000_000) throw Error('AlbionBB page exceeds size limit');
|
||||||
|
return html;
|
||||||
|
} catch(error) {
|
||||||
|
if (attempt===2 || /HTTP (401|403|429)/.test(error.message)) throw error;
|
||||||
|
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
import { readFile, writeFile, mkdir, rename, readdir, rm } from 'node:fs/promises';
|
import { readFile, writeFile, mkdir, rename, readdir, rm } from 'node:fs/promises';
|
||||||
import { createHash } from 'node:crypto';
|
import { createHash } from 'node:crypto';
|
||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
import { fetchJson } from './fetch-battles.mjs';
|
import { createPageClient, fetchPublicPage } from './scrape-intel.mjs';
|
||||||
import { groupReports, ownGuild, ownPlayers, normalizeName, selectBattles, scanListings, mapLimit } from '../src/intel-core.js';
|
import { groupReports, ownGuild, ownPlayers, normalizeName, selectBattles, scanListings, mapLimit } from '../src/intel-core.js';
|
||||||
import { validateIndex } from '../src/intel-data.js';
|
import { validateIndex } from '../src/intel-data.js';
|
||||||
|
|
||||||
const API = 'https://api.albionbb.com/eu';
|
|
||||||
export const groupKey = ids => [...ids].map(Number).sort((a,b)=>a-b).join(',');
|
export const groupKey = ids => [...ids].map(Number).sort((a,b)=>a-b).join(',');
|
||||||
export function compactBattle(raw, guildId) {
|
export function compactBattle(raw, guildId) {
|
||||||
const guild = ownGuild(raw,guildId);
|
const guild = ownGuild(raw,guildId);
|
||||||
@@ -62,7 +61,7 @@ export async function collectGuild(name, previous, {request,asOf=new Date().toIS
|
|||||||
multis[key] = compactBattle(raw,guild.Id);
|
multis[key] = compactBattle(raw,guild.Id);
|
||||||
if (++done%10===0 || done===required.size) log(`${guild.Name}: combined reports ${done}/${required.size}`);
|
if (++done%10===0 || done===required.size) log(`${guild.Name}: combined reports ${done}/${required.size}`);
|
||||||
});
|
});
|
||||||
return {schemaVersion:1,guild,asOf,coverageDays:60,battles,multis};
|
return {schemaVersion:1,source:'albionbb-html',guild,asOf,coverageDays:60,battles,multis};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
|
if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
|
||||||
@@ -74,13 +73,12 @@ if (process.argv[1] && import.meta.url===pathToFileURL(process.argv[1]).href) {
|
|||||||
const supplied = process.env.INTEL_GUILD_NAME?.trim();
|
const supplied = process.env.INTEL_GUILD_NAME?.trim();
|
||||||
const names = [...new Map([...configured,...manifest.guilds.map(g=>g.Name),...(supplied?[supplied]:[])].map(name=>[normalizeName(name),name.trim()])).values()];
|
const names = [...new Map([...configured,...manifest.guilds.map(g=>g.Name),...(supplied?[supplied]:[])].map(name=>[normalizeName(name),name.trim()])).values()];
|
||||||
let nextStart = 0;
|
let nextStart = 0;
|
||||||
const request = async(path,query={})=>{
|
const fetchPage = async url=>{
|
||||||
const start = Math.max(Date.now(),nextStart); nextStart = start+220;
|
const start = Math.max(Date.now(),nextStart); nextStart = start+220;
|
||||||
await new Promise(resolve=>setTimeout(resolve,Math.max(0,start-Date.now())));
|
await new Promise(resolve=>setTimeout(resolve,Math.max(0,start-Date.now())));
|
||||||
const url = new URL(API+path);
|
return fetchPublicPage(url);
|
||||||
for (const [key,value] of Object.entries(query)) url.searchParams.set(key,value);
|
|
||||||
return fetchJson(url);
|
|
||||||
};
|
};
|
||||||
|
const request = createPageClient({fetchPage,knownGuilds:manifest.guilds});
|
||||||
const entries = [], asOf = new Date().toISOString();
|
const entries = [], asOf = new Date().toISOString();
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
const old = manifest.guilds.find(g=>normalizeName(g.Name)===normalizeName(name));
|
const old = manifest.guilds.find(g=>normalizeName(g.Name)===normalizeName(name));
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {readPageData,readBattlePage,readListingPage,createPageClient,fetchPublicPage} from '../scripts/scrape-intel.mjs';
|
||||||
|
|
||||||
|
const report={albionId:123,startedAt:'2026-10-20T12:00:00Z',finishedAt:'2026-10-20T12:01:00Z',totalPlayers:40,totalFame:100001,
|
||||||
|
guilds:[{albionId:'guild',name:'OneUP',players:4,kills:2,deaths:1,killFame:100001}],
|
||||||
|
players:[{name:'Player',guildName:'OneUP',role:'tank',weapon:{name:'2H_MACE',type:'T8_2H_MACE',quality:4}}]};
|
||||||
|
function page(data) {
|
||||||
|
const values=[['ShallowReactive',1],{data:2},['ShallowReactive',3],{}];
|
||||||
|
function store(value) {
|
||||||
|
const index=values.length;values.push(null);
|
||||||
|
values[index]=Array.isArray(value)?value.map(store):value && typeof value==='object'?Object.fromEntries(Object.entries(value).map(([key,v])=>[key,store(v)])):value;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
for(const [key,value] of Object.entries(data))values[3][key]=store(value);
|
||||||
|
return `<html><script>throw new Error('must never execute page code')</script><script data-nuxt-data="nuxt-app" id="__NUXT_DATA__" type="application/json">${JSON.stringify(values)}</script></html>`;
|
||||||
|
}
|
||||||
|
test('HTML scraper decodes exact fame, roster, weapon and role from server-rendered data',()=>{
|
||||||
|
const html=page({'$arbitrary-build-key':report});
|
||||||
|
assert.deepEqual(readBattlePage(html),report);
|
||||||
|
assert.deepEqual(readPageData(html),[report]);
|
||||||
|
assert.deepEqual(readListingPage(page({identity:{name:'OneUP'},'$other-key':[report]})),[report]);
|
||||||
|
assert.deepEqual(readListingPage(page({'$empty-key':[]})),[]);
|
||||||
|
});
|
||||||
|
test('scraper rejects missing, malformed or incompatible payloads instead of empty success',()=>{
|
||||||
|
assert.throws(()=>readBattlePage('<html>Access denied</html>'),/server-rendered data/);
|
||||||
|
assert.throws(()=>readListingPage(page({unrelated:{message:'API unavailable'}})),/listing missing/);
|
||||||
|
assert.throws(()=>readBattlePage(page({'$key':[report]})),/Battle data missing/);
|
||||||
|
const bad=page({x:report}).replace(/"albionId":\d+/,'"albionId":999999');
|
||||||
|
assert.throws(()=>readPageData(bad),/out of bounds/);
|
||||||
|
});
|
||||||
|
test('page client retrieves listings, single and multi reports using only public website URLs',async()=>{
|
||||||
|
const calls=[];
|
||||||
|
const request=createPageClient({knownGuilds:[{Id:'guild',Name:'OneUP',file:'private-cache-detail.json'}],fetchPage:async url=>{
|
||||||
|
calls.push(url);
|
||||||
|
assert.equal(url.origin,'https://europe.albionbb.com');
|
||||||
|
return page({data:url.pathname.endsWith('/battles')?[report]:report});
|
||||||
|
}});
|
||||||
|
assert.deepEqual(await request('/guilds/search',{search:'OneUP'}),[{Id:'guild',Name:'OneUP'}]);
|
||||||
|
assert.equal(calls.length,0);
|
||||||
|
assert.deepEqual(await request('/battles',{guildId:'guild',minPlayers:40,minGuildPlayers:1,page:2}),[report]);
|
||||||
|
assert.equal(calls[0].pathname,'/guilds/guild/battles');assert.equal(calls[0].searchParams.get('minPlayers'),'40');
|
||||||
|
assert.equal(calls[0].searchParams.get('page'),'2');
|
||||||
|
assert.deepEqual(await request('/battles/123'),report);
|
||||||
|
assert.deepEqual(await request('/battles/multi',{ids:'123,124'}),report);
|
||||||
|
assert.equal(calls.at(-1).pathname,'/battles/multi');assert.equal(calls.at(-1).searchParams.get('ids'),'123,124');
|
||||||
|
assert.ok(calls.every(url=>!url.hostname.startsWith('api.')));
|
||||||
|
});
|
||||||
|
test('new guild discovery reads public search and detail pages with encoded names',async()=>{
|
||||||
|
const calls=[];
|
||||||
|
const request=createPageClient({fetchPage:async url=>{
|
||||||
|
calls.push(url);return page({data:url.pathname==='/'?[report]:report});
|
||||||
|
}});
|
||||||
|
assert.deepEqual(await request('/guilds/search',{search:'OneUP'}),[{Id:'guild',Name:'OneUP'}]);
|
||||||
|
assert.equal(calls[0].pathname,'/');assert.equal(calls[0].searchParams.get('search'),'OneUP');
|
||||||
|
assert.equal(calls[1].pathname,'/battles/123');
|
||||||
|
});
|
||||||
|
test('HTML requests stop on access/rate restrictions and never fetch another origin',async()=>{
|
||||||
|
for(const status of [403,429]){
|
||||||
|
let calls=0;
|
||||||
|
await assert.rejects(fetchPublicPage(new URL('https://europe.albionbb.com/battles/123'),async()=>{
|
||||||
|
calls++;return new Response('',{status});
|
||||||
|
}),new RegExp(`HTTP ${status}`));
|
||||||
|
assert.equal(calls,1);
|
||||||
|
}
|
||||||
|
await assert.rejects(fetchPublicPage(new URL('https://unrelated.test')),/Unsupported page origin/);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user