#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch pinned WiiBrew pages into reference/wiki/. WiiBrew (https://wiibrew.org) states no content licence on its pages, its About, Policy, General disclaimer or Copyrights pages (read 2026-11-26), so its facts are used and cited and its prose and tables are never copied into this repository ("facts only"; docs/sources-wii.md). **robots.txt.** WiiBrew's robots.txt (read 2026-11-26) disallows ``/w/`` for every user agent: that is where MediaWiki's ``api.php`` and ``index.php?oldid=`` live, so this script never asks for an old revision or uses the API (unlike n64-python's fetch_wiki.py). It reads only ``/wiki/``, the page as it is now, and pins what it got: the revision id the page reports (``wgRevisionId``) and the SHA-256 of the article body (the ``mw-content-text`` block). It waits two seconds between pages. Consequence: a page edited since the pin cannot be fetched at its pinned revision. The script then reports the move and keeps nothing; ``--pin`` re-pins deliberately. python -I scripts/fetch_wiki.py # fetch what is missing, check pins python -I scripts/fetch_wiki.py --verify # hash what is present, fetch nothing python -I scripts/fetch_wiki.py --pin # fetch and pin titles not yet pinned (revid 0) python -I scripts/fetch_wiki.py --repin # fetch every title now and pin it again Each page lands as reference/wiki/<title>.html (the article body) and a plain-text rendering beside it (<title>.txt) for reading; only the .html is pinned. """ from __future__ import annotations import argparse import hashlib import html import json import re import subprocess import sys import time import urllib.parse from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_wiki.json" BASE = "https://wiibrew.org/wiki/" # An honest agent name, never a browser's (the 2026-11-26 brief). USER_AGENT = "wii-python-reference-fetch/0.1 (emulator documentation; honours robots.txt)" DELAY_S = 2.0 def get(title: str) -> str: url = BASE + urllib.parse.quote(title.replace(" ", "_"), safe="/:()_-.,") result = subprocess.run( ["curl", "-sSfL", "--max-time", "120", "-A", USER_AGENT, url], capture_output=True, check=False, ) if result.returncode: raise OSError(f"{title}: " + result.stderr.decode("utf-8", "replace").strip()) return result.stdout.decode("utf-8", "replace") def article(page: str) -> tuple[int, str, str]: """Return (revision id, last-edited text, article body) from a /wiki/ page.""" rev = re.search(r'"wgRevisionId":(\d+)', page) start = page.find('<div id="mw-content-text"') end = page.find('<div class="printfooter"', start) if not rev or start < 0 or end < 0: raise ValueError("not a MediaWiki article page (a challenge or an error page?)") edited = re.search(r"This page was last edited on ([^<]+?)\.\s*<", page) # The parser report comments carry cache times; drop them so the hash is stable. body = re.sub(r"<!--.*?-->", "", page[start:end], flags=re.S) return int(rev.group(1)), edited.group(1).strip() if edited else "", body def as_text(body: str) -> str: body = re.sub(r"<(script|style)\b.*?</\1>", "", body, flags=re.S) body = re.sub(r"<(br|/p|/tr|/h[1-6]|/li|/div|/pre)\b[^>]*>", "\n", body) body = re.sub(r"<t[dh]\b[^>]*>", " | ", body) body = re.sub(r"<[^>]+>", "", body) body = html.unescape(body) return re.sub(r"\n\s*\n+", "\n\n", re.sub(r"[ \t]+", " ", body)).strip() + "\n" def local_path(title: str) -> Path: return ROOT / "reference" / "wiki" / (title.replace("/", "--").replace(" ", "_") + ".html") def sha256(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def store(title: str, body: str) -> None: path = local_path(title) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(body, encoding="utf-8") path.with_suffix(".txt").write_text(as_text(body), encoding="utf-8") def pin(everything: bool) -> int: entries = json.loads(PINS.read_text(encoding="utf-8")) problems = 0 asked = 0 for entry in entries: if entry["revid"] and not everything: continue if asked: time.sleep(DELAY_S) asked += 1 try: revid, edited, body = article(get(entry["title"])) except (OSError, ValueError) as error: print(f"ERROR: {entry['title']}: {error}") problems += 1 continue entry.update(revid=revid, edited=edited, sha256=sha256(body)) store(entry["title"], body) print(f"pinned {entry['title']} at revision {revid} ({edited})") PINS.write_text(json.dumps(entries, indent=1) + "\n", encoding="utf-8") return problems def fetch(verify_only: bool) -> int: problems = 0 fetched = 0 for entry in json.loads(PINS.read_text(encoding="utf-8")): path = local_path(entry["title"]) if path.exists(): if sha256(path.read_text(encoding="utf-8")) != entry["sha256"]: print(f"ERROR: {path.name} does not match its pin") problems += 1 continue if verify_only: print(f"missing: {path.name}") problems += 1 continue if fetched: time.sleep(DELAY_S) fetched += 1 try: revid, _, body = article(get(entry["title"])) except (OSError, ValueError) as error: print(f"ERROR: {entry['title']}: {error}") problems += 1 continue if revid != entry["revid"] or sha256(body) != entry["sha256"]: print(f"ERROR: {entry['title']} is now revision {revid}, pinned {entry['revid']}: " "old revisions live under /w/, which robots.txt disallows; re-pin deliberately") problems += 1 continue store(entry["title"], body) print(f"fetched {path.name}") return problems def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--verify", action="store_true", help="check what is present; fetch nothing") parser.add_argument("--pin", action="store_true", help="fetch and pin titles not yet pinned") parser.add_argument("--repin", action="store_true", help="fetch every title now and pin it again") args = parser.parse_args() problems = pin(args.repin) if args.pin or args.repin else fetch(args.verify) print("all pins verified" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())