cal-proxy/app.py

72 lines
1.8 KiB
Python

from flask import Flask, request
import os
import urllib.request
from icalendar.cal import Calendar, Component
app = Flask(__name__)
EXCLUDED_COURSES = os.environ.get('COURSES', '').split(',')
EXCLUDED_TYPES = os.environ.get('TYPES', '').split(',')
YEAR = os.environ.get('YEAR', '4')
GROUP = os.environ.get('GROUP', '1')
ALLOWED_YEARS = os.environ.get('ALLOWED_YEARS', '3,4,5').split(',')
ALLOWED_GROUPS = os.environ.get('ALLOWED_GROUPS', '1,2,3').split(',')
@app.route("/")
def hello():
url = os.environ.get('URL', None)
if url is None:
return ""
year = request.args.get('year', '')
group = request.args.get('group', '')
try:
int(year)
if year not in ALLOWED_YEARS:
raise ValueError('year not allowed')
except ValueError:
year = YEAR
try:
int(group)
if group not in ALLOWED_GROUPS:
raise ValueError('group not allowed')
except ValueError:
group = GROUP
url += "&promo={year}&groupe={group}".format(year=year, group=group)
cal_str = urllib.request.urlopen(url).read()
cal = Component.from_ical(cal_str)
other = Calendar()
# Copy all properties of calendar
for k, v in cal.items():
other.add(k, v)
# Copy the VTIMEZONE component
other.add_component(cal.walk('VTIMEZONE')[0])
# Filter and copy VEVENTs
for ev in cal.walk('VEVENT'):
if should_add(ev):
other.add_component(ev)
return other.to_ical().replace(b'\r\n', b'\n').strip()
def should_add(event):
course_code = event['SUMMARY'].split('-')[1].split('/')[0]
course_type = event['SUMMARY'].split('/')[1].split('_')[1]
return \
course_code not in EXCLUDED_COURSES \
and course_type not in EXCLUDED_TYPES
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run('0.0.0.0', port)