Refactor Google Calendar module into a class
This commit is contained in:
parent
2c2848732e
commit
f29a6170c1
@ -17,57 +17,63 @@ SCOPES = [
|
||||
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())
|
||||
class CalendarService:
|
||||
service: Resource
|
||||
|
||||
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 build("calendar", "v3", credentials=creds)
|
||||
return 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(
|
||||
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}")
|
||||
|
||||
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:
|
||||
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:
|
||||
self.service.events().insert(
|
||||
calendarId=CALENDAR_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()
|
||||
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
raise
|
||||
|
8
main.py
8
main.py
@ -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:
|
||||
|
Loading…
Reference in New Issue
Block a user