#!/usr/bin/env python3 """Fetch public datasets from 17Lands.com. 17Lands publishes its bulk data as gzipped CSV files on S3. The list of available files is not served by a plain API; it lives in a Prismic CMS document of type ``public-data``. This script reads that catalog, lets you filter it, and downloads the matching files (optionally gunzipping them). Requires only the Python standard library (3.8+). Examples -------- # Show every dataset in the catalog. python scripts/fetch_17lands.py list # Show only SOS datasets. python scripts/fetch_17lands.py list --set SOS # Download the game data for SOS Premier Draft. python scripts/fetch_17lands.py fetch --set SOS --format PremierDraft --type game # Download draft + game data for the 3 most recent expansions, unzipped. python scripts/fetch_17lands.py fetch --latest 3 --type draft,game --decompress # Download the shared helper files and card lists. python scripts/fetch_17lands.py helpers """ from __future__ import annotations import argparse import gzip import json import shutil import sys import time from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import urlencode, urlparse from urllib.request import Request, urlopen PRISMIC_API = "https://17lands.cdn.prismic.io/api/v2" PRISMIC_SEARCH = PRISMIC_API + "/documents/search" USER_AGENT = "mtga-17lands-fetcher/1.0 (+https://17lands.com)" DEFAULT_OUT = Path(__file__).resolve().parent.parent / "data" / "17lands" CACHE_TTL_HOURS = 24 DATA_TYPES = ("draft", "game", "replay") CHUNK = 1 << 20 # 1 MiB # --------------------------------------------------------------------------- # # Catalog access # --------------------------------------------------------------------------- # def _http_json(url: str, timeout: float) -> dict: req = Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"}) with urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8")) def _rich_text(node) -> str: """Flatten a Prismic rich-text field into plain text.""" if isinstance(node, list): return "".join(_rich_text(item) for item in node) if isinstance(node, dict): if "text" in node: return str(node.get("text") or "") return "".join(_rich_text(v) for v in node.values()) return "" def _first_hyperlink(node) -> str | None: """Return the first hyperlink URL found anywhere in a rich-text field.""" if isinstance(node, list): for item in node: found = _first_hyperlink(item) if found: return found elif isinstance(node, dict): if node.get("type") == "hyperlink": return (node.get("data") or {}).get("url") for value in node.values(): found = _first_hyperlink(value) if found: return found return None def _basename(url: str) -> str: return Path(urlparse(url).path).name def fetch_catalog(refresh: bool, out_dir: Path, timeout: float) -> dict: """Return the parsed catalog, using an on-disk cache when possible.""" cache_file = out_dir / ".cache" / "catalog.json" if cache_file.exists() and not refresh: age = time.time() - cache_file.stat().st_mtime if age < CACHE_TTL_HOURS * 3600: try: with cache_file.open(encoding="utf-8") as fh: return json.load(fh) except (OSError, json.JSONDecodeError): pass # fall through to a network fetch api = _http_json(PRISMIC_API, timeout) ref = next((r["ref"] for r in api.get("refs", []) if r.get("isMasterRef")), None) ref = ref or next((r["ref"] for r in api.get("refs", [])), None) if not ref: raise RuntimeError("Prismic did not return a document ref") query = urlencode( { "ref": ref, "q": '[[at(document.type,"public-data")]]', "pageSize": 100, } ) payload = _http_json(f"{PRISMIC_SEARCH}?{query}", timeout) results = payload.get("results", []) if not results: raise RuntimeError("No public-data document found in the 17Lands catalog") catalog = _parse_document(results[0]) catalog["fetched_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") cache_file.parent.mkdir(parents=True, exist_ok=True) tmp = cache_file.with_suffix(".tmp") with tmp.open("w", encoding="utf-8") as fh: json.dump(catalog, fh, ensure_ascii=False, indent=1) tmp.replace(cache_file) return catalog def _parse_document(doc: dict) -> dict: data = doc.get("data", {}) datasets = [] for entry in data.get("datasets", []): urls = {} for kind in DATA_TYPES: url = _first_hyperlink(entry.get(kind + "_data")) if url: urls[kind] = url datasets.append( { "expansion": _rich_text(entry.get("expansion")).strip(), "format": _rich_text(entry.get("format")).strip(), "last_updated": _rich_text(entry.get("last_updated")).strip(), "urls": urls, } ) helpers = [] for entry in data.get("helper_files", []): url = _first_hyperlink(entry.get("file")) if url: helpers.append( { "name": _basename(url), "description": _rich_text(entry.get("description")).strip(), "last_updated": _rich_text(entry.get("last_updated")).strip(), "url": url, } ) for entry in data.get("card_lists", []): url = _first_hyperlink(entry.get("dataset")) if url: helpers.append( { "name": _basename(url), "description": "", "last_updated": _rich_text(entry.get("last_updated")).strip(), "url": url, } ) return { "source": "https://www.17lands.com/public_datasets", "datasets": datasets, "helpers": helpers, } # --------------------------------------------------------------------------- # # Filtering / listing # --------------------------------------------------------------------------- # def _split(value: str | None) -> list[str]: if not value: return [] return [part.strip() for part in value.split(",") if part.strip()] def select_datasets(catalog: dict, args) -> list[dict]: records = catalog["datasets"] if not records: return [] sets = {s.upper() for s in _split(args.set)} formats = {f.lower() for f in _split(args.format)} types = [t.lower() for t in _split(args.type)] or ["game"] for t in types: if t not in DATA_TYPES: raise SystemExit(f"unknown --type {t!r}; choose from {', '.join(DATA_TYPES)}") if args.latest: ordered = sorted( {r["expansion"] for r in records}, key=lambda e: max(r["last_updated"] for r in records if r["expansion"] == e), reverse=True, ) keep = set(ordered[: args.latest]) records = [r for r in records if r["expansion"] in keep] if sets: records = [r for r in records if r["expansion"].upper() in sets] if formats: records = [r for r in records if r["format"].lower() in formats] selected = [] for rec in records: for kind in types: url = rec["urls"].get(kind) if url: selected.append( { "expansion": rec["expansion"], "format": rec["format"], "last_updated": rec["last_updated"], "type": kind, "url": url, } ) return selected def cmd_list(catalog: dict, args) -> int: records = catalog["datasets"] sets = {s.upper() for s in _split(args.set)} formats = {f.lower() for f in _split(args.format)} if sets: records = [r for r in records if r["expansion"].upper() in sets] if formats: records = [r for r in records if r["format"].lower() in formats] if not records: print("No datasets matched the given filters.") return 1 header = f"{'SET':<6} {'FORMAT':<14} {'UPDATED':<12} {'AVAILABLE':<22} URL HINT" print(header) print("-" * len(header)) for rec in sorted(records, key=lambda r: (r["last_updated"], r["expansion"], r["format"])): available = ",".join(k for k in DATA_TYPES if k in rec["urls"]) or "-" print( f"{rec['expansion']:<6} {rec['format']:<14} {rec['last_updated']:<12} " f"{available:<22} {_url_hint(rec['urls'])}" ) print(f"\n{len(records)} dataset(s). Catalog cached from {catalog.get('fetched_at', '?')}.") print("Download with: fetch --set --format --type game,draft,replay") return 0 def _url_hint(urls: dict) -> str: if not urls: return "-" first = next(iter(urls.values())) return _basename(first) # --------------------------------------------------------------------------- # # Downloading # --------------------------------------------------------------------------- # def _remote_size(url: str, timeout: float) -> int: req = Request(url, method="HEAD", headers={"User-Agent": USER_AGENT}) try: with urlopen(req, timeout=timeout) as resp: return int(resp.headers.get("Content-Length") or 0) except (HTTPError, URLError, OSError): return 0 def _human(num: float) -> str: for unit in ("B", "KiB", "MiB", "GiB", "TiB"): if abs(num) < 1024 or unit == "TiB": return f"{num:,.0f} {unit}" if unit == "B" else f"{num:,.1f} {unit}" num /= 1024 return f"{num:.1f} TiB" def download(url: str, dest: Path, *, overwrite: bool = False, quiet: bool = False, timeout: float = 60, retries: int = 3) -> tuple[str, Path, int]: """Download ``url`` to ``dest`` atomically, resuming partial files.""" dest.parent.mkdir(parents=True, exist_ok=True) expected = _remote_size(url, timeout) if not overwrite and dest.exists() and expected and dest.stat().st_size == expected: return ("skip", dest, expected) tmp = dest.with_name(dest.name + ".part") last_error = None for attempt in range(1, retries + 1): pos = tmp.stat().st_size if tmp.exists() and not overwrite else 0 headers = {"User-Agent": USER_AGENT} if pos: headers["Range"] = f"bytes={pos}-" req = Request(url, headers=headers) try: with urlopen(req, timeout=timeout) as resp: # S3 ignores Range and returns 200 if resuming isn't supported. if pos and getattr(resp, "status", 200) == 200: pos = 0 total = pos + int(resp.headers.get("Content-Length") or 0) mode = "ab" if pos else "wb" done = pos with tmp.open(mode) as out: while True: chunk = resp.read(CHUNK) if not chunk: break out.write(chunk) done += len(chunk) if not quiet: _progress(dest.name, done, total) if not quiet: sys.stderr.write("\r" + " " * 79 + "\r") tmp.replace(dest) return ("download", dest, dest.stat().st_size) except (HTTPError, URLError, OSError, TimeoutError) as exc: last_error = exc if attempt < retries: time.sleep(min(2 ** attempt, 10)) raise RuntimeError(f"failed to download {url}: {last_error}") def _progress(name: str, done: int, total: int) -> None: if total: pct = done * 100 / total msg = f" {name[:40]:<40} {pct:5.1f}% {_human(done)} / {_human(total)}" else: msg = f" {name[:40]:<40} {_human(done)}" sys.stderr.write("\r" + msg[:79]) sys.stderr.flush() def gunzip_file(path: Path, keep: bool) -> Path: target = path.with_suffix("") # strip .gz with gzip.open(path, "rb") as src, target.open("wb") as dst: shutil.copyfileobj(src, dst, CHUNK) if not keep: path.unlink() return target # --------------------------------------------------------------------------- # # Commands # --------------------------------------------------------------------------- # def _download_jobs(jobs: list[dict], out_dir: Path, args) -> int: if args.dry_run: for job in jobs: print(f"[dry-run] {job['url']}\n -> {out_dir / job['filename']}") return 0 failures = 0 quiet = args.quiet or args.jobs > 1 def run(job: dict) -> tuple[str, Path, int]: dest = out_dir / job["filename"] final = dest.with_suffix("") if args.decompress and dest.suffix == ".gz" else dest if not args.overwrite and final.exists(): return ("skip", final, final.stat().st_size) status, path, size = download( job["url"], dest, overwrite=args.overwrite, quiet=quiet, timeout=args.timeout ) if status == "download" and args.decompress and path.suffix == ".gz": path = gunzip_file(path, keep=args.keep_gz) return status, path, size if args.jobs > 1: with ThreadPoolExecutor(max_workers=args.jobs) as pool: futures = {pool.submit(run, job): job for job in jobs} for future in as_completed(futures): job = futures[future] try: status, path, size = future.result() print(f"[{status}] {path} ({_human(size)})") except Exception as exc: # noqa: BLE001 - report and keep going failures += 1 print(f"[failed] {job['filename']}: {exc}", file=sys.stderr) else: for job in jobs: try: status, path, size = run(job) print(f"[{status}] {path} ({_human(size)})") except Exception as exc: # noqa: BLE001 failures += 1 print(f"[failed] {job['filename']}: {exc}", file=sys.stderr) return 1 if failures else 0 def _dataset_jobs(selected: list[dict]) -> list[dict]: jobs = [] for rec in selected: url = rec["url"] filename = _basename(url) or f"{rec['type']}.csv.gz" jobs.append({"url": url, **rec, "filename": filename}) return jobs def cmd_fetch(catalog: dict, args) -> int: selected = select_datasets(catalog, args) if not selected: print("No datasets matched. Run `list` to see what is available.", file=sys.stderr) return 1 if not args.all and not _split(args.set) and not args.format and not args.latest: print( f"Refusing to download all {len(selected)} files. " "Narrow with --set/--format/--latest, or pass --all to confirm.", file=sys.stderr, ) return 2 return _download_jobs(_dataset_jobs(selected), Path(args.out), args) def cmd_helpers(catalog: dict, args) -> int: jobs = [ { "url": item["url"], "filename": item["name"], "expansion": "-", "format": "-", "type": "helper", } for item in catalog.get("helpers", []) ] if not jobs: print("No helper files found in the catalog.", file=sys.stderr) return 1 return _download_jobs(jobs, Path(args.out), args) # --------------------------------------------------------------------------- # # CLI # --------------------------------------------------------------------------- # def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description="Browse and download 17Lands public datasets.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__, ) parser.add_argument("--out", default=str(DEFAULT_OUT), help="output directory (default: %(default)s)") parser.add_argument("--refresh", action="store_true", help="ignore the cached catalog and refetch") parser.add_argument("--timeout", type=float, default=60, help="per-request timeout in seconds") parser.add_argument("-q", "--quiet", action="store_true", help="suppress progress output") sub = parser.add_subparsers(dest="command") def add_filter_args(p): p.add_argument("-s", "--set", help="comma-separated expansion codes, e.g. SOS,BLB") p.add_argument("-f", "--format", help="comma-separated formats, e.g. PremierDraft,TradDraft") p.add_argument("-t", "--type", default="game", help="comma-separated data types: draft,game,replay (default: game)") p_list = sub.add_parser("list", help="list datasets in the catalog") add_filter_args(p_list) p_fetch = sub.add_parser("fetch", help="download datasets") add_filter_args(p_fetch) p_fetch.add_argument("--latest", type=int, metavar="N", help="only the N most recently updated expansions") p_fetch.add_argument("--all", action="store_true", help="download everything the filters match") p_fetch.add_argument("-o", "--overwrite", action="store_true", help="redownload files that already exist") p_fetch.add_argument("-d", "--decompress", action="store_true", help="gunzip files after download") p_fetch.add_argument("--keep-gz", action="store_true", help="keep the .gz alongside the decompressed file") p_fetch.add_argument("-j", "--jobs", type=int, default=1, help="parallel downloads (default: 1)") p_fetch.add_argument("-n", "--dry-run", action="store_true", help="show what would be downloaded") p_helpers = sub.add_parser("helpers", help="download shared helper files and card lists") p_helpers.add_argument("-o", "--overwrite", action="store_true") p_helpers.add_argument("-d", "--decompress", action="store_true") p_helpers.add_argument("--keep-gz", action="store_true") p_helpers.add_argument("-j", "--jobs", type=int, default=1) p_helpers.add_argument("-n", "--dry-run", action="store_true") return parser def main(argv: list[str] | None = None) -> int: parser = build_parser() args = parser.parse_args(argv) out_dir = Path(args.out) try: catalog = fetch_catalog(args.refresh, out_dir, args.timeout) except (HTTPError, URLError, OSError, RuntimeError, json.JSONDecodeError) as exc: print(f"Could not load the 17Lands catalog: {exc}", file=sys.stderr) return 3 command = args.command or "list" if command == "list": return cmd_list(catalog, args) if command == "fetch": return cmd_fetch(catalog, args) if command == "helpers": return cmd_helpers(catalog, args) parser.error(f"unknown command {command!r}") return 2 if __name__ == "__main__": try: raise SystemExit(main()) except KeyboardInterrupt: print("\nInterrupted.", file=sys.stderr) raise SystemExit(130)