from __future__ import annotations import hashlib, os, re, urllib.request, zipfile from update_swarm.census import _from_text, CHANGELOG_NAMES from update_swarm.hosts import classify_url from update_swarm.versions import compare_versions UA = "Mozilla/5.0 (homelab personal archival)" MF = re.compile(r"https://download\d+\.mediafire\.com/[^\"'\s<>]+") class GatedHostError(ValueError): pass def resolve_mediafire(html: str) -> str | None: m = MF.search(html or "") return m.group(0) if m else None def _open(url: str, opener=None): req = urllib.request.Request(url, headers={"User-Agent": UA}) if opener: return opener(req, timeout=60) return urllib.request.urlopen(req, timeout=60) def download(url: str, dest_path: str, opener=None) -> dict: host, gate = classify_url(url) if gate == "gated": raise GatedHostError(f"{host} is gated: {url}") if host == "mega": raise NotImplementedError("mega downloads use megadl in the CLI") fetch_url = url if host == "mediafire" and "/file/" in url: with _open(url, opener) as resp: html = resp.read().decode("utf-8", "ignore") direct = resolve_mediafire(html) if not direct: raise ValueError("no mediafire direct link") fetch_url = direct os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True) part_path = dest_path + ".part" h = hashlib.sha256() size = 0 try: with _open(fetch_url, opener) as resp, open(part_path, "wb") as out: while True: chunk = resp.read(1024 * 1024) if not chunk: break out.write(chunk) h.update(chunk) size += len(chunk) except BaseException: if os.path.exists(part_path): os.remove(part_path) raise os.replace(part_path, dest_path) return {"path": dest_path, "sha256": h.hexdigest(), "size": size, "url": fetch_url} def english_mismatch(archive_path: str, expected_version: str) -> bool: if not zipfile.is_zipfile(archive_path): return False with zipfile.ZipFile(archive_path) as z: for n in z.namelist(): if os.path.basename(n).lower() in CHANGELOG_NAMES: found = _from_text(z.read(n).decode("utf-8", "ignore")) if found and compare_versions(found, expected_version) != "eq": return True return False