icalendar_tools.py 1.76 KB
Newer Older
1
import logging
Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
2 3 4 5 6 7 8 9
from datetime import datetime, date
from typing import Union

from icalendar import Calendar
from requests import get
from requests.auth import HTTPBasicAuth


10 11
class OnlineCalendar:
    logger = logging.getLogger('OnlineCalendar')
Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
12

13 14 15 16 17
    def __init__(self, url: str, login: str, password: str):
        """Download and parse an icalendar file with authentication"""
        self.logger.info("Downloading {}".format(url))
        request = get(url, auth=HTTPBasicAuth(login, password))
        content = request.text
Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
        # Parse components
        self.components = Calendar.from_ical(content)

    def get_events(self):
        """Return all calendar events"""
        for component in self.components.walk():
            if component.name == 'VEVENT':
                yield component

    def get_todos(self):
        """Return all calendar tasks"""
        for component in self.components.walk():
            if component.name == 'VTODO':
                yield component

Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
34 35 36 37 38 39
    def get_timezone(self):
        """Return one timezone"""
        for component in self.components.walk():
            if component.name == 'VTIMEZONE':
                return component

40 41
    def get_other_components(self):
        """Return all unrecognised components"""
Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
42
        blacklist = ['VEVENT', 'VTODO', 'VTIMEZONE', 'VCALENDAR', 'DAYLIGHT', 'STANDARD']
43 44 45 46

        for component in self.components.walk():
            if component.name not in blacklist:
                yield component
Alexandre (erdnaxe)'s avatar
Alexandre (erdnaxe) committed
47 48 49 50 51 52 53 54 55 56 57 58


def get_event_start_date(event) -> Union[date, bool]:
    """Return start date of an event"""
    event_date = event.decoded('dtstart')

    if isinstance(event_date, datetime):
        return event_date.date()
    elif isinstance(event_date, date):
        return event_date
    else:
        return False