| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import urllib.request
- from datetime import date, datetime
- from room_cal._utils import CalendarEntry, EventSource, get_config
- from room_cal.store import EventRecord
- _source = EventSource('ical_feeds')
- _TIMEOUT = 15
- def _webcal_to_https(url: str) -> str:
- if url.startswith('webcal://'):
- return 'https://' + url[len('webcal://'):]
- return url
- def _parse_dt(dt) -> datetime:
- if isinstance(dt, datetime):
- return dt.replace(tzinfo=None)
- if isinstance(dt, date):
- return datetime(dt.year, dt.month, dt.day)
- return dt
- def _is_all_day(dt) -> bool:
- return isinstance(dt, date) and not isinstance(dt, datetime)
- def _parse_ical(raw_bytes: bytes, calendar_name: str) -> list[EventRecord]:
- from icalendar import Calendar as _iCal
- cal = _iCal.from_ical(raw_bytes)
- events = []
- for component in cal.walk():
- if component.name != 'VEVENT':
- continue
- dtstart_prop = component.get('DTSTART')
- if dtstart_prop is None:
- continue
- dtstart = dtstart_prop.dt
- dtend_prop = component.get('DTEND') or component.get('DUE')
- dtend = dtend_prop.dt if dtend_prop else dtstart
- events.append(EventRecord(
- uid=str(component.get('UID', '')),
- start=_parse_dt(dtstart),
- end=_parse_dt(dtend),
- all_day=_is_all_day(dtstart),
- title=str(component.get('SUMMARY', '')),
- description=str(component.get('DESCRIPTION', '')),
- x_data=None,
- _meta={'calendar': calendar_name},
- ))
- events.sort(key=lambda e: e.start)
- return events
- async def fetch_calendar(entry: CalendarEntry) -> list[EventRecord]:
- """Fetch one CalendarEntry by URL and return its events."""
- url = _webcal_to_https(entry.url)
- req = urllib.request.Request(url, headers={'User-Agent': 'room_cal/1.0'})
- with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
- raw = resp.read()
- return _parse_ical(raw, entry.name)
- async def fetch_all() -> dict[str, list[EventRecord]]:
- """Fetch all configured external calendars. Returns {name: [events]}."""
- results = {}
- for entry in get_config().ical_feeds:
- results[entry.name] = await fetch_calendar(entry)
- return results
|