__init__.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import urllib.request
  2. from datetime import date, datetime
  3. from room_cal._utils import CalendarEntry, EventSource, get_config
  4. from room_cal.store import EventRecord
  5. _source = EventSource('ical_feeds')
  6. _TIMEOUT = 15
  7. def _webcal_to_https(url: str) -> str:
  8. if url.startswith('webcal://'):
  9. return 'https://' + url[len('webcal://'):]
  10. return url
  11. def _parse_dt(dt) -> datetime:
  12. if isinstance(dt, datetime):
  13. return dt.replace(tzinfo=None)
  14. if isinstance(dt, date):
  15. return datetime(dt.year, dt.month, dt.day)
  16. return dt
  17. def _is_all_day(dt) -> bool:
  18. return isinstance(dt, date) and not isinstance(dt, datetime)
  19. def _parse_ical(raw_bytes: bytes, calendar_name: str) -> list[EventRecord]:
  20. from icalendar import Calendar as _iCal
  21. cal = _iCal.from_ical(raw_bytes)
  22. events = []
  23. for component in cal.walk():
  24. if component.name != 'VEVENT':
  25. continue
  26. dtstart_prop = component.get('DTSTART')
  27. if dtstart_prop is None:
  28. continue
  29. dtstart = dtstart_prop.dt
  30. dtend_prop = component.get('DTEND') or component.get('DUE')
  31. dtend = dtend_prop.dt if dtend_prop else dtstart
  32. events.append(EventRecord(
  33. uid=str(component.get('UID', '')),
  34. start=_parse_dt(dtstart),
  35. end=_parse_dt(dtend),
  36. all_day=_is_all_day(dtstart),
  37. title=str(component.get('SUMMARY', '')),
  38. description=str(component.get('DESCRIPTION', '')),
  39. x_data=None,
  40. _meta={'calendar': calendar_name},
  41. ))
  42. events.sort(key=lambda e: e.start)
  43. return events
  44. async def fetch_calendar(entry: CalendarEntry) -> list[EventRecord]:
  45. """Fetch one CalendarEntry by URL and return its events."""
  46. url = _webcal_to_https(entry.url)
  47. req = urllib.request.Request(url, headers={'User-Agent': 'room_cal/1.0'})
  48. with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
  49. raw = resp.read()
  50. return _parse_ical(raw, entry.name)
  51. async def fetch_all() -> dict[str, list[EventRecord]]:
  52. """Fetch all configured external calendars. Returns {name: [events]}."""
  53. results = {}
  54. for entry in get_config().ical_feeds:
  55. results[entry.name] = await fetch_calendar(entry)
  56. return results