wp-cal-integration/adapters/google.py

69 lines
2.5 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tempfile
import datetime
import os.path
import json
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']
class Google():
def __init__(self, calendar_id, *, credentials, token_file):
_, credentials_file = tempfile.mkstemp()
with open(credentials_file, 'w') as fp:
json.dump(credentials, fp)
self.calendar_id = calendar_id
self.credentials_file = credentials_file
self.token_file = token_file
self.credentials = None
def login(self):
print('token_file =', self.token_file)
print('exists?', os.path.exists(self.token_file))
if os.path.exists(self.token_file):
self.credentials = Credentials.from_authorized_user_file(self.token_file, SCOPES)
print('valid?', self.credentials.valid)
if self.credentials is None or not self.credentials.valid:
if self.credentials is not None \
and self.credentials.expired \
and self.credentials.refresh_token:
self.credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.credentials_file,
SCOPES,
)
self.credentials = flow.run_local_server(port=0)
with open(self.token_file, 'w') as token:
token.write(self.credentials.to_json())
def get_events(self, start: datetime.datetime | None=None, until: datetime.timedelta | None=None, limit=None):
until = until if until else datetime.timedelta(days=365)
now = start if start else datetime.datetime.utcnow().astimezone()
now_365 = now + until
try:
service = build('calendar', 'v3', credentials=self.credentials)
events = service.events().list(
calendarId=self.calendar_id,
timeMin=now.isoformat(),
timeMax=now_365.isoformat(),
maxResults=limit,
).execute()
except HttpError:
print('an error occured')
raise
events = events.get('items', [])
return events