""" All network access to the live HPR archive goes through this module, and every URL it builds goes through config.CCDN_BASE -- never a backend host observed in a redirect or error message (that's an implementation detail of HPR's current hosting, not a stable contract; see docs/DESIGN.md). AccessDenied, 403, 404, and a 200-with-empty-body are all treated as the same outcome: "not available right now" -- callers fall back to the next detection signal rather than special-casing any one status code. """ import os import threading import time import urllib.error import urllib.request from . import config MIN_PLAUSIBLE_BYTES = 16 # anything smaller than this is treated as a placeholder _last_request_lock = threading.Lock() _last_request_at = 0.0 def _wait_for_politeness_gap(): """Enforces config.REQUEST_DELAY_SECONDS between any two requests this process makes to HPR's servers, regardless of which function issued them (audio, SRT, txt, or a neighbour's audio during sibling correlation all share this gate).""" global _last_request_at with _last_request_lock: wait = config.REQUEST_DELAY_SECONDS - (time.monotonic() - _last_request_at) if wait > 0: time.sleep(wait) _last_request_at = time.monotonic() # A byte-length check alone isn't enough -- an error response large enough # to clear MIN_PLAUSIBLE_BYTES (an HTML 404 page, an S3-style AccessDenied # XML body) would otherwise get saved under an audio/SRT filename and fail # much later, confusingly, in ffprobe or SRT parsing. Reject anything that # looks like markup rather than real content before it's ever written to # disk. _ERROR_PAGE_PREFIXES = (b" 0: return dest except Exception: pass os.remove(dest) # saved bytes didn't decode as real audio -- try the next format return None def fetch_official_srt(ep_id, cache_dir, force=False): """Returns the local path to the official SRT if HPR has published a real one for this episode, else None. A 0-byte/placeholder response is treated the same as 404 -- never assumed present from the episode page or from era alone.""" from . import srt # deferred to avoid a module-level cycle with srt.py's own imports dest = os.path.join(cache_dir, "transcripts", f"hpr{ep_id:04d}.srt") if not force and os.path.exists(dest): return dest data = _fetch_bytes(_episode_url(ep_id, "srt")) if data is None: return None _atomic_save(data, dest) try: if srt.parse_file(dest): return dest except Exception: pass os.remove(dest) # saved bytes didn't parse as at least one real SRT segment return None def fetch_official_txt(ep_id, cache_dir, force=False): dest = os.path.join(cache_dir, "transcripts", f"hpr{ep_id:04d}.txt") if not force and os.path.exists(dest): return dest data = _fetch_bytes(_episode_url(ep_id, "txt")) if data is None: return None _atomic_save(data, dest) return dest