calendarwatch_backend/icalHandler.py
raphael 056779f7d2 adds ical url handling
- icalToCalendarDB converts the information the user puts into the form
  on the calendar.html page and pulls the calendar from the url.
  It then passes it into the database.

- fetchCanedarEvents gets all events within a startDate and an endDate
  and removes any all day events. This is currently a bit costly, because
  it takes some time for the ics library to download the entire .ical
  file from the url. Then it goes through every entry ever added to the
  file and saves only the future events.
2020-07-25 18:03:02 +02:00

64 lines
1.9 KiB
Python

from server import db
from database.models import Calendar as dbCalendar
from backend import Event as bEvent
from ics import Calendar as iCalendar
import requests
def icalToCalendarDb(url, name, user):
try:
c = iCalendar(requests.get(url).text)
except:
return False
c = dbCalendar(calendar_id = url,
calendar_type = 'ical',
name = name,
toggle = "False",
color = "#000000")
db.session.add(c)
user.calendars.append(c)
db.session.commit()
def fetchCalendarEvents(calendars, startDate, endDate):
all_events = []
for calendar in calendars:
if calendar.toggle == "True" and calendar.calendar_type == "ical":
ical = iCalendar(requests.get(calendar.calendar_id).text)
for event in ical.events:
name = event.name
start = event.begin.format()
end = event.end.format()
newEvent = bEvent(name, start, end)
if eventWithinStartEnd(startDate, endDate, event):
if not eventAllDay(event):
all_events.append(newEvent)
return all_events
# converts everything to epoch seconds and utc
# and then checks if at either event start or event end
# is is within startDate and endDate
def eventWithinStartEnd(startDate, endDate, event):
if((startDate.timestamp() <= event.begin.timestamp and
event.begin.timestamp <= endDate.timestamp()) or
startDate.timestamp() <= event.end.timestamp and
event.end.timestamp <= endDate.timestamp()):
return True
return False
def eventAllDay(event):
beginDay = event.begin.replace(hour=0, minute=0, second=0)
endDay = event.end.replace(hour=0, minute=0, second=0)
delta = endDay - beginDay
if delta.days >= 2:
return True
return False