Files
libretro/scripts/scraper/redump_dat_scraper.py
T
Abdessamad Derraz f61c2cb7d4 refactor: one network layer for the scrapers
Each network job had several copies. One is kept per job and
every caller uses it.

- Source revision: model.sourcerevision (source_revision, required_revision,
  platform_revision) replaces BaseTargetScraper's pattern list, the
  exporter's _REVISION, the four launcher_revision copies and RetroBat's
  own YAML reader. It reads the union of the shapes: GitHub raw, blob and
  tree with or without a path after the revision, GitLab raw, blob, tree
  and archive, codeload tar.gz and zip. The target scrapers now answer
  for RetroDECK, NextUI, MinUI and MyMinUI, whose tree URLs end at the
  commit, and the exporter reads GitLab blob and tree and codeload zip.
  EmuDeck and RetroBat still require a 40-hex commit, and each launcher
  reader requires its own repository in the URL.
- Latest release: fetch_github_latest_version, type-checked, is the only
  lookup. mame_hash_scraper, romset_dat_importer and the Lakka target
  scraper call it. romset_dat_importer's NoReleaseError is gone: a
  release without a tag raises RuntimeError.
- Tree listing: github_tree and tree_entries refuse a truncated or
  unreadable listing. The libretro and core-info scrapers share
  core_info_files and fetch_info_file, with libretro's refusal of an empty
  listing. The core-info listing and the RetroDECK, ROCKNIX launcher and
  libretro listings were not checked for truncation before.
- GET: fetch_bytes is the one request path. fetch_text, fetch_present
  (None on 404 only), github_json and download are built on it, so every
  read retries 429 and 5xx, caps the body and raises FetchError, a
  ConnectionError carrying the HTTP status. The target scrapers' own
  fetch_text raised RuntimeError: they now raise FetchError, and an
  optional Batocera board include is skipped on 404 only, not on any
  failure. The exporter's originals, MiSTer, RetroPie, redump and the
  buildbot index go through it too.
- Headers: core.upstream.forge_headers is the one builder. The token goes
  to api.github.com and raw.githubusercontent.com, the host compared
  whole, as Bearer. A URL that only names api.github.com in its query
  got the scrapers' token before, and profile_sync sent its token to
  github.com, whose release downloads redirect to asset storage with the
  header. Scraper reads of raw files now carry the token.
- Submodule commit: submodule_commit checks that the path is a
  submodule. Batocera's target scraper accepted any contents answer with
  a sha, a directory's tree sha included.
- Download: download streams through a scratch file renamed into place,
  retries like fetch_bytes, can keep an existing file and returns the
  Content-Disposition. It replaces the _download of romset_dat_importer
  and game_dat_importer.
2026-11-20 20:02:15 +01:00

100 lines
3.5 KiB
Python

"""Fetch Redump BIOS DAT files and write a provenance snapshot.
Redump serves BIOS DATs as Logiqx files linked from
https://redump.info/downloads. The links were static files under
/static/bios/<name>.dat and are now one route per system,
/bios/<CODE> (PSX, PS2, GC, XBOX), served as an attachment. The
downloads page is scanned for either shape, so new BIOS DATs are
picked up without code changes.
Run manually, then commit the snapshot:
python -m scripts.scraper.redump_dat_scraper --dry-run
python -m scripts.scraper.redump_dat_scraper --output provenance/redump.json
"""
from __future__ import annotations
import argparse
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from model.dumpcatalog import write_provenance_snapshot
from .base_scraper import fetch_bytes
from .logiqx_parser import parse_logiqx, validate_logiqx_format
BASE_URL = "https://redump.info"
DOWNLOADS_URL = f"{BASE_URL}/downloads"
def _fetch(url: str) -> str:
return fetch_bytes(url).decode("utf-8", "replace")
def discover_bios_datfiles(downloads_html: str) -> list[str]:
"""Extract BIOS DAT paths from the downloads page."""
paths = set(re.findall(r'href="(/static/bios/[^"]+\.dat)"', downloads_html))
paths.update(re.findall(r'href="(/bios/[A-Za-z0-9_-]+)"', downloads_html))
return sorted(paths)
def parse_redump_dat(content: str) -> tuple[str, str, list[dict]]:
"""Parse a Redump Logiqx BIOS DAT into provenance entries.
The machine description carries the useful context (hardware
model, kernel or firmware version), so it is kept per entry.
"""
dat = parse_logiqx(content)
return dat.name, dat.version, dat.provenance_entries()
def fetch_snapshot() -> tuple[dict, list[dict]]:
"""Fetch all Redump BIOS DATs. Returns (dats metadata, entries)."""
paths = discover_bios_datfiles(_fetch(DOWNLOADS_URL))
if not paths:
raise ValueError("No BIOS datfile links found on downloads page")
dats = {}
entries = []
for path in paths:
content = _fetch(f"{BASE_URL}{path}")
if not validate_logiqx_format(content):
raise ValueError(f"Unexpected DAT format for {path}")
name, version, dat_entries = parse_redump_dat(content)
dats[name] = version
entries.extend(dat_entries)
return dats, entries
def main() -> int:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Fetch Redump BIOS DAT provenance")
parser.add_argument("--dry-run", action="store_true", help="Show fetched entries")
parser.add_argument(
"--output", "-o", default="provenance/redump.json", help="Snapshot output path"
)
args = parser.parse_args()
try:
dats, entries = fetch_snapshot()
except (ConnectionError, ValueError) as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if args.dry_run:
for dat in sorted(dats):
count = sum(1 for e in entries if e["dat"] == dat)
print(f" {dat} ({dats[dat]}): {count} entries")
print(f"\nTotal: {len(entries)} entries across {len(dats)} DATs")
return 0
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
imported_at = datetime.now(timezone.utc).strftime("%Y-%m-%d")
written = write_provenance_snapshot(args.output, "redump", imported_at, dats, entries)
status = "Written" if written else "Unchanged"
print(f"{status} {args.output}: {len(entries)} entries from {len(dats)} DATs")
return 0
if __name__ == "__main__":
sys.exit(main())