#!/usr/bin/env python3 """Fetch CODE (AIUB) final global ionosphere maps, one IONEX file per UT day. Usage: python3 -I fetch_code_gim.py [--sleep S] dates.txt holds one YYYY-MM-DD per line. Files go to //. Names: CODGddd0.yyI.Z up to 2022 day 330, COD0OPSFIN_yyyyddd0000_01D_01H_GIM.INX.gz from 2022 day 331 (checked by HEAD on 2026-11-06). URL base as the note gives it: https://www.aiub.unibe.ch/download/CODE// (it redirects to AIUB's bucket on SWITCH's cloud). Plain client name, curl -L. Stops at once on 403, 429, any 5xx, or an HTML answer, and on more than 3 consecutive failures; a 404 is logged and skipped. A file already present with a logged SHA-256 is not fetched again. """ import datetime as dt import hashlib import json import os import subprocess import sys import time UA = "factchecked-research/1.0" BASE = "https://www.aiub.unibe.ch/download/CODE" SWITCH_DAY = dt.date(2022, 11, 27) # 2022 day 331: first long-name file def name_for(d): doy = d.timetuple().tm_yday if d < SWITCH_DAY: return "CODG%03d0.%02dI.Z" % (doy, d.year % 100) return "COD0OPSFIN_%04d%03d0000_01D_01H_GIM.INX.gz" % (d.year, doy) def sha256(path): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def main(): dates_file, out_dir, log_path = sys.argv[1], sys.argv[2], sys.argv[3] pause = 0.5 if "--sleep" in sys.argv: pause = float(sys.argv[sys.argv.index("--sleep") + 1]) done = set() if os.path.exists(log_path): with open(log_path, encoding="utf-8") as f: for line in f: r = json.loads(line) if r.get("status") == 200 and r.get("sha256"): done.add(r["file"]) dates = [] with open(dates_file, encoding="utf-8") as f: for line in f: line = line.strip() if line: dates.append(dt.date.fromisoformat(line)) fails = 0 n_new = 0 t_start = time.time() with open(log_path, "a", encoding="utf-8", newline="\n") as log: for d in dates: name = name_for(d) rel = "%04d/%s" % (d.year, name) if rel in done and os.path.exists(os.path.join(out_dir, rel)): continue os.makedirs(os.path.join(out_dir, "%04d" % d.year), exist_ok=True) url = "%s/%04d/%s" % (BASE, d.year, name) dest = os.path.join(out_dir, "%04d" % d.year, name) part = dest + ".part" t0 = time.time() p = subprocess.run( ["curl", "-sS", "-L", "-A", UA, "--max-time", "120", "-o", part, "-w", "%{http_code} %{size_download} %{content_type} %{url_effective}", url], capture_output=True, text=True) secs = time.time() - t0 parts = (p.stdout or "").split(" ", 3) status = int(parts[0]) if parts and parts[0].isdigit() else -1 ctype = parts[2] if len(parts) > 2 else "" final_url = parts[3] if len(parts) > 3 else "" rec = {"date": d.isoformat(), "file": rel, "url": url, "final_url": final_url, "status": status, "content_type": ctype, "seconds": round(secs, 2), "fetched_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")} html_answer = False if os.path.exists(part): with open(part, "rb") as f: head = f.read(512).lstrip().lower() html_answer = head.startswith(b" 1000: os.replace(part, dest) rec["bytes"] = os.path.getsize(dest) rec["sha256"] = sha256(dest) fails = 0 n_new += 1 else: rec["bytes"] = os.path.getsize(part) if os.path.exists(part) else 0 if os.path.exists(part): os.remove(part) rec["error"] = (p.stderr or "").strip()[:300] if html_answer: rec["error"] = "HTML answer instead of data" fails += 1 log.write(json.dumps(rec) + "\n") log.flush() print("%s %s %s %s %.2fs" % (rec["fetched_utc"], rel, status, rec.get("bytes"), secs), flush=True) if status in (403, 429) or status >= 500 or html_answer: print("STOP: refusal or unexpected answer (%s) for %s" % (status, url), flush=True) sys.exit(2) if fails > 3: print("STOP: more than 3 consecutive failures", flush=True) sys.exit(3) time.sleep(pause) print("done: %d new files in %.1f s" % (n_new, time.time() - t_start), flush=True) if __name__ == "__main__": main()