diff --git a/calendar_booking_api.py b/calendar_booking_api.py index 1c00f79..9aa768b 100644 --- a/calendar_booking_api.py +++ b/calendar_booking_api.py @@ -1,6 +1,6 @@ import bisect from datetime import datetime, timedelta -from flask import Flask, jsonify, redirect, request +from flask import Flask, jsonify, make_response, redirect, request from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from googleapiclient.discovery import build @@ -14,7 +14,8 @@ WEEK_DAYS = {1, 2, 3, 4, 5} FROM = 9 TO = 17 -TIMEZONE = pytz.timezone('America/New_York') +TIMEZONE_NAME = 'America/New_York' +TIMEZONE = pytz.timezone(TIMEZONE_NAME) AVAILABILITY_LIFETIME = timedelta(minutes=2) @@ -31,8 +32,12 @@ def read_datetime(dct): return dt +def asiso(dt): + return dt.isoformat()[:19] + + def asutciso(dt): - return dt.astimezone(UTC).isoformat()[:19] + 'Z' + return asiso(dt.astimezone(UTC)) + 'Z' def aslocal(dt): @@ -111,6 +116,49 @@ def api_availability(): return jsonify({'availability': [asutciso(time) for time in availability]}) -@app.route('/book', methods=['POST']) +@app.route('/book', methods=['POST', 'OPTIONS']) def api_book(): - TODO + # Allow cross-origin + if request.method == 'OPTIONS': + response = make_response() + response.headers.add( + 'Access-Control-Allow-Origin', + 'https://vicky.rampin.org', + ) + response.headers.add( + 'Access-Control-Allow-Headers', + 'Content-Type', + ) + response.headers.add( + 'Access-Control-Allow-Methods', + 'POST', + ) + return response + + if not creds.valid: + creds.refresh(Request()) + service = build('calendar', 'v3', credentials=creds) + + full_name = request.form['name'] + email = request.form['email'] + topic = request.form['topic'] + date = request.form['date'] + + end = start + timedelta(minutes=30) + + service.events().insert( + calendarId='primary', + body=dict( + start={'dateTime': asiso(start), 'timeZone': TIMEZONE_NAME}, + end={'dateTime': asiso(end), 'timeZone': TIMEZONE_NAME}, + summary="Meeting with Vicky", + description="Meeting scheduled from the web", + ), + ) + + response = redirect('https://vicky.rampin.org/book-successful', 303) + response.headers.add( + 'Access-Control-Allow-Origin', + 'https://vicky.rampin.org', + ) + return response