From a359d7ae04651999c0269f6723ecf014758ddafc Mon Sep 17 00:00:00 2001
From: Kevin Alberts <kevin@kevinalberts.nl>
Date: Wed, 11 Nov 2020 21:59:42 +0100
Subject: [PATCH] Handle error if ical is malformed

---
 davinci/caldav/models.py    | 4 ++--
 davinci/icalendar/models.py | 9 ++++++++-
 2 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/davinci/caldav/models.py b/davinci/caldav/models.py
index 394bfb6..746d523 100644
--- a/davinci/caldav/models.py
+++ b/davinci/caldav/models.py
@@ -4,9 +4,9 @@ from typing import List, Tuple, Optional
 import caldav
 from caldav import Calendar, vcal
 from django.db import models
+from ics import Event
 
 # Create your models here.
-from ics import Event
 
 
 class CalDAVServer(models.Model):
@@ -75,7 +75,7 @@ class CalDAVCalendar(models.Model):
         :return Amount of events added, updated, and deleted
         :rtype Tuple[int, int, int]
         """
-        logger = logging.getLogger("davinci.icalendar.ICalSync.upload_events")
+        logger = logging.getLogger("davinci.icalendar.CalDAVCalendar.upload_events")
         calendar = self.get_calendar()
         if calendar is None:
             logger.error(f"No calendar found on url '{self.calendar_url}'")
diff --git a/davinci/icalendar/models.py b/davinci/icalendar/models.py
index 1e48a9a..770824d 100644
--- a/davinci/icalendar/models.py
+++ b/davinci/icalendar/models.py
@@ -1,3 +1,4 @@
+import logging
 from datetime import timedelta
 
 import humanize
@@ -29,8 +30,14 @@ class ICalSync(models.Model):
         return humanize.precisedelta(self.sync_interval)
 
     def get_events(self):
+        logger = logging.getLogger("davinci.icalendar.ICalSync.get_events")
         data = ical_utils.get_ical_from_url(self.ical_url)
-        events = ical_utils.split_events(data)
+        try:
+            events = ical_utils.split_events(data)
+        except ValueError as e:
+            logger.error(f"ValueError while parsing events from iCal {self.name}: {e}. Please check iCal (URL: {self.ical_url} ) for correct format.")
+            return []
+
         # We have to pad the uids with some string related to the target calendar,
         # So that if someone wants to sync the same .ics to two calendars, the UIDs are different.
         fixed_events = ical_utils.fix_ical_uids(events, self.target)