Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Free Timeslots Endpoint #36

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ def toJSON(self):
"user_id": self.user_id
})

class Interval:
def __init__(self, start, end, id, duration):
self.start = start
self.end = end
self.id = id
self.duration = duration

def toJSON(self):
return jsonify({
"start": self.start,
"end": self.end,
"id": self.id,
"duration": self.duration
})

class Error(Exception):
status_code = 400

Expand Down
43 changes: 41 additions & 2 deletions backend/app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
from dateutil import parser
from google.auth.transport import requests
from .models import User, Error
from .util import convertDateToRFC3339
import os.path, json
from .util import convertDateToRFC3339, convertDateTimeToRFC3339, formulate_open_timeslots
import os.path, json, time, datetime, pytz
from pytz import timezone

routes_blueprint = Blueprint('routes', __name__)

Expand Down Expand Up @@ -57,6 +58,44 @@ def login():
# Invalid token
raise Error(e, status_code = 400)

@routes_blueprint.route('/free_intervals/id=<id>')
@cross_origin(supports_credentials=True)
def get_free_intervals(id):
user = User.objects(user_id = id).first()
if not user:
raise Error("No existing user with the associated user ID", status_code = 400)
else:
access_token = user.access_token


credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')


try:
service = build('calendar', 'v3', credentials=credentials)

local_timezone = timezone('US/Pacific')
now = datetime.datetime.now(tz=local_timezone)
today = now.date()
today_7am = local_timezone.localize(datetime.datetime.combine(today, datetime.time(7,0)))
tomorrow = today + datetime.timedelta(days=1)
tomorrow_start = local_timezone.localize(datetime.datetime.combine(tomorrow, datetime.time(0,0)))

events_result = service.events().list(calendarId='primary', timeMin=convertDateTimeToRFC3339(today_7am), timeMax=convertDateTimeToRFC3339(tomorrow_start), singleEvents=True, orderBy='startTime').execute()
if not events_result:
raise ValueError("Could not get events from Calendar API", status_code = 500)
events = events_result.get('items', [])

return jsonify([timeslot.__dict__ for timeslot in formulate_open_timeslots(events, today)]), 200


except ValueError as e:
raise Error(e, status_code = 500)

except Exception as e:
raise Error("Could not connect to calendar API, perhaps due to invalid credentials/access_token --> Returned Error: {}".format(e), status_code = 400)



@routes_blueprint.route('/calendar/id=<id>&start=<start_date>&end=<end_date>', methods=['GET'])
@cross_origin(supports_credentials=True)
Expand Down
43 changes: 41 additions & 2 deletions backend/app/util.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,48 @@
from dateutil import parser
import datetime, time
from .models import Interval
from pytz import timezone
import datetime, time, pytz



def convertDateToRFC3339(date):
# Parse date into datetime object
date_time = parser.parse(date)

# Return RFC3339 date after switching to UTC format
return datetime.datetime.utcfromtimestamp(time.mktime(date_time.timetuple())).isoformat('T') + 'Z'
return date_time.astimezone(tz=pytz.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')

def convertDateTimeToRFC3339(date_time):
return date_time.astimezone(tz=pytz.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')

def duration(start, end):
difference_seconds = (end - start).total_seconds()
hours, leftover_seconds = divmod(difference_seconds, 3600)
return float(hours) + float(leftover_seconds/3600)

def formulate_open_timeslots(events, current_date):
time_slots = []
local_timezone = timezone('US/Pacific')
start_time = local_timezone.localize(datetime.datetime.combine(current_date, datetime.time(7, 0))) # beginning of first interval is 7am day 1
end_time = local_timezone.localize(datetime.datetime.combine(current_date + datetime.timedelta(days = 1), datetime.time(0, 0))) #end of first interval is beginning of next day
curr_interval = (start_time, end_time)
i = 1

for event in events:
event_start = parser.parse(event['start']['dateTime']).astimezone(local_timezone) #assume event time is PST timezone
event_end = parser.parse(event['end']['dateTime']).astimezone(local_timezone) #assume event time is PST timezone

if event_start > curr_interval[0]:
new_interval = (event_end, curr_interval[1])
changed_curr_interval = (curr_interval[0], event_start)
time_slots.append(Interval(changed_curr_interval[0], changed_curr_interval[1], i, duration(changed_curr_interval[0], changed_curr_interval[1])))

i += 1
curr_interval = new_interval
elif event_end > curr_interval[0]:
new_interval = (event_end, curr_interval[1])
curr_interval = new_interval

time_slots.append(Interval(curr_interval[0], curr_interval[1], i, duration(curr_interval[0], curr_interval[1])))

return time_slots
1 change: 1 addition & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pyasn1==0.4.5
pyasn1-modules==0.2.4
pymongo==3.7.2
python-dateutil==2.8.0
pytz==2019.1
requests==2.21.0
requests-oauthlib==1.2.0
rsa==4.0
Expand Down