2020-12-14 17:57:45 +01:00

61 lines
2.3 KiB
Python

import requests
from collections import namedtuple
from datetime import datetime, timedelta
class DaisyHandler:
def __init__(self, config):
self.auth = (config['daisy']['user'],
config['daisy']['password'])
self.headers = {'Accept': 'application/json'}
self.url = config['daisy']['url'].rstrip('/')
def _get(self, path, params={}):
requestpath = '{}{}'.format(self.url, path)
r = requests.get(requestpath,
params,
headers=self.headers,
auth=self.auth)
if not r.status_code == 200:
raise Exception('Got bad response from Daisy API: {}'
.format(r.status_code))
return r.json()
def get_booking(self, start_time, end_time, room):
fmt = '%Y-%m-%d'
start_day = start_time.strftime(fmt)
end_day = end_time.strftime(fmt)
params = {'start': start_day,
'end': end_day,
'room': room}
Fit = namedtuple('Fit', ['booking', 'overlap'])
best = Fit(None, timedelta())
for booking in self._get('/schedule', params=params):
b_start = datetime.fromtimestamp(int(booking['start'] / 1000))
b_end = datetime.fromtimestamp(int(booking['end'] / 1000))
range_start = max(start_time, b_start)
range_end = min(end_time, b_end)
overlap = range_end - range_start
if overlap > best.overlap:
best = Fit(booking, overlap)
return best.booking
def get_person(self, person_id):
usernames = [name['username']
for name in self._get(
'/person/{}/usernames'.format(person_id))
if name['realm'] == "SU.SE"]
if len(usernames) != 1:
raise Exception("More than one SU.SE username: {}"
.format(usernames))
return usernames[0]
def get_course(self, course_id):
course = self._get('/courseSegment/{}'.format(course_id))
return course['designation']
def get_room_name(self, room_id):
location = self._get('/location/{}'.format(room_id))
return location['designation']