First draft
This commit is contained in:
1 parent
1b0358c8c0
commit
6fe522abeb
4 files changed
+113
No files matched your search
@@ -0,0 +1,66 @@
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
from icalendar import Calendar
|
||||
|
||||
from generic_errors import SourceApiError, SourceUrlNotFoundError
|
||||
from models import CalendarEntry
|
||||
from simple_logger_handler import setup_logger
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
|
||||
utc_tz = ZoneInfo("UTC")
|
||||
|
||||
def _fetch_text(url: str) -> str:
|
||||
try:
|
||||
response = requests.get(url, timeout=10)
|
||||
except requests.RequestException as e:
|
||||
raise SourceApiError(f"Request to {url} failed: {type(e).__name__}") from e
|
||||
|
||||
if response.status_code == 404:
|
||||
raise SourceUrlNotFoundError(f"Not found: {url}")
|
||||
if not response.ok:
|
||||
raise SourceApiError(f"HTTP {response.status_code} for {url}")
|
||||
|
||||
return response.text
|
||||
|
||||
|
||||
def create_calendar_entries(gcal: Calendar) -> list[CalendarEntry]:
|
||||
now = datetime.now(utc_tz)
|
||||
entries: list[CalendarEntry] = []
|
||||
|
||||
for component in gcal.walk("VEVENT"):
|
||||
dtstart = component.get("dtstart")
|
||||
summary = component.get("summary")
|
||||
uid = component.get("uid")
|
||||
|
||||
if not (dtstart and summary and uid):
|
||||
logger.debug("[Calendar] Missing date, summary or uid, skipping.")
|
||||
continue
|
||||
|
||||
date = dtstart.dt
|
||||
if not isinstance(date, datetime):
|
||||
logger.debug("[Calendar] All-day event, skipping: uid=%s", uid)
|
||||
continue
|
||||
|
||||
if date.tzinfo is None:
|
||||
date = date.replace(tzinfo=utc_tz)
|
||||
|
||||
if date <= now:
|
||||
continue
|
||||
|
||||
logger.debug("[Calendar] Adding future event: summary=%s, date=%s, uid=%s",
|
||||
summary, date, uid)
|
||||
entries.append(CalendarEntry(date=date, summary=str(summary), uid=str(uid)))
|
||||
|
||||
return entries
|
||||
|
||||
if __name__ == "__main__":
|
||||
g = open('example.ics','rb')
|
||||
gcal = Calendar.from_ical(g.read())
|
||||
req = _fetch_text("https://i.cal.to/ical/3/borussiadortmund/bundesliga-spielplan/de/e4838f52.0089dab3-0039c7e6.ics")
|
||||
cal = Calendar.from_ical(req)
|
||||
print(create_calendar_entries(cal))
|
||||
|
||||
g.close()
|
||||
@@ -0,0 +1,23 @@
|
||||
from typing import assert_never
|
||||
|
||||
from models import SourceType
|
||||
|
||||
def _bvb(event: str) -> list[str]:
|
||||
entries = event.split("|")
|
||||
event = entries[0]
|
||||
if entries[1].strip().lower() == "ucl":
|
||||
competition = f"{entries[1].strip()} - {entries[2].strip()}"
|
||||
match_day = entries[3].strip()
|
||||
else:
|
||||
competition = entries[1].strip()
|
||||
match_day = entries[2].strip()
|
||||
return [entries, competition, match_day]
|
||||
|
||||
def event_formatting(event: str, source: SourceType) -> list[str]:
|
||||
match source:
|
||||
case SourceType.BVB:
|
||||
return _bvb(event)
|
||||
case SourceType.GENERIC:
|
||||
return [event]
|
||||
case _:
|
||||
assert_never(source)
|
||||
@@ -15,7 +15,21 @@ class GenericError(Exception):
|
||||
"""Extra HTTP headers the proxy should send with this error."""
|
||||
return {}
|
||||
|
||||
class SourceApiError(GenericError):
|
||||
"""Temporary or unexpected API problem (network, timeout, 5xx, bad response).
|
||||
|
||||
Nothing is wrong with the request itself, so retry later.
|
||||
"""
|
||||
|
||||
def __init__(self, source: str, detail: str):
|
||||
super().__init__(f"API error: {detail}")
|
||||
|
||||
class SourceUrlNotFoundError(GenericError):
|
||||
"""Temporary or unexpected API problem (network, timeout, 5xx, bad response).
|
||||
|
||||
Nothing is wrong with the request itself, so retry later.
|
||||
"""
|
||||
|
||||
def __init__(self, source: str, detail: str):
|
||||
super().__init__(f"API error: {detail}")
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel, Field, computed_field
|
||||
|
||||
|
||||
class SourceType(StrEnum):
|
||||
BVB = "bvb"
|
||||
GENERIC = "generic"
|
||||
|
||||
class CalendarEntry(BaseModel):
|
||||
date: datetime
|
||||
summary: str
|
||||
uid: str
|
||||
|
||||
class GenericEntry(BaseModel):
|
||||
name: str
|
||||
custom_name: str | None = None
|
||||
|
||||
Reference in new issue
Block a user