From 47a8e6f5ad2cc28e729e34d8b95597c8675e44cd Mon Sep 17 00:00:00 2001 From: Adam Goldsmith Date: Mon, 27 Dec 2021 14:31:26 -0500 Subject: [PATCH] Move google calendar functionality to a separate module --- google_calendar.py | 73 +++++++++++++++++++++++++++++++++++++ main.py | 89 +++++++--------------------------------------- 2 files changed, 85 insertions(+), 77 deletions(-) create mode 100644 google_calendar.py diff --git a/google_calendar.py b/google_calendar.py new file mode 100644 index 0000000..5500982 --- /dev/null +++ b/google_calendar.py @@ -0,0 +1,73 @@ +from datetime import datetime +import os.path +from base64 import b32hexencode + +from google.auth.transport.requests import Request +from google.oauth2.credentials import Credentials +from google_auth_oauthlib.flow import InstalledAppFlow +from googleapiclient.discovery import build, Resource +from googleapiclient.errors import HttpError + +# If modifying these scopes, delete the file token.json. +SCOPES = [ + "https://www.googleapis.com/auth/calendar.readonly", + "https://www.googleapis.com/auth/calendar.events", +] + +CALENDAR_ID = "40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com" + + +def authenticate() -> Credentials: + creds = None + # The file token.json stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + if os.path.exists("token.json"): + creds = Credentials.from_authorized_user_file("token.json", SCOPES) + # If there are no (valid) credentials available, let the user log in. + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + creds.refresh(Request()) + else: + flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run + with open("token.json", "w") as token: + token.write(creds.to_json()) + + return creds + + +def get_service(creds: Credentials) -> Resource: + return build("calendar", "v3", credentials=creds) + + +def insert_or_update_event( + service: Resource, id: str, title: str, start: datetime, end: datetime +): + event_id = b32hexencode(id.encode("ascii")).decode("ascii").lower() + event = { + "id": event_id, + "summary": title, + "start": { + "dateTime": start.isoformat() + "Z", # 'Z' indicates UTC time + }, + "end": { + "dateTime": end.isoformat() + "Z", # 'Z' indicates UTC time + }, + } + + print(f"Adding/updating event: {title}, start: {start}, end: {end}") + + try: + service.events().update( + calendarId=CALENDAR_ID, eventId=event_id, body=event + ).execute() + + except HttpError as error: + # Create event if it doesn't exist + if error.status_code == 409: + service.events().insert(calendarId=CALENDAR_ID, body=event).execute() + + else: + raise diff --git a/main.py b/main.py index cb1da74..452c9ec 100644 --- a/main.py +++ b/main.py @@ -1,85 +1,20 @@ -import datetime -import os.path -from base64 import b32hexencode +from datetime import datetime, timedelta -from google.auth.transport.requests import Request -from google.oauth2.credentials import Credentials -from google_auth_oauthlib.flow import InstalledAppFlow -from googleapiclient.discovery import build -from googleapiclient.errors import HttpError - -# If modifying these scopes, delete the file token.json. -SCOPES = ['https://www.googleapis.com/auth/calendar.readonly', - 'https://www.googleapis.com/auth/calendar.events'] - -CALENDAR_ID = '40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com' - - -def authenticate_google() -> Credentials: - creds = None - # The file token.json stores the user's access and refresh tokens, and is - # created automatically when the authorization flow completes for the first - # time. - if os.path.exists('token.json'): - creds = Credentials.from_authorized_user_file('token.json', SCOPES) - # If there are no (valid) credentials available, let the user log in. - if not creds or not creds.valid: - if creds and creds.expired and creds.refresh_token: - creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server(port=0) - # Save the credentials for the next run - with open('token.json', 'w') as token: - token.write(creds.to_json()) - - return creds - - -def insert_or_update_event(service, id, title, start, end): - event_id = b32hexencode(id.encode('ascii')).decode('ascii').lower() - event = { - "id": event_id, - "summary": title, - "start": { - "dateTime": start.isoformat() + 'Z', # 'Z' indicates UTC time - }, - "end": { - "dateTime": end.isoformat() + 'Z', # 'Z' indicates UTC time - }, - } - - print(f"Adding/updating event: {title}, start: {start}, end: {end}") - - try: - service \ - .events() \ - .update(calendarId=CALENDAR_ID, eventId=event_id, body=event) \ - .execute() - - except HttpError as error: - # Create event if it doesn't exist - if error.status_code == 409: - service \ - .events() \ - .insert(calendarId=CALENDAR_ID, body=event) \ - .execute() - - else: - raise error +import google_calendar def main(): - creds = authenticate_google() - service = build('calendar', 'v3', credentials=creds) + creds = google_calendar.authenticate() + service = google_calendar.get_service(creds) - insert_or_update_event(service, - "octoprint_test_event", - "Test!", - datetime.datetime.utcnow(), - datetime.datetime.utcnow() + datetime.timedelta(hours=1)) + google_calendar.insert_or_update_event( + service, + "octoprint_test_event", + "Test!", + datetime.utcnow(), + datetime.utcnow() + timedelta(hours=1), + ) -if __name__ == '__main__': +if __name__ == "__main__": main()