smallprint/webdav.py

90 lines
2.8 KiB
Python

import datetime
import os
import os.path
from pathlib import Path
from icalendar import Calendar
from webdav3.client import Client as WDClient
CACHE_DIR = "~/.cache/smallprint"
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)
cache_path = Path(CACHE_DIR).expanduser() # Generate the full path
if not cache_path.is_dir():
# Create the cache dir
os.mkdir(cache_path)
self.cache_path = cache_path
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
"""
cache_file = os.path.join(self.cache_path, pathname)
if not os.path.exists(cache_file):
print(f"Downloading {pathname}")
# File not in cache, download
rpath = os.path.join(self.calendar_path, pathname)
self.client.download_sync(remote_path=rpath,
local_path=cache_file)
# Read the downloaded or cached data
with open(cache_file, 'r') as fics:
fics = open(cache_file, 'r')
data = fics.read()
# 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