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"
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
# The file token.json stores the user's access and refresh tokens, and is
# 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:
creds.refresh(Request())
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)
# Save the credentials for the next run
with open("token.json", "w") as token:
@ -37,14 +46,9 @@ def authenticate() -> Credentials:
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
):
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,
@ -60,14 +64,16 @@ def insert_or_update_event(
print(f"Adding/updating event: {title}, start: {start}, end: {end}")
try:
service.events().update(
self.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 == 404:
service.events().insert(calendarId=CALENDAR_ID, body=event).execute()
self.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 ruamel.yaml import YAML
import google_calendar
from google_calendar import CalendarService
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)
event_name = f'{current_job["job"]["user"]} | Digital Fabrication and Electronics Lab - {printer["name"]}'
google_calendar.insert_or_update_event(
calendar,
calendar.insert_or_update_event(
f'OctoPrint Reservations: {printer["name"]}',
event_name,
start,
@ -31,8 +30,7 @@ def get_printer_job(calendar, printer):
def main():
creds = google_calendar.authenticate()
calendar = google_calendar.get_service(creds)
calendar = CalendarService()
yaml = YAML(typ="safe")
with open("printers.yaml") as f: