Files
libretro/scripts/scraper/retrobat_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

298 lines
11 KiB
Python

#!/usr/bin/env python3
"""Scraper for RetroBat batocera-systems.json.
Source: https://github.com/RetroBat-Official/emulatorlauncher
Format: JSON with system keys containing biosFiles arrays
Hash: MD5 primary
"""
from __future__ import annotations
import re
from pathlib import Path
from model.sourcerevision import platform_revision, required_revision
from .base_scraper import (
BaseScraper,
BiosRequirement,
fetch_branch_head,
fetch_bytes,
fetch_github_latest_version,
fetch_text,
json_object,
systems_from_requirements,
)
from .batocera_scraper import SYSTEM_SLUG_MAP as BATOCERA_SLUGS
from .retrobat_launchers import SOURCE_FILES as LAUNCHER_FILES
from .retrobat_launchers import extract_launchers
PLATFORM_NAME = "retrobat"
PLATFORM_FILE = Path(__file__).resolve().parents[2] / "platforms" / "retrobat.yml"
LAUNCHER_REPO = "RetroBat-Official/emulatorlauncher"
SOURCE_URL = (
"https://raw.githubusercontent.com/RetroBat-Official/emulatorlauncher/"
"{rev}/batocera-systems/Resources/batocera-systems.json"
)
LAUNCHER_FILE_URL = (
"https://raw.githubusercontent.com/RetroBat-Official/emulatorlauncher/{rev}/{path}"
)
GITHUB_REPO = "RetroBat-Official/retrobat"
ES_SYSTEMS_URL = (
"https://raw.githubusercontent.com/RetroBat-Official/retrobat/{tag}"
"/system/templates/emulationstation/es_systems.cfg"
)
def es_systems_dual(text: str) -> set[str]:
"""Emulators es_systems.cfg offers both as a libretro core and standalone."""
from model.safeparse import parse_untrusted_xml
libretro: set[str] = set()
standalone: set[str] = set()
for emulator in parse_untrusted_xml(text, "es_systems.cfg").iter("emulator"):
name = (emulator.get("name") or "").strip()
if name == "libretro":
libretro |= {(core.text or "").strip() for core in emulator.iter("core")} - {""}
elif name:
standalone.add(name)
return libretro & standalone
def es_systems_cores(text: str) -> tuple[set[str], set[str]]:
"""Every core RetroBat's ES offers, and the emulators it runs standalone.
emulatorlauncher starts what es_systems.cfg lists: a libretro core by its
name under ``<emulator name="libretro">``, any other emulator by its own
name. batocera-systems.json names BIOS files only, so the platform read
from it alone had no core list and relied on one kept by hand.
"""
from model.safeparse import parse_untrusted_xml
root = parse_untrusted_xml(text, "es_systems.cfg")
cores: set[str] = set()
standalone: set[str] = set()
for emulator in root.iter("emulator"):
name = (emulator.get("name") or "").strip()
if not name:
continue
listed = {(core.text or "").strip() for core in emulator.iter("core")} - {""}
if name == "libretro":
cores |= listed
else:
cores.add(name)
standalone.add(name)
return cores, standalone
def es_systems_libretro_systems(text: str) -> dict[str, list[str]]:
"""libretro core -> the ES systems es_systems.cfg offers it for.
emulatorLauncher hands a libretro core saves\\<system> at each launch
(LibRetro.Generator.cs Configure: savefile_directory), so a file a core
reads below its save directory sits once in each of these system
folders. A commented-out system is no element and counts for nothing.
"""
from model.safeparse import parse_untrusted_xml
found: dict[str, set[str]] = {}
for system in parse_untrusted_xml(text, "es_systems.cfg").iter("system"):
name = (system.findtext("name") or "").strip()
if not name:
continue
for emulator in system.iter("emulator"):
if (emulator.get("name") or "").strip() != "libretro":
continue
for core in emulator.iter("core"):
core_name = (core.text or "").strip()
if core_name:
found.setdefault(core_name, set()).add(name)
return {core: sorted(systems) for core, systems in sorted(found.items())}
def pinned_revision(platform_file: Path = PLATFORM_FILE) -> str:
"""The emulatorLauncher commit platforms/retrobat.yml was read from.
A rescrape reads this commit unless told to move, so a change to an
extractor shows in the diff alone, without upstream's commits since.
"""
return platform_revision(platform_file, LAUNCHER_REPO, commit=True)
def resolve_revision(revision: str | None) -> str:
"""The commit to read: the pin when None, a branch's head, or a sha."""
if revision is None:
return pinned_revision()
if re.fullmatch(r"[0-9a-f]{40}", revision):
return revision
return fetch_branch_head(LAUNCHER_REPO, revision)
def fetch_launchers(rev: str) -> list[dict]:
"""Launcher records read from the generators at the commit the BIOS list comes from."""
texts = {
path: fetch_bytes(LAUNCHER_FILE_URL.format(rev=rev, path=path)).decode("utf-8-sig")
for path in LAUNCHER_FILES
}
return extract_launchers(texts)
# RetroBat's system keys are Batocera's (its emulatorlauncher reads the same
# batocera-systems.json format): psx, nds and atari800 met no profile system
# until the two shared one map.
SYSTEM_SLUG_MAP = {
**BATOCERA_SLUGS,
"amiga4000": "commodore-amiga",
"arcadia": "emerson-arcadia-2001",
"ecwolf": "wolfenstein3d",
"namco2x6": "namco-system246",
"ps2": "sony-playstation-2",
"ps3": "sony-playstation-3",
"psvita": "sony-playstation-vita",
"gsplus": "apple-iigs",
}
class Scraper(BaseScraper):
"""Scraper for RetroBat batocera-systems.json."""
def __init__(self, url: str | None = None, revision: str | None = None) -> None:
# The BIOS list and the generators are read at one commit, the one
# platforms/retrobat.yml pins unless a revision moves it (--revision
# master reads the branch head). The commit read is recorded.
if url is None:
url = SOURCE_URL.format(rev=resolve_revision(revision))
elif revision is not None:
raise ValueError("pass a url or a revision, not both")
super().__init__(url=url)
def fetch_requirements(self) -> list[BiosRequirement]:
"""Parse batocera-systems.json and return BIOS requirements."""
raw = self._fetch_raw()
if not self.validate_format(raw):
raise ValueError("batocera-systems.json format validation failed")
data = self._fetch_json()
requirements = []
for sys_key, sys_data in data.items():
if not isinstance(sys_data, dict):
continue
bios_files = sys_data.get("biosFiles", [])
if not isinstance(bios_files, list):
continue
for bios in bios_files:
if not isinstance(bios, dict):
continue
declared_path = bios.get("file", "")
file_path = declared_path
md5 = bios.get("md5", "")
if not file_path:
continue
# Strip bios/ prefix from file paths
if file_path.startswith("bios/"):
file_path = file_path[5:]
name = file_path.split("/")[-1] if "/" in file_path else file_path
native: dict[str, object] = {}
sys_name = sys_data.get("name", "") if isinstance(sys_data, dict) else ""
if sys_name:
native["native_name"] = sys_name
# One held file of a group is enough (Program.cs): verify reads it.
if bios.get("group"):
native["group"] = str(bios["group"])
requirements.append(
BiosRequirement(
name=name,
system=SYSTEM_SLUG_MAP.get(sys_key, sys_key),
md5=md5 or None,
destination=file_path,
required=not bios.get("optional", False),
native_id=sys_key,
native_path=declared_path,
native=native,
)
)
return requirements
def validate_format(self, raw_data: str) -> bool:
"""Validate that raw_data is valid JSON containing biosFiles entries."""
data = json_object(raw_data)
if data is None:
return False
has_bios = False
for sys_data in data.values():
if isinstance(sys_data, dict) and "biosFiles" in sys_data:
has_bios = True
break
return has_bios
def generate_platform_yaml(self) -> dict:
"""Generate a platform YAML config dict from scraped data."""
requirements = self.fetch_requirements()
source_data = self._fetch_json()
display_names: dict[str, str] = {}
for sys_key, sys_data in source_data.items():
if isinstance(sys_data, dict):
dname = sys_data.get("name", "")
if dname:
slug = SYSTEM_SLUG_MAP.get(sys_key, sys_key)
display_names[slug] = dname
systems = systems_from_requirements(
requirements,
lambda req: {"name": display_names[req.system]} if display_names.get(req.system) else {},
)
version = fetch_github_latest_version(GITHUB_REPO)
es_url = ES_SYSTEMS_URL.format(tag=version)
es_text = fetch_text(es_url)
cores, standalone = es_systems_cores(es_text)
dual = es_systems_dual(es_text)
libretro_systems = es_systems_libretro_systems(es_text)
if not cores:
raise RuntimeError(f"es_systems.cfg at {version} names no core")
return {
"platform": "RetroBat",
"version": version,
"homepage": "https://www.retrobat.org",
"source": self.url,
"base_destination": "bios",
"hash_type": "md5",
"verification_mode": "md5",
"cores": sorted(cores),
"standalone_cores": sorted(standalone),
# Launched both ways: each layout gets its files.
**({"dual_mode_cores": sorted(dual)} if dual else {}),
"systems": systems,
# The systems each libretro core runs for: its save folders.
"libretro_systems": libretro_systems,
"launchers": fetch_launchers(required_revision(self.url, LAUNCHER_REPO, commit=True)),
}
def main() -> None:
from scripts.scraper.base_scraper import scraper_cli
scraper_cli(Scraper, "Scrape retrobat BIOS requirements")
if __name__ == "__main__":
main()