import datetime import os import os.path import tempfile from icalendar import Calendar from webdav3.client import Client as WDClient class Client: def __init__(self, config): """ Initializes a client """ options = { 'webdav_hostname': config["WEBDAV_SERVER"], 'webdav_login': config["WEBDAV_USER"], 'webdav_password': config["WEBDAV_PASSWORD"], } self.calendar_path = config["CALENDAR_PATH"] self.client = WDClient(options) def retrieve_calendars_list(self): """ Retrieves the calendar list """ paths = [path for path in self.client.list(self.calendar_path) if ".ics" in path] return paths def read_calendar(self, pathname): """ Given a filename, tries to read the calendar event """ f, temp_path = tempfile.mkstemp() rpath = os.path.join(self.calendar_path, pathname) self.client.download_sync(remote_path=rpath, local_path=temp_path) # Read the temporary data, close the file, remove it fics = open(temp_path, 'r') data = fics.read() fics.close() os.remove(temp_path) # Now with the data read, we can process it return self.parse_calendar(data) def parse_calendar(self, data): """ Parses ICS calendar data received """ events = [] now = datetime.datetime.now() start_day = datetime.datetime(now.year, now.month, now.day) tomorrow = start_day + datetime.timedelta(days=1) calendar = Calendar.from_ical(data) for component in calendar.walk(): if component.name == 'VEVENT': event_date = component.decoded('dtstart') ed = datetime.datetime(event_date.year, event_date.month, event_date.day) if ed >= start_day and ed < tomorrow: events.append((component.get('summary'), component.decoded('dtstart'))) return events def get_todays_events(self): """ Get todays events """ calendars = self.retrieve_calendars_list() events = [] for calendar in calendars: cal_events = self.read_calendar(calendar) for ev in cal_events: events.append(ev) return events