9
9
10
10
from ical .calendar import Calendar
11
11
from ical .calendar_stream import IcsCalendarStream
12
+ from ical .compat import enable_compat_mode
12
13
from ical .exceptions import CalendarParseError
13
14
14
15
from homeassistant .core import HomeAssistant
@@ -20,24 +21,23 @@ class InvalidIcsException(Exception):
20
21
"""Exception to indicate that the ICS content is invalid."""
21
22
22
23
23
- def _make_compat (ics : str ) -> str :
24
- """Make the ICS content compatible with the parser."""
25
- # Office 365 returns a calendar with a TZID that is not valid and does not meet
26
- # rfc5545. Remove the invalid TZID from the calendar so that it can be parsed correctly.
27
- return ics .replace (";TZID=Customized Time Zone" , "" )
24
+ def _compat_calendar_from_ics (ics : str ) -> Calendar :
25
+ """Parse the ICS content and return a Calendar object.
28
26
27
+ This function is called in a separate thread to avoid blocking the event
28
+ loop while loading packages or parsing the ICS content for large calendars.
29
29
30
- async def parse_calendar (hass : HomeAssistant , ics : str ) -> Calendar :
31
- """Parse the ICS content and return a Calendar object."""
30
+ It uses the `enable_compat_mode` context manager to fix known issues with
31
+ calendar providers that return invalid calendars.
32
+ """
33
+ with enable_compat_mode (ics ) as compat_ics :
34
+ return IcsCalendarStream .calendar_from_ics (compat_ics )
32
35
33
- ics = _make_compat (ics )
34
36
35
- # calendar_from_ics will dynamically load packages the first time it is called, so we need
36
- # to do it in a separate thread to avoid blocking the event loop
37
+ async def parse_calendar ( hass : HomeAssistant , ics : str ) -> Calendar :
38
+ """Parse the ICS content and return a Calendar object."""
37
39
try :
38
- return await hass .async_add_executor_job (
39
- IcsCalendarStream .calendar_from_ics , ics
40
- )
40
+ return await hass .async_add_executor_job (_compat_calendar_from_ics , ics )
41
41
except CalendarParseError as err :
42
42
_LOGGER .error ("Error parsing calendar information: %s" , err .message )
43
43
_LOGGER .debug ("Additional calendar error detail: %s" , str (err .detailed_error ))
0 commit comments