Change google adapter to use service account.
This commit is contained in:
parent
e683a90b34
commit
21be48f8e3
1 changed files with 13 additions and 24 deletions
|
@ -3,47 +3,36 @@
|
|||
|
||||
import tempfile
|
||||
import datetime
|
||||
import logging
|
||||
import os.path
|
||||
|
||||
import json
|
||||
from google.auth.transport.requests import Request
|
||||
from google.oauth2.credentials import Credentials
|
||||
#from google.oauth2.credentials import Credentials
|
||||
from google.oauth2.service_account import Credentials
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from googleapiclient.discovery import build
|
||||
from googleapiclient.errors import HttpError
|
||||
|
||||
logger = logging.getLogger(f"wp_cal.{__name__}")
|
||||
|
||||
# If modifying these scopes, delete the file token.json.
|
||||
SCOPES = ['https://www.googleapis.com/auth/calendar']
|
||||
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
|
||||
|
||||
|
||||
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_info = credentials
|
||||
self.credentials = None
|
||||
|
||||
def login(self):
|
||||
if os.path.exists(self.token_file):
|
||||
self.credentials = Credentials.from_authorized_user_file(self.token_file, SCOPES)
|
||||
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 = Credentials.from_service_account_info(self.credentials_info, scopes=SCOPES)
|
||||
if not self.credentials.valid:
|
||||
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())
|
||||
logger.debug('credentials.valid = %s', repr(self.credentials.valid))
|
||||
|
||||
|
||||
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)
|
||||
|
@ -59,7 +48,7 @@ class Google():
|
|||
maxResults=limit,
|
||||
).execute()
|
||||
except HttpError:
|
||||
print('an error occured')
|
||||
logger.exception("a http error occured")
|
||||
raise
|
||||
events = events.get('items', [])
|
||||
return events
|
||||
|
|
Loading…
Reference in a new issue