Spaces:
Sleeping
Sleeping
| import os | |
| os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' | |
| import json | |
| from flask import Flask, redirect, url_for, request, jsonify | |
| from google.oauth2.credentials import Credentials | |
| from google_auth_oauthlib.flow import InstalledAppFlow | |
| from googleapiclient.discovery import build | |
| import datetime | |
| app = Flask(__name__) | |
| CLIENT_SECRETS_FILE = "credentials.json" | |
| SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] | |
| REDIRECT_URI = "https://nsquarzoni-gcalendar.hf.space/oauth2callback" | |
| flow = InstalledAppFlow.from_client_secrets_file( | |
| CLIENT_SECRETS_FILE, | |
| scopes=SCOPES, | |
| redirect_uri=REDIRECT_URI | |
| ) | |
| def index(): | |
| credentials = None | |
| if os.path.exists("token.json") and os.path.getsize("token.json") > 0: | |
| with open("/app/token.json", 'r') as file: | |
| data = json.load(file) | |
| return data | |
| #credentials = Credentials.from_authorized_user_file("/app/token.json") | |
| #return '<pre>Already authorized</pre>' | |
| #return credentials.jsonify | |
| if not credentials or not credentials.valid: | |
| authorization_url, state = flow.authorization_url( | |
| access_type='offline', | |
| include_granted_scopes='true' | |
| ) | |
| return redirect(authorization_url) | |
| def oauth2callback(): | |
| flow.fetch_token(authorization_response=request.url) | |
| credentials = flow.credentials | |
| return credentials.to_json() | |
| with open("/app/token.json", "w") as file: | |
| file.write(credentials.to_json()) | |
| with open("/app/token.json", 'r') as file: | |
| data = json.load(file) | |
| return data | |
| service = build('calendar', 'v3', credentials=credentials) | |
| now = datetime.datetime.utcnow().isoformat() + 'Z' | |
| end_of_week = (datetime.datetime.utcnow() + datetime.timedelta(days=7)).isoformat() + 'Z' | |
| events_result = service.events().list(calendarId='primary', timeMin=now, timeMax=end_of_week, | |
| singleEvents=True, orderBy='startTime').execute() | |
| events = events_result.get('items', []) | |
| return jsonify(events) | |
| if __name__ == '__main__': | |
| app.run(port=7860) |