OctoprintReservations/main.py

86 lines
2.7 KiB
Python
Raw Normal View History

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
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
def main():
creds = authenticate_google()
service = build('calendar', 'v3', credentials=creds)
insert_or_update_event(service,
"octoprint_test_event",
"Test!",
datetime.datetime.utcnow(),
datetime.datetime.utcnow() + datetime.timedelta(hours=1))
if __name__ == '__main__':
main()