"""Fetch the iCalendar feed with conditional requests.""" from __future__ import annotations import logging from dataclasses import dataclass from datetime import datetime, timedelta, timezone import httpx from .store import Store, from_iso, iso log = logging.getLogger(__name__) USER_AGENT = "signal-cal-bot/0.1 (iCalendar to Signal bridge)" def normalize_feed_url(url: str) -> str: """webcal:// is a hint, not a transport scheme.""" if url.startswith("webcal://"): return "https://" + url[len("webcal://") :] return url @dataclass(frozen=True) class FeedResponse: """A fetch result whose validators are committed only after a good parse.""" content: bytes | None = None etag: str | None = None last_modified: str | None = None @property def not_modified(self) -> bool: return self.content is None class Feed: """The iCalendar feed, fetched with conditional requests. ``fetch`` deliberately does not persist ETag/Last-Modified; the caller calls ``commit`` once the body has parsed, so a malformed response cannot lock itself behind a 304. """ def __init__(self, url: str, store: Store, refresh_minutes: int, http: httpx.Client): self.url = normalize_feed_url(url) self.store = store self.refresh_minutes = max(1, refresh_minutes) self.http = http def due(self, now: datetime) -> bool: last = self.store.get_meta("feed_last_attempt") if not last: return True return now - from_iso(last) >= timedelta(minutes=self.refresh_minutes) def fetch(self, now: datetime) -> FeedResponse: """Fetch the feed. Validators are *not* stored here; see commit().""" headers = {"User-Agent": USER_AGENT, "Accept": "text/calendar, */*"} etag = self.store.get_meta("feed_etag") modified = self.store.get_meta("feed_last_modified") if etag: headers["If-None-Match"] = etag if modified: headers["If-Modified-Since"] = modified self.store.set_meta("feed_last_attempt", iso(now)) response = self.http.get(self.url, headers=headers, timeout=30) if response.status_code == 304: log.debug("feed not modified") return FeedResponse() response.raise_for_status() log.info("fetched feed: %d bytes", len(response.content)) return FeedResponse( content=response.content, etag=response.headers.get("etag"), last_modified=response.headers.get("last-modified"), ) def commit(self, response: FeedResponse) -> None: """Persist validators after the payload parsed successfully.""" if response.etag: self.store.set_meta("feed_etag", response.etag) if response.last_modified: self.store.set_meta("feed_last_modified", response.last_modified) self.store.set_meta("feed_last_success", iso(datetime.now(timezone.utc)))