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,7 +17,14 @@ SCOPES = [
CALENDAR_ID = "40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com" CALENDAR_ID = "40e4v6t1s2spr9f1d9d45br3ik@group.calendar.google.com"
def authenticate() -> Credentials: class CalendarService:
service: Resource
def __init__(self):
creds = self._authenticate()
self.service = build("calendar", "v3", credentials=creds)
def _authenticate(self) -> Credentials:
creds = None creds = None
# The file token.json stores the user's access and refresh tokens, and is # The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first # created automatically when the authorization flow completes for the first
@ -29,7 +36,9 @@ def authenticate() -> Credentials:
if creds and creds.expired and creds.refresh_token: if creds and creds.expired and creds.refresh_token:
creds.refresh(Request()) creds.refresh(Request())
else: else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json", SCOPES
)
creds = flow.run_local_server(port=0) creds = flow.run_local_server(port=0)
# Save the credentials for the next run # Save the credentials for the next run
with open("token.json", "w") as token: with open("token.json", "w") as token:
@ -37,14 +46,9 @@ def authenticate() -> Credentials:
return creds return creds
def insert_or_update_event(
def get_service(creds: Credentials) -> Resource: self, id: str, title: str, start: datetime, end: datetime
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().rstrip("=") event_id = b32hexencode(id.encode("ascii")).decode("ascii").lower().rstrip("=")
event = { event = {
"id": event_id, "id": event_id,
@ -60,14 +64,16 @@ def insert_or_update_event(
print(f"Adding/updating event: {title}, start: {start}, end: {end}") print(f"Adding/updating event: {title}, start: {start}, end: {end}")
try: try:
service.events().update( self.service.events().update(
calendarId=CALENDAR_ID, eventId=event_id, body=event calendarId=CALENDAR_ID, eventId=event_id, body=event
).execute() ).execute()
except HttpError as error: except HttpError as error:
# Create event if it doesn't exist # Create event if it doesn't exist
if error.status_code == 404: if error.status_code == 404:
service.events().insert(calendarId=CALENDAR_ID, body=event).execute() self.service.events().insert(
calendarId=CALENDAR_ID, body=event
).execute()
else: else:
raise 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: