diff --git a/gapi/apis/base_api.py b/gapi/apis/base_api.py index 5f66e55..91e988f 100644 --- a/gapi/apis/base_api.py +++ b/gapi/apis/base_api.py @@ -1,19 +1,14 @@ import datetime -from googleapiclient.discovery import build - -from oauth2client import client -from oauth2client import tools -from oauth2client.file import Storage - - -import httplib2 import os +import pickle -import argparse + +from googleapiclient.discovery import build +from google_auth_oauthlib.flow import InstalledAppFlow +from google.auth.transport.requests import Request import gapi -flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() HOUR = datetime.timedelta(seconds=60 ** 2) @@ -38,29 +33,33 @@ class API: self.version = version def get_credentials(self): - - credential_path = os.path.join(self.credentials_dir, "token.json") - - store = Storage(credential_path) - credentials = store.get() - if not credentials or credentials.invalid: - flow = client.flow_from_clientsecrets(self.client_secret_file, self.scopes) - flow.user_agent = self.app_name - if flags: - credentials = tools.run_flow(flow, store, flags) + creds = None + # The file token.pickle stores the user's access and refresh tokens, and is + # created automatically when the authorization flow completes for the first + # time. + credential_path = os.path.join(self.credentials_dir, "token.pickle") + if os.path.exists(credential_path): + with open(credential_path, "rb") as token: + creds = pickle.load(token) + # 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: - credentials = tools.run(flow, store) + flow = InstalledAppFlow.from_client_secrets_file( + self.client_secret_file, self.scopes + ) + creds = flow.run_local_server(port=0) + # Save the credentials for the next run print("Storing credentials to " + credential_path) - return credentials + with open(credential_path, "wb") as token: + pickle.dump(creds, token) + return creds def build_service(self): credentials = self.get_credentials() - http = credentials.authorize(httplib2.Http()) - - service = build( - self.service_name, self.version, http=http, cache_discovery=False - ) + service = build(self.service_name, self.version, credentials=credentials) return service def _needs_renewal(self): diff --git a/requirements.txt b/requirements.txt index 6bceffc..722d98f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ +appdirs google-api-python-client +google-auth-httplib2 +google-auth-oauthlib python-dateutil -oauth2client tzlocal -appdirs