"""Fetching and parsing what scheduled receipts read: calendars (ICS), feeds and JSON.""" from __future__ import annotations import datetime as dt import html import json import re import threading import time from dataclasses import dataclass from zoneinfo import ZoneInfo import requests import receipt MAX_SOURCE_BYTES = 5 * 1024 * 1024 USER_AGENT = "receipt-maker/1.0 (thermal receipt printer)" CALENDAR_MAX_AGE = 15 * 60 # seconds an ICS download is reused FEED_MAX_AGE = 10 * 60 class SourceError(Exception): """A calendar or feed couldn't be downloaded or read.""" @dataclass(frozen=True) class Event: uid: str title: str start: dt.datetime # aware, in the settings timezone; midnight for all-day events end: dt.datetime all_day: bool location: str = "" description: str = "" @property def key(self) -> str: """Identifies one occurrence of a (possibly recurring) event.""" return f"{self.uid}|{self.start.isoformat()}" @dataclass(frozen=True) class Item: id: str title: str link: str = "" summary: str = "" source: str = "" class SourceCache: """Downloads by URL, reused for max_age seconds so previews and ticks don't refetch.""" def __init__(self): self._lock = threading.Lock() self._entries: dict[str, tuple[float, bytes]] = {} def get(self, url: str, max_age: float) -> bytes: with self._lock: entry = self._entries.get(url) if entry and time.monotonic() - entry[0] < max_age: return entry[1] data = fetch(url) with self._lock: self._entries[url] = (time.monotonic(), data) return data def forget(self, url: str) -> None: with self._lock: self._entries.pop(url, None) def fetch(url: str) -> bytes: try: data = receipt.fetch_capped(url, MAX_SOURCE_BYTES, headers={"User-Agent": USER_AGENT}) except requests.RequestException as e: raise SourceError(_short_error(e)) from e if data is None: raise SourceError(f"over the {MAX_SOURCE_BYTES // 1024 // 1024} MB limit") return data def _short_error(e: requests.RequestException) -> str: response = getattr(e, "response", None) if response is not None and response.status_code: return f"HTTP {response.status_code}" if isinstance(e, requests.Timeout): return "timed out" if isinstance(e, requests.ConnectionError): return "couldn't connect" return type(e).__name__ def _local(value: dt.date | dt.datetime, tz: ZoneInfo) -> tuple[dt.datetime, bool]: """An ICS start/end as an aware local datetime, and whether it was a whole day.""" if not isinstance(value, dt.datetime): return dt.datetime.combine(value, dt.time(), tz), True if value.tzinfo is None: # "floating" time: the calendar's local time return value.replace(tzinfo=tz), False return value.astimezone(tz), False def parse_events(data: bytes, start: dt.datetime, end: dt.datetime, tz: ZoneInfo) -> list[Event]: """Occurrences overlapping [start, end), recurring events expanded, sorted by start.""" import icalendar import recurring_ical_events try: calendar = icalendar.Calendar.from_ical(data) occurrences = recurring_ical_events.of(calendar, skip_bad_series=True).between(start, end) except Exception as e: # icalendar raises ValueError, KeyError and its own errors raise SourceError(f"not a readable calendar ({type(e).__name__})") from e events = [] for component in occurrences: if str(component.get("STATUS", "")).upper() == "CANCELLED": continue raw_start = component.get("DTSTART") if raw_start is None: continue event_start, all_day = _local(raw_start.dt, tz) raw_end = component.get("DTEND") event_end = _local(raw_end.dt, tz)[0] if raw_end is not None else event_start events.append( Event( uid=str(component.get("UID", "")) or f"{component.get('SUMMARY', '')}", title=str(component.get("SUMMARY", "")).strip() or "(no title)", start=event_start, end=event_end, all_day=all_day, location=str(component.get("LOCATION", "")).strip(), description=str(component.get("DESCRIPTION", "")).strip(), ) ) events.sort(key=lambda e: (e.start, not e.all_day, e.title)) return events def parse_items(data: bytes, source: str = "") -> list[Item]: """Feed entries, newest first as the feed lists them.""" import feedparser feed = feedparser.parse(data) if feed.bozo and not feed.entries: raise SourceError("not a readable RSS/Atom feed") items = [] for entry in feed.entries: title = " ".join(str(entry.get("title", "")).split()) or "(untitled)" link = str(entry.get("link", "")) items.append( Item( id=str(entry.get("id") or link or title), title=title, link=link, summary=_plain(str(entry.get("summary", ""))), source=source or str(feed.feed.get("title", "")), ) ) return items def _plain(markup: str) -> str: """Feed summaries are HTML; the printer wants text.""" return " ".join(html.unescape(re.sub(r"<[^>]+>", " ", markup)).split()) def json_value(data: bytes, path: str): """The value at a dotted path ("data.items.0.price") in a JSON document.""" try: value = json.loads(data) except ValueError as e: raise SourceError("not valid JSON") from e for part in (p for p in path.split(".") if p): if isinstance(value, list) and part.lstrip("-").isdigit(): index = int(part) if not -len(value) <= index < len(value): raise SourceError(f"{path}: index {index} is out of range") value = value[index] elif isinstance(value, dict) and part in value: value = value[part] else: raise SourceError(f"{path}: no {part!r} there") if isinstance(value, (dict, list)): raise SourceError(f"{path} is a {type(value).__name__}, not a single value") return value