Files
pokemon/scripts/update_swarm/fetch.py
T

60 lines
2.2 KiB
Python

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)
return urllib.request.urlopen(req)
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)
h = hashlib.sha256()
size = 0
with _open(fetch_url, opener) as resp, open(dest_path, "wb") as out:
while True:
chunk = resp.read(1024 * 1024)
if not chunk:
break
out.write(chunk)
h.update(chunk)
size += len(chunk)
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