"""Download and verify the complete Unity project snapshots. Tokens are never embedded.""" import argparse import bisect import hashlib import io import json import os from pathlib import Path, PurePosixPath import shutil import sys import zipfile REPO = "yanguanyue/unity-learning-projects" REVISION = "full-2026-10-22" def sha256(path): h = hashlib.sha256() with Path(path).open("rb") as f: for chunk in iter(lambda: f.read(4 * 1024**2), b""): h.update(chunk) return h.hexdigest() class MultipartReader(io.RawIOBase): def __init__(self, paths): super().__init__() self.paths = [Path(p) for p in paths] self.starts = [0] for path in self.paths: self.starts.append(self.starts[-1] + path.stat().st_size) self.position = 0 self.handles = {} def readable(self): return True def seekable(self): return True def tell(self): return self.position def seek(self, offset, whence=0): position = offset if whence == 0 else self.position + offset if whence == 1 else self.starts[-1] + offset if position < 0: raise ValueError("Negative seek") self.position = position return position def read(self, size=-1): remaining = self.starts[-1] - self.position if size < 0 or size > remaining: size = max(0, remaining) output = [] while size: index = bisect.bisect_right(self.starts, self.position) - 1 if index >= len(self.paths): break handle = self.handles.get(index) if handle is None: handle = self.paths[index].open("rb") self.handles[index] = handle offset = self.position - self.starts[index] handle.seek(offset) chunk = handle.read(min(size, self.starts[index + 1] - self.position)) if not chunk: raise OSError("Truncated archive part") output.append(chunk) size -= len(chunk) self.position += len(chunk) return b"".join(output) def close(self): for handle in self.handles.values(): handle.close() super().close() def safe_path(root, relative): p = PurePosixPath(relative) if p.is_absolute() or any(piece in ("..", "") or ":" in piece or "\\" in piece for piece in p.parts): raise ValueError(f"Unsafe archive path: {relative}") destination = root.joinpath(*p.parts) if not destination.resolve().is_relative_to(root.resolve()): raise ValueError(f"Path outside destination: {relative}") return destination def extract_project(parts, inventory_path, target, expected_files, expected_bytes): entries = [json.loads(line) for line in Path(inventory_path).read_text(encoding="utf-8").splitlines() if line] expected = {item["path"]: item for item in entries if item["type"] == "file"} if len(expected) != expected_files or sum(item["bytes"] for item in expected.values()) != expected_bytes: raise ValueError("Inventory totals do not match manifest") temporary = target.with_name(target.name + ".restoring") if target.exists() or temporary.exists(): raise FileExistsError(f"Destination already exists; nothing overwritten: {target}") temporary.mkdir(parents=True) total = 0 with MultipartReader(parts) as stream, zipfile.ZipFile(stream) as archive: members = [m for m in archive.infolist() if not m.is_dir()] if len(members) != expected_files or {m.filename for m in members} != set(expected): raise ValueError("Archive contents do not match inventory") for item in entries: if item["type"] == "directory": safe_path(temporary, item["path"]).mkdir(parents=True, exist_ok=True) for number, member in enumerate(members, 1): record = expected[member.filename] destination = safe_path(temporary, member.filename) destination.parent.mkdir(parents=True, exist_ok=True) h = hashlib.sha256() size = 0 with archive.open(member) as original, destination.open("xb") as out: for chunk in iter(lambda: original.read(1024**2), b""): out.write(chunk) h.update(chunk) size += len(chunk) if size != record["bytes"] or h.hexdigest() != record["sha256"]: raise ValueError(f"File verification failed: {member.filename}") os.utime(destination, ns=(record["mtime_ns"], record["mtime_ns"])) total += size if number % 1000 == 0: print(f"Verifying and restoring {target.name}: {number}/{expected_files} files", flush=True) if total != expected_bytes: raise ValueError("Restored byte count differs") temporary.rename(target) print(f"Restored and verified: {target}", flush=True) def main(): parser = argparse.ArgumentParser(description="Download complete Unity learning project backups") parser.add_argument("--only", choices=["all", "MMONetcode", "BraverGame", "Zip"], default="all") parser.add_argument("--root", type=Path, default=Path(r"F:\Game")) parser.add_argument("--cache", type=Path, default=Path(__file__).resolve().parent / "download-cache") parser.add_argument("--revision", default=REVISION) parser.add_argument("--check-connection", action="store_true") args = parser.parse_args() from huggingface_hub import hf_hub_download def fetch(path, expected=None): local = Path(hf_hub_download(repo_id=REPO, repo_type="dataset", filename=path, revision=args.revision, local_dir=args.cache)) if expected and (local.stat().st_size != expected["bytes"] or sha256(local) != expected["sha256"]): raise ValueError(f"Download verification failed: {path}") return local manifest_file = fetch("manifest.json") manifest = json.loads(manifest_file.read_text(encoding="utf-8")) if manifest["repo_id"] != REPO or manifest["schema_version"] != 1: raise ValueError("Unexpected manifest") if args.check_connection: print(json.dumps({"repository": REPO, "snapshot": manifest["snapshot"], "original_bytes": manifest["original_bytes"], "connection": "ok"}, ensure_ascii=False)) return for item in manifest["artifacts"]: if args.only not in ("all", item["name"]): continue target = safe_path(args.root, item["restore_relative"]) if target.exists(): print(f"Already exists; skipped without overwriting: {target}", flush=True) continue print(f"Downloading {item['name']} ({item['source_bytes']/1024**3:.2f} GiB original)", flush=True) if item["kind"] == "multipart_zip": inventory = fetch(item["inventory"]["path"], item["inventory"]) parts = [fetch(part["path"], part) for part in item["parts"]] extract_project(parts, inventory, target, item["file_count"], item["source_bytes"]) elif item["kind"] == "original_files": temporary = target.with_name(target.name + ".restoring") if temporary.exists(): raise FileExistsError(f"An earlier restore needs inspection: {temporary}") temporary.mkdir(parents=True) for record in item["files"]: source = fetch(record["path"], record) destination = safe_path(temporary, record["name"]) shutil.copyfile(source, destination) if sha256(destination) != record["sha256"]: raise ValueError(f"Restored zip differs: {record['name']}") os.utime(destination, ns=(record["mtime_ns"], record["mtime_ns"])) temporary.rename(target) print(f"Restored original ZIP files: {target}", flush=True) print("Complete. Existing local projects were never overwritten.", flush=True) if __name__ == "__main__": try: main() except Exception as exc: print(f"Restore stopped: {exc}", file=sys.stderr, flush=True) raise SystemExit(1)