Commit d20ac05d authored by Alexandre (erdnaxe)'s avatar Alexandre (erdnaxe) 🎇

Write ics and cleanup

parent fd3955bf
......@@ -7,3 +7,5 @@ config.yml
# Python specific
__pycache__
# Generated
*.ics
\ No newline at end of file
from urllib.parse import urljoin
import keyring
import yaml
class Configuration:
"""Regroup app configuration"""
def __init__(self, yaml_file):
with open(yaml_file, 'r') as f:
config = yaml.load(f)
self.base_url = config['base_url']
self.calendars_url = [urljoin(self.base_url, r) for r in config['calendars_url']]
self.login = config['login']
self.selected_groups = config['selected_groups']
# Load password
self.password = keyring.get_password('sogo', self.login)
import logging
import re
from datetime import date
from icalendar_tools import get_event_start_date
logger = logging.getLogger('Filters')
def filter_date(event) -> bool:
"""Return true if event day is today or in the future"""
event_date = get_event_start_date(event)
if event_date:
return event_date >= date.today()
else:
# If there is a bug in data then do not filter
summary = event.get('summary')
logger.warn('There was an issue with the date of {}'.format(summary))
return True
def filter_group(event, selected_groups) -> bool:
"""Filter group according to the group selected"""
summary = event.get('summary')
summary_search = re.search('([0-9]{3}) - ([A-Z]{2}) \(grpe : ([^\)]*)\)', summary, re.IGNORECASE)
if summary_search:
ue, group = summary_search.group(1), summary_search.group(3)
if int(ue) in selected_groups:
if group in selected_groups[int(ue)]:
ue, group = 'ue_' + summary_search.group(1), summary_search.group(3)
if ue in selected_groups:
# UE is configured
if group in selected_groups[ue]:
# Group was selected
return True
else:
# Group is not the one selected
print('-- UE', ue, 'group', group, 'removed')
logger.info('Removed {} because it had not been chosen'.format(summary))
return False
# If there is not a group specified do not filter
......
import logging
from datetime import datetime, date
from typing import Union
......@@ -6,21 +7,41 @@ from requests import get
from requests.auth import HTTPBasicAuth
def download_icalendar(url: str, login: str, password: str) -> Calendar:
"""Download and parse an icalendar file with authentication"""
class OnlineCalendar:
logger = logging.getLogger('OnlineCalendar')
# Download calendar
print('Downloading', url)
request = get(url, auth=HTTPBasicAuth(login, password))
content = request.text
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
# Parse to create a calendar
return Calendar.from_ical(content)
# 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
def get_other_components(self):
"""Return all unrecognised components"""
blacklist = ['VEVENT', 'VTODO', 'VCALENDAR', 'DAYLIGHT', 'VTIMEZONE', 'STANDARD']
for component in self.components.walk():
if component.name not in blacklist:
yield component
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):
......
from urllib.parse import urljoin
import logging
import keyring
import yaml
from icalendar import Calendar
from configuration import Configuration
from filters import filter_date, filter_group
from icalendar_tools import download_icalendar, get_event_start_date
with open("config.yml", 'r') as f:
config = yaml.load(f)
base_url = config['base_url']
calendars_url = [urljoin(base_url, r) for r in config['calendars_url']]
login = config['login']
selected_groups = config['selected_groups']
password = keyring.get_password('sogo', login)
for url in calendars_url:
cal = download_icalendar(url, login, password)
for event in cal.walk():
# If it is an event in the future
if event.name == 'VEVENT' and filter_date(event) and filter_group(event, selected_groups):
print(event.get('summary'), get_event_start_date(event))
from icalendar_tools import OnlineCalendar
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
config = Configuration('config.yml')
calendar = Calendar()
for url in config.calendars_url:
online_calendar = OnlineCalendar(url, config.login, config.password)
for event in online_calendar.get_events():
# If it is an event in the future and in the correct group
if filter_date(event) and filter_group(event, config.selected_groups):
logging.debug('An event was added : {}'.format(event.get('summary')))
calendar.add_component(event)
for todo in online_calendar.get_todos():
logging.debug('A task was added : {}'.format(todo.get('summary')))
calendar.add_component(todo)
for component in online_calendar.get_other_components():
logging.info('A unrecognised component ({}) was added : {}'.format(component.name, component.to_ical()))
calendar.add_component(component)
# Write resulting calendar
with open('calendar.ics', 'wb') as f:
f.write(calendar.to_ical())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment