Move google calendar functionality to a separate module
This commit is contained in:
parent
812ef0f979
commit
47a8e6f5ad
73
google_calendar.py
Normal file
73
google_calendar.py
Normal file
@ -0,0 +1,73 @@
|
||||
from datetime 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, Resource
|
||||
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() -> 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 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
|
||||
):
|
||||
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
|
85
main.py
85
main.py
@ -1,85 +1,20 @@
|
||||
import datetime
|
||||
import os.path
|
||||
from base64 import b32hexencode
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
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
|
||||
import google_calendar
|
||||
|
||||
|
||||
def main():
|
||||
creds = authenticate_google()
|
||||
service = build('calendar', 'v3', credentials=creds)
|
||||
creds = google_calendar.authenticate()
|
||||
service = google_calendar.get_service(creds)
|
||||
|
||||
insert_or_update_event(service,
|
||||
google_calendar.insert_or_update_event(
|
||||
service,
|
||||
"octoprint_test_event",
|
||||
"Test!",
|
||||
datetime.datetime.utcnow(),
|
||||
datetime.datetime.utcnow() + datetime.timedelta(hours=1))
|
||||
datetime.utcnow(),
|
||||
datetime.utcnow() + timedelta(hours=1),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
Loading…
Reference in New Issue
Block a user