"""Orbital elements for the Almanac's Earth view: the GPS constellation and the ISS. The view (static/almanac-earth.js) propagates these with SGP4 in the browser; this module only decides which element set it gets. Three sources, and the newest wins: snapshot zimi/assets/satellites-snapshot.json, fetched when the release was cut (``python3 scripts/build_satellite_snapshot.py``) cache the last live fetch, in the data directory (and in memory, so a data directory that cannot be written still keeps it) live CelesTrak's GP data, fetched when the cache is older than CACHE_TTL_S and the setting below allows it A request is answered at once from what is here. Whether Zimi then reaches CelesTrak is a server-wide setting, "Satellite data from the internet" (Eric, 2026-09-28: "i'm not positive how i feel about unexpected network calls from zimi"): ask the default. Nothing is fetched on its own: a stale answer says so (``stale``), and an admin's "Get fresh data" (refresh_now) fetches once. auto a stale answer starts one background refresh (single flight, with a cooldown after a failure), the stale-while-revalidate rule the Kiwix catalog follows, and says so (``refreshing``) so an open view knows to ask again. never nothing is fetched, ever; the view says how old its data is. ZIMI_SATELLITE_UPDATES wins over the saved choice, and ZIMI_OFFLINE forces never over both. The upstream request carries Zimi's user agent and nothing about whoever opened the view. Records are CelesTrak's OMM JSON (the CCSDS Orbit Mean-Elements Message fields), checked field by field before they are kept: a bad or partial answer leaves the cache as it was. """ import json import logging import math import os import re import threading import time import urllib.parse import urllib.request from zimi import outbound from zimi import server as _srv log = logging.getLogger("zimi") CELESTRAK_GP_URL = "https://celestrak.org/NORAD/elements/gp.php" # The operational GPS constellation, and the ISS by its catalogue number. GPS_QUERY = {"GROUP": "gps-ops", "FORMAT": "json"} ISS_NORAD_ID = 25544 ISS_QUERY = {"CATNR": str(ISS_NORAD_ID), "FORMAT": "json"} # The Earth-orbiting craft the view draws with their models: CelesTrak's "science" group holds both, so one request # answers for them. Hubble is low and round; Chandra's orbit is a long ellipse out to a third of the way to the Moon. HUBBLE_NORAD_ID = 20580 CHANDRA_NORAD_ID = 25867 CRAFT_NORAD_IDS = (HUBBLE_NORAD_ID, CHANDRA_NORAD_ID) CRAFT_QUERY = {"GROUP": "science", "FORMAT": "json"} SNAPSHOT_PATH = os.path.join( os.path.dirname(os.path.abspath(__file__)), "assets", "satellites-snapshot.json" ) CACHE_FILENAME = "satellites_cache.json" # CelesTrak publishes new elements a few times a day and asks clients not to # fetch the same data more often than it changes. Six hours keeps the ISS's # place along its orbit within a few km and costs CelesTrak four requests a # day per Zimi that has the view open. CACHE_TTL_S = 6 * 3600 FAIL_COOLDOWN_S = 3600 FETCH_TIMEOUT_S = 20 # The setting. Saved beside the other server-wide choices (the app-update # prefs file, like the Apps switch); the env var, when it names a mode, wins. UPDATES_ENV = "ZIMI_SATELLITE_UPDATES" UPDATE_ASK = outbound.ASK UPDATE_AUTO = outbound.AUTO UPDATE_NEVER = outbound.NEVER UPDATE_MODES = outbound.MODES UPDATE_DEFAULT = UPDATE_ASK PREFS_KEY = "satellite_updates" LOCKED_ENV = outbound.LOCKED_ENV LOCKED_OFFLINE = outbound.LOCKED_OFFLINE MAX_RESPONSE_BYTES = 512 * 1024 MAX_GPS = 64 # The OMM fields satellite.js's json2satrec reads, plus the name and the # international designator the view shows. OMM_NUMBER_FIELDS = ( "MEAN_MOTION", "ECCENTRICITY", "INCLINATION", "RA_OF_ASC_NODE", "ARG_OF_PERICENTER", "MEAN_ANOMALY", "BSTAR", "MEAN_MOTION_DOT", "MEAN_MOTION_DDOT", ) # Plausible ranges: an Earth orbit, not a typo. Mean motion in revolutions a # day (Chandra makes 0.38, a GPS satellite two, the ISS about 15.5). _RANGES = { "MEAN_MOTION": (0.2, 17.0), "ECCENTRICITY": (0.0, 0.99), "INCLINATION": (0.0, 180.0), "RA_OF_ASC_NODE": (0.0, 360.0), "ARG_OF_PERICENTER": (0.0, 360.0), "MEAN_ANOMALY": (0.0, 360.0), } _EPOCH_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d+)?Z?$") _lock = threading.Lock() _refreshing = False _last_fail = 0.0 # The last good live fetch. The disk cache is its durable copy; this one # outlives a data directory that cannot be written, which would otherwise # lose every fetch and ask CelesTrak again each FAIL_COOLDOWN_S, forever. _memory = None def _cache_path(): return os.path.join(_srv.ZIMI_DATA_DIR, CACHE_FILENAME) def _user_agent(): from zimi.library import USER_AGENT return USER_AGENT def _offline(): from zimi import p2p return bool(p2p.is_offline()) # The shared Ask first / Automatically / Never machinery (outbound.py), read # through this module's _offline so a test can stand in for ZIMI_OFFLINE. POLICY = outbound.FetchPolicy( UPDATES_ENV, PREFS_KEY, UPDATE_DEFAULT, "Satellite data from the internet", offline=lambda: _offline(), ) normalize_mode = outbound.normalize_mode def update_mode(): """The mode in force and what fixed it: ``(mode, locked)``. ``locked`` is "offline" (ZIMI_OFFLINE: never), "env" (ZIMI_SATELLITE_UPDATES names a mode) or None, when the saved choice, or the default, decides.""" return POLICY.mode() def setting(): """The setting as Server settings shows it.""" return POLICY.setting() def set_update_mode(value): """Save the choice. ``(mode, error)``: error is "invalid", "env" or "offline" (the choice is not the setting's to make), or "unwritable".""" return POLICY.set(value) def normalize_record(rec): """One OMM record, checked and trimmed, or None. The epoch is written to the millisecond with a Z, the one form every browser's Date parses (six fractional digits are not).""" if not isinstance(rec, dict): return None out = {} try: name = str(rec.get("OBJECT_NAME") or "").strip() if not name or len(name) > 64: return None norad = int(rec.get("NORAD_CAT_ID")) if norad <= 0: return None m = _EPOCH_RE.match(str(rec.get("EPOCH") or "")) if not m: return None frac = (m.group(2) or ".0")[1:] millis = (frac + "000")[:3] out["OBJECT_NAME"] = name out["OBJECT_ID"] = str(rec.get("OBJECT_ID") or "")[:16] out["NORAD_CAT_ID"] = norad out["EPOCH"] = f"{m.group(1)}.{millis}Z" for key in OMM_NUMBER_FIELDS: val = float(rec.get(key, 0) or 0) if not math.isfinite(val): return None lo_hi = _RANGES.get(key) if lo_hi and not (lo_hi[0] <= val <= lo_hi[1]): return None out[key] = val except (TypeError, ValueError): return None return out def parse_craft(craft_list): """The records of CRAFT_NORAD_IDS in an answer, each once, in that order ([] for an answer without them).""" if not isinstance(craft_list, list): return [] found = {} for rec in craft_list: rec = normalize_record(rec) if rec and rec["NORAD_CAT_ID"] in CRAFT_NORAD_IDS: found.setdefault(rec["NORAD_CAT_ID"], rec) return [found[n] for n in CRAFT_NORAD_IDS if n in found] def parse_payload(gps_list, iss_list, fetched_at, craft_list=None): """The payload the view reads, from CelesTrak's answers. Raises ValueError when the answers do not hold what they should. The craft (Hubble, Chandra) are optional: an answer without them leaves the list empty.""" if not isinstance(gps_list, list) or not isinstance(iss_list, list): raise ValueError("expected lists") gps = [r for r in (normalize_record(x) for x in gps_list[:MAX_GPS]) if r] iss = [ r for r in (normalize_record(x) for x in iss_list) if r and r["NORAD_CAT_ID"] == ISS_NORAD_ID ] if not gps or not iss: raise ValueError("no usable elements") return { "fetched": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(fetched_at)), "fetched_at": fetched_at, "gps": gps, "iss": iss[0], "craft": parse_craft(craft_list), } def _get_json(query): url = CELESTRAK_GP_URL + "?" + urllib.parse.urlencode(query) req = urllib.request.Request(url, headers={"User-Agent": _user_agent()}) with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT_S, context=_srv.SSL_CTX) as resp: body = resp.read(MAX_RESPONSE_BYTES + 1) if len(body) > MAX_RESPONSE_BYTES: raise ValueError("response too large") return json.loads(body.decode("utf-8")) def fetch_live(): """The element sets from CelesTrak, as one payload. The GPS and ISS answers raise on failure; the telescopes' is best effort (the view keeps the last it had for them).""" gps, iss = _get_json(GPS_QUERY), _get_json(ISS_QUERY) try: craft = _get_json(CRAFT_QUERY) except Exception as e: log.info("Telescope elements not fetched: %s", e) craft = None return parse_payload(gps, iss, time.time(), craft) def _read_json(path): try: with open(path, encoding="utf-8") as f: payload = json.load(f) except (OSError, ValueError): return None if ( not isinstance(payload, dict) or not payload.get("gps") or not payload.get("iss") ): return None try: payload["fetched_at"] = float(payload.get("fetched_at") or 0) except (TypeError, ValueError): return None return payload def read_cache(): return _read_json(_cache_path()) def read_snapshot(): return _read_json(SNAPSHOT_PATH) def write_snapshot(path, payload): """Stable bytes (sorted keys, one record per line) so an unchanged element set rebuilds byte for byte and a changed one diffs readably.""" lines = ["{"] lines.append(f' "fetched": {json.dumps(payload["fetched"])},') lines.append(f' "fetched_at": {json.dumps(payload["fetched_at"])},') lines.append(f' "iss": {json.dumps(payload["iss"], sort_keys=True)},') craft = ",\n".join(f" {json.dumps(r, sort_keys=True)}" for r in payload.get("craft") or []) lines.append(' "craft": [' + ("\n" + craft + "\n " if craft else "") + "],") lines.append(' "gps": [') rows = [f" {json.dumps(r, sort_keys=True)}" for r in payload["gps"]] lines.append(",\n".join(rows)) lines.append(" ]") lines.append("}") with open(path, "w", encoding="utf-8") as f: f.write("\n".join(lines) + "\n") def refresh(): """Fetch live and replace the cache. Returns the payload, or None when the fetch failed or another refresh is running (the cache stays).""" global _refreshing, _last_fail, _memory with _lock: if _refreshing: return None _refreshing = True try: payload = fetch_live() except Exception as e: _last_fail = time.time() log.info("Satellite elements not refreshed: %s", e) return None finally: with _lock: _refreshing = False _memory = payload # A failed write logs itself and leaves the disk cache as it was. _srv._atomic_write_json(_cache_path(), payload) log.info("Satellite elements refreshed: %d GPS + ISS + %d craft", len(payload["gps"]), len(payload["craft"])) return payload def _kick_refresh(): """Start a background refresh unless offline, cooling down after a failure, or one is already running. True when a refresh is under way.""" if _offline() or time.time() - _last_fail < FAIL_COOLDOWN_S: return False with _lock: if _refreshing: return True threading.Thread(target=refresh, name="satellite-elements", daemon=True).start() return True def _newest(*payloads): have = [p for p in payloads if p] return max(have, key=lambda p: p["fetched_at"]) if have else None def get(allow_refresh=True): """The newest element set here, at once: ``{source, fetched, gps, iss, stale, refreshing, mode, locked}``. Under Automatically a stale one starts a background refresh when allowed, and ``refreshing`` says one is under way, so fresher elements are coming. Under Ask first and Never nothing is fetched here; ``stale`` is what lets the view offer to.""" mode, locked = update_mode() live, snap = _newest(read_cache(), _memory), read_snapshot() best, source = None, "none" if live and (not snap or live["fetched_at"] >= snap["fetched_at"]): best, source = live, "cache" elif snap: best, source = snap, "snapshot" age = time.time() - best["fetched_at"] if best else float("inf") stale = age > CACHE_TTL_S refreshing = bool( allow_refresh and mode == UPDATE_AUTO and stale and _kick_refresh() ) # A fetch that missed the telescopes keeps the ones the snapshot shipped. craft = (best.get("craft") if best else None) or (snap.get("craft") if snap else None) or [] return { "source": source, "fetched": best.get("fetched") if best else None, "gps": best["gps"] if best else [], "iss": best["iss"] if best else None, "craft": craft, "stale": stale, "refreshing": refreshing, "mode": mode, "locked": locked, } def refresh_now(): """An admin's "Get fresh data": one fetch, waited for. ``(payload, error)``: the view's answer, and "never" when this server may not fetch (Never, or ZIMI_OFFLINE) or "failed" when CelesTrak could not be had. Elements that are already fresh are answered as they are: CelesTrak asks not to be asked again for data that has not changed. A fetch already under way is answered with ``refreshing``, so the view asks again.""" if update_mode()[0] == UPDATE_NEVER: return None, "never" current = get(allow_refresh=False) if not current["stale"]: return current, None fetched = refresh() after = get(allow_refresh=False) if fetched is not None or not after["stale"]: return after, None with _lock: running = _refreshing if running: after["refreshing"] = True return after, None return after, "failed" def _reset_for_tests(): global _refreshing, _last_fail, _memory _refreshing = False _last_fail = 0.0 _memory = None