wp-cal-integration/adapters/google.py

53 lines
1.8 KiB
Python
Raw Normal View History

2022-09-28 15:59:12 +02:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2022-09-28 15:52:52 +02:00
import datetime
import logging
2022-09-28 15:52:52 +02:00
from google.auth.transport.requests import Request
#from google.oauth2.credentials import Credentials
from google.oauth2.service_account import Credentials
2022-09-28 15:52:52 +02:00
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
logger = logging.getLogger(f"wp_cal.{__name__}")
2022-09-28 15:52:52 +02:00
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
2022-09-28 15:52:52 +02:00
class Google():
def __init__(self, calendar_id, *, credentials, token_file):
self.calendar_id = calendar_id
self.credentials_info = credentials
2022-09-28 15:52:52 +02:00
self.credentials = None
def login(self):
self.credentials = Credentials.from_service_account_info(self.credentials_info, scopes=SCOPES)
if not self.credentials.valid:
self.credentials.refresh(Request())
logger.debug('credentials.valid = %s', repr(self.credentials.valid))
2022-09-28 15:52:52 +02:00
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:
logger.exception("a http error occured")
2022-09-28 15:52:52 +02:00
raise
events = events.get('items', [])
return events