feat: download, validate and cache timetable pages

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Haiku 4.5 committed 2026-10-07 00:36:25 +02:00
1 parent ce52e38f66
commit e199600140
2 files changed
+193

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
"""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
+81
View File
@@ -0,0 +1,81 @@
from datetime import datetime, timedelta
import pytest
import store
from tests.helpers import ROOT, fixture_html
LINE4 = store.LineConfig("4", "Štípa,u potoka", "https://example.test/4")
NOW = datetime(2026, 10, 6, 12, 0)
EMPTY_TABLE = (
'<table><thead><tr><th>Hod.</th><th>Pracovní dny<br/>platnost od 1.10.2026</th></tr></thead>'
'<tbody><tr><td class="hour-cell">00</td><td class="minutes-cell"></td></tr></tbody></table>'
)
def good_page(url):
return fixture_html("line4_u_potoka.html")
def test_refresh_stores_page_and_load_parses_it(tmp_path):
report = store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
assert report.updated == [LINE4.label] and report.failed == {}
[timetable] = store.load_timetables([LINE4], tmp_path)
assert timetable.line == "4" and len(timetable.columns[0].departures) == 36
def test_failed_download_keeps_previous_cache(tmp_path):
store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
def network_down(url):
raise OSError("network down")
report = store.refresh([LINE4], tmp_path, fetch=network_down, now=NOW + timedelta(days=1))
assert "network down" in report.failed[LINE4.label]
assert len(store.load_timetables([LINE4], tmp_path)[0].columns[0].departures) == 36
# the failed attempt must not make the old cache look fresh
assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=3, hours=1)) is True
@pytest.mark.parametrize("html", ["<html>redesigned page</html>", EMPTY_TABLE, ""])
def test_unparseable_page_does_not_replace_cache(tmp_path, html):
store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
report = store.refresh([LINE4], tmp_path, fetch=lambda url: html, now=NOW + timedelta(days=1))
assert LINE4.label in report.failed and report.updated == []
assert len(store.load_timetables([LINE4], tmp_path)[0].columns[0].departures) == 36
def test_refresh_continues_after_one_line_fails(tmp_path):
other = store.LineConfig("5", "Štípa,u potoka", "https://example.test/5")
def fetch(url):
if url.endswith("/4"):
raise OSError("boom")
return fixture_html("line5_u_potoka.html")
report = store.refresh([LINE4, other], tmp_path, fetch=fetch, now=NOW)
assert report.updated == [other.label] and list(report.failed) == [LINE4.label]
def test_load_timetables_skips_missing_and_corrupt_cache(tmp_path):
assert store.load_timetables([LINE4], tmp_path) == [] # nothing cached yet
store.cache_path(tmp_path, LINE4).write_text("<html>junk</html>", encoding="utf-8")
assert store.load_timetables([LINE4], tmp_path) == []
def test_is_stale(tmp_path):
assert store.is_stale([LINE4], tmp_path, NOW) is True # never fetched
store.refresh([LINE4], tmp_path, fetch=good_page, now=NOW)
assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=2, hours=23)) is False
assert store.is_stale([LINE4], tmp_path, NOW + timedelta(days=3, hours=1)) is True
def test_load_lines_reads_yaml(tmp_path):
path = tmp_path / "lines.yaml"
path.write_text('lines:\n - line: "4"\n stop: "Štípa,u potoka"\n url: "https://x.test/4"\n', encoding="utf-8")
assert store.load_lines(path) == [store.LineConfig("4", "Štípa,u potoka", "https://x.test/4")]
def test_repo_lines_yaml_lists_the_four_lines():
labels = [c.label for c in store.load_lines(ROOT / "lines.yaml")]
assert labels == ["4 Štípa,u potoka", "5 Štípa,u potoka", "35 Štípa,družstvo", "36 Štípa,družstvo"]