Refactor Google Calendar module into a class

This commit is contained in:
Adam Goldsmith 2021-12-28 00:01:05 -05:00
parent 2c2848732e
commit f29a6170c1
2 changed files with 55 additions and 51 deletions

View File

@ -17,57 +17,63 @@ SCOPES = [
CALENDAR_ID = "40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com" CALENDAR_ID = "40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com"
def authenticate() -> Credentials: class CalendarService:
creds = None service: Resource
# 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 __init__(self):
creds = self._authenticate()
self.service = build("calendar", "v3", credentials=creds)
def _authenticate(self) -> 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())
def get_service(creds: Credentials) -> Resource: return creds
return build("calendar", "v3", credentials=creds)
def insert_or_update_event(
self, id: str, title: str, start: datetime, end: datetime
):
event_id = b32hexencode(id.encode("ascii")).decode("ascii").lower().rstrip("=")
event = {
"id": event_id,
"summary": title,
"start": {
"dateTime": start.isoformat() + "Z", # 'Z' indicates UTC time
},
"end": {
"dateTime": end.isoformat() + "Z", # 'Z' indicates UTC time
},
}
def insert_or_update_event( print(f"Adding/updating event: {title}, start: {start}, end: {end}")
service: Resource, id: str, title: str, start: datetime, end: datetime
):
event_id = b32hexencode(id.encode("ascii")).decode("ascii").lower().rstrip("=")
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:
self.service.events().update(
calendarId=CALENDAR_ID, eventId=event_id, body=event
).execute()
try: except HttpError as error:
service.events().update( # Create event if it doesn't exist
calendarId=CALENDAR_ID, eventId=event_id, body=event if error.status_code == 404:
).execute() self.service.events().insert(
calendarId=CALENDAR_ID, body=event
).execute()
except HttpError as error: else:
# Create event if it doesn't exist raise
if error.status_code == 404:
service.events().insert(calendarId=CALENDAR_ID, body=event).execute()
else:
raise

View File

@ -3,7 +3,7 @@ from datetime import datetime, timedelta
from octorest import OctoRest from octorest import OctoRest
from ruamel.yaml import YAML from ruamel.yaml import YAML
import google_calendar from google_calendar import CalendarService
def get_printer_job(calendar, printer): def get_printer_job(calendar, printer):
@ -18,8 +18,7 @@ def get_printer_job(calendar, printer):
print(current_job["job"]["file"]["name"], start, estimated_end) print(current_job["job"]["file"]["name"], start, estimated_end)
event_name = f'{current_job["job"]["user"]} | Digital Fabrication and Electronics Lab - {printer["name"]}' event_name = f'{current_job["job"]["user"]} | Digital Fabrication and Electronics Lab - {printer["name"]}'
google_calendar.insert_or_update_event( calendar.insert_or_update_event(
calendar,
f'OctoPrint Reservations: {printer["name"]}', f'OctoPrint Reservations: {printer["name"]}',
event_name, event_name,
start, start,
@ -31,8 +30,7 @@ def get_printer_job(calendar, printer):
def main(): def main():
creds = google_calendar.authenticate() calendar = CalendarService()
calendar = google_calendar.get_service(creds)
yaml = YAML(typ="safe") yaml = YAML(typ="safe")
with open("printers.yaml") as f: with open("printers.yaml") as f: