113 lines
3.7 KiB
Python
113 lines
3.7 KiB
Python
"""Download DSZO timetable pages, cache them on disk and load them back."""
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import os
|
|
import urllib.request
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
|
|
import yaml
|
|
|
|
from timetable import ParseError, Timetable, parse_page
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
USER_AGENT = "bus-department-schedule/1.0 (personal home display; 4 requests/day)"
|
|
MAX_AGE = timedelta(days=3)
|
|
FETCHED_FILE = "fetched.json"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class LineConfig:
|
|
line: str
|
|
stop: str
|
|
url: str
|
|
|
|
@property
|
|
def label(self) -> str:
|
|
return f"{self.line} {self.stop}"
|
|
|
|
|
|
@dataclass
|
|
class RefreshReport:
|
|
updated: list[str] = field(default_factory=list)
|
|
failed: dict[str, str] = field(default_factory=dict)
|
|
|
|
|
|
def load_lines(path) -> list[LineConfig]:
|
|
data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
|
|
return [LineConfig(str(e["line"]), e["stop"], e["url"]) for e in data["lines"]]
|
|
|
|
|
|
def fetch_page(url: str, timeout: float = 20.0) -> str:
|
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
return response.read().decode("utf-8")
|
|
|
|
|
|
def cache_path(data_dir, cfg: LineConfig) -> Path:
|
|
digest = hashlib.sha1(cfg.url.encode("utf-8")).hexdigest()[:10]
|
|
return Path(data_dir) / f"line{cfg.line}-{digest}.html"
|
|
|
|
|
|
def _read_fetched(data_dir: Path) -> dict[str, str]:
|
|
try:
|
|
return json.loads((data_dir / FETCHED_FILE).read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return {}
|
|
|
|
|
|
def _write_atomic(path: Path, text: str) -> None:
|
|
tmp = path.with_name(path.name + ".tmp")
|
|
tmp.write_text(text, encoding="utf-8")
|
|
os.replace(tmp, path)
|
|
|
|
|
|
def refresh(lines, data_dir, fetch=fetch_page, now: datetime | None = None) -> RefreshReport:
|
|
"""Download every line; only a page that parses replaces the cached copy."""
|
|
data_dir = Path(data_dir)
|
|
data_dir.mkdir(parents=True, exist_ok=True)
|
|
now = now or datetime.now()
|
|
fetched = _read_fetched(data_dir)
|
|
report = RefreshReport()
|
|
for cfg in lines:
|
|
try:
|
|
html = fetch(cfg.url)
|
|
parse_page(html, cfg.line, cfg.stop) # validate before touching the cache
|
|
except Exception as exc: # network, HTTP, decoding and ParseError all mean "keep old cache"
|
|
log.warning("refresh failed for %s: %s", cfg.label, exc)
|
|
report.failed[cfg.label] = str(exc)
|
|
continue
|
|
_write_atomic(cache_path(data_dir, cfg), html)
|
|
fetched[cfg.label] = now.isoformat(timespec="seconds")
|
|
report.updated.append(cfg.label)
|
|
_write_atomic(data_dir / FETCHED_FILE, json.dumps(fetched, ensure_ascii=False, indent=2))
|
|
return report
|
|
|
|
|
|
def load_timetables(lines, data_dir) -> list[Timetable]:
|
|
"""Parse every cached page; lines without a usable cache are skipped."""
|
|
timetables = []
|
|
for cfg in lines:
|
|
try:
|
|
html = cache_path(data_dir, cfg).read_text(encoding="utf-8")
|
|
timetables.append(parse_page(html, cfg.line, cfg.stop))
|
|
except (OSError, ValueError, ParseError) as exc:
|
|
log.warning("no usable cache for %s: %s", cfg.label, exc)
|
|
return timetables
|
|
|
|
|
|
def is_stale(lines, data_dir, now: datetime, max_age: timedelta = MAX_AGE) -> bool:
|
|
"""True if any line was never fetched or its last good fetch is older than max_age."""
|
|
fetched = _read_fetched(Path(data_dir))
|
|
for cfg in lines:
|
|
try:
|
|
when = datetime.fromisoformat(fetched[cfg.label])
|
|
except (KeyError, ValueError):
|
|
return True
|
|
if now - when > max_age:
|
|
return True
|
|
return False
|