#!/usr/bin/env python3 # SPDX-License-Identifier: AGPL-3.0-only """Acquire source-native AniTrack archives. No downloads without --download.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import re import shutil import urllib.request MANIFEST_NAMES = ( "topview_core4_human_sources.json", "core4_gated_public_sources.json", "topviewmouse_source.json", ) def load_sources(root: Path) -> list[dict]: sources = [] seen = set() for name in MANIFEST_NAMES: manifest = json.loads((root / "manifests" / name).read_text()) for source in manifest["sources"]: source_id = source["id"] if not re.fullmatch(r"[a-z0-9_]+", source_id) or source_id in seen: raise ValueError(f"Unsafe or duplicate source ID: {source_id}") seen.add(source_id) names = set() for spec in source["files"]: filename = spec["name"] if (not filename or filename in {".", ".."} or "/" in filename or "\\" in filename or filename in names): raise ValueError(f"Unsafe or duplicate filename: {filename}") names.add(filename) if not spec["url"].startswith("https://"): raise ValueError("Only HTTPS source URLs are accepted") if not re.fullmatch(r"[0-9a-f]{32}", spec["md5"]): raise ValueError("Every source requires a pinned publisher MD5") sources.append(source) return sources def verify(path: Path, spec: dict) -> dict: size = path.stat().st_size if "size" in spec and size != spec["size"]: raise ValueError(f"Size mismatch for {path.name}: {size} != {spec['size']}") md5 = hashlib.md5(usedforsecurity=False) sha256 = hashlib.sha256() with path.open("rb") as handle: while chunk := handle.read(8 * 1024 * 1024): md5.update(chunk) sha256.update(chunk) if md5.hexdigest() != spec["md5"]: raise ValueError(f"Publisher MD5 mismatch for {path.name}; file not accepted") return {"name": spec["name"], "bytes": size, "md5": md5.hexdigest(), "sha256": sha256.hexdigest(), "source_url": spec["url"]} def acquire(destination: Path, spec: dict) -> dict: if destination.is_symlink(): raise ValueError(f"Refusing symlink destination: {destination}") if destination.exists(): return verify(destination, spec) # Never silently overwrite an interrupted download or unverified archive. partial = destination.with_name(destination.name + ".partial") with partial.open("xb") as target: request = urllib.request.Request(spec["url"], headers={"User-Agent": "AniTrack-source-setup/1"}) with urllib.request.urlopen(request, timeout=120) as response: if not response.url.startswith("https://"): raise ValueError("Refusing a non-HTTPS source redirect") shutil.copyfileobj(response, target, length=8 * 1024 * 1024) receipt = verify(partial, spec) partial.rename(destination) return receipt def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__) action = parser.add_mutually_exclusive_group() action.add_argument("--list", action="store_true", help="List sources; never download") action.add_argument("--download", action="store_true") parser.add_argument("--accept-source-terms", action="store_true", help="Confirm you reviewed each publisher's applicable terms") parser.add_argument("--sources", nargs="+", help="Selected source IDs; default all") parser.add_argument("--output-root", type=Path) args = parser.parse_args(argv) sources = load_sources(Path(__file__).resolve().parent) if args.sources: unknown = set(args.sources) - {source["id"] for source in sources} if unknown: parser.error(f"Unknown sources: {sorted(unknown)}") sources = [source for source in sources if source["id"] in args.sources] for source in sources: terms = source.get("license", source.get("license_note", "See publisher")) size = sum(spec.get("size", 0) for spec in source["files"]) print(f"{source['id']}: {len(source['files'])} files; known bytes={size}; {terms}") if not args.download: print("Plan only. No files downloaded. Review LICENSE.md before --download.") return if not args.accept_source_terms or args.output_root is None: parser.error("Downloads require --accept-source-terms and --output-root") root = args.output_root.resolve() root.mkdir(parents=True, exist_ok=True) for source in sources: destination = root / source["id"] / "archives" if destination.is_symlink() or destination.parent.is_symlink(): raise ValueError("Refusing a symlink archive directory") destination.mkdir(parents=True, exist_ok=True) receipts = [] for spec in source["files"]: print(f"Acquire and verify: {source['id']}/{spec['name']}", flush=True) receipts.append(acquire(destination / spec["name"], spec)) (destination.parent / "acquisition.json").write_text( json.dumps({"source": source["id"], "files": receipts}, indent=2) + "\n") print("Verified source archives acquired. No extraction or split modification performed.") if __name__ == "__main__": main()