"""Discover changed Fonsora editions and retrieve one reviewed, direct-access file.""" import argparse import hashlib import json import re import sys import xml.etree.ElementTree as ET from datetime import datetime from pathlib import Path from tempfile import NamedTemporaryFile from urllib.parse import urlencode from urllib.request import Request, urlopen ORIGIN = "https://fonsora.net" CATALOG = ORIGIN + "/data/catalog.json" EDITION_ID = r"[a-z0-9-]+(?:/[a-z0-9-]+)+" NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}" MEDIA = {"csv": "text/csv", "parquet": "application/vnd.apache.parquet"} def inventory(path): root = ET.parse(path).getroot() if root.tag != NS + "urlset": raise ValueError("Expected the Fonsora edition sitemap") records = {} catalog_seen = False for row in root.findall(NS + "url"): loc = row.findtext(NS + "loc", "") if not loc.startswith(ORIGIN + "/"): raise ValueError("Sitemap contains a missing or foreign URL") if loc == ORIGIN + "/data/": catalog_seen = True match = re.fullmatch(re.escape(ORIGIN) + "/data/(" + EDITION_ID + ")/", loc) if not match and loc.startswith(ORIGIN + "/data/") and loc not in {ORIGIN + "/data/", CATALOG}: raise ValueError(f"Unexpected data URL in sitemap: {loc}") if match: key = match.group(1) stamp = row.findtext(NS + "lastmod", "") if key in records or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", stamp): raise ValueError(f"Duplicate edition or missing revision date for {key}") datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ") records[key] = stamp if not catalog_seen: raise ValueError("Sitemap is missing the Fonsora data catalog") return records def changes(previous, current): for key in sorted(previous.keys() | current.keys()): if previous.get(key) != current.get(key): item = {"id": key, "url": f"{ORIGIN}/data/{key}/"} if key in current: item.update(status="updated" if key in previous else "added", lastmod=current[key]) item["manifest"] = CATALOG + "?" + urlencode({"view": "manifest", "id": key}) else: item["status"] = "delisted" yield item def open_url(url): response = urlopen(Request(url, headers={"User-Agent": "Fonsora-Example/1.0"}), timeout=30) if response.status != 200 or response.geturl() != url: response.close() raise ValueError("Expected a full response from the requested Fonsora URL") return response def download(key, fmt, destination): if not re.fullmatch(EDITION_ID, key): raise ValueError("Use the edition identifier from a catalog search result") with open_url(CATALOG + "?" + urlencode({"view": "manifest", "id": key})) as response: manifest = json.load(response) landing = f"{ORIGIN}/data/{key}/" if manifest["identifier"] != key or manifest["url"] != landing: raise ValueError("Manifest identifies a different edition") if manifest["agreement"] is not None: raise ValueError(f"This edition requires an agreement. Visit {landing}") matches = [f for f in manifest["files"] if f["mediaType"] == MEDIA[fmt] and f["linkType"] == "download"] if len(matches) != 1: raise ValueError(f"Expected one direct {fmt} file") file = matches[0] digest = file["sha256"] if not re.fullmatch(r"[a-f0-9]{64}", digest) or file["href"] != f"{landing}{digest}.{fmt}": raise ValueError("Unexpected checksum or distribution URL") expected = file["bytes"] if type(expected) is not int or expected < 0: raise ValueError("Invalid distribution size") temp = None try: with open_url(file["href"]) as response, NamedTemporaryFile(dir=destination.parent, delete=False) as output: temp = Path(output.name) size = 0 check = hashlib.sha256() for chunk in iter(lambda: response.read(65536), b""): size += len(chunk) if size > expected: raise ValueError("File exceeds its reviewed size") check.update(chunk) output.write(chunk) if size != expected or check.hexdigest() != digest: raise ValueError("File failed its size or SHA-256 check") temp.replace(destination) finally: if temp is not None and temp.exists(): temp.unlink() def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) diff = commands.add_parser("changes", help="Compare saved copies of /sitemap.xml and print JSON Lines") diff.add_argument("current", type=Path) diff.add_argument("--previous", type=Path) fetch = commands.add_parser("download", help="Save a direct-access file after checking its manifest") fetch.add_argument("identifier") fetch.add_argument("format", choices=MEDIA) fetch.add_argument("destination", type=Path) args = parser.parse_args() if args.command == "changes": previous = inventory(args.previous) if args.previous else {} for row in changes(previous, inventory(args.current)): print(json.dumps(row)) else: download(args.identifier, args.format, args.destination) if __name__ == "__main__": try: main() except (OSError, ValueError, KeyError, ET.ParseError) as exc: sys.exit(str(exc))