Python google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file() Examples

The following are 28 code examples of google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module google_auth_oauthlib.flow.InstalledAppFlow , or try the search function .
Example #1
Source File: bot.py    From Telegram-bot-Google-Drive with MIT License 6 votes vote down vote up
def getCreds():
  # 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.
  creds = None
  SCOPES = 'https://www.googleapis.com/auth/drive'

  if os.path.exists('token.pickle'):
      with open('token.pickle', '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:
          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.pickle', 'wb') as token:
          pickle.dump(creds, token)

  return creds 
Example #2
Source File: google_email.py    From trusat-backend with Apache License 2.0 6 votes vote down vote up
def init_email_sending():
    SCOPES = ['https://www.googleapis.com/auth/gmail.send']

    creds = None

    try:
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        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_console()
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)
        return True
    except Exception as e:
        print(e)
        return False 
Example #3
Source File: flow.py    From google-auth-library-python-oauthlib with Apache License 2.0 6 votes vote down vote up
def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs):
        """Creates a :class:`Flow` instance from a Google client secrets file.

        Args:
            client_secrets_file (str): The path to the client secrets .json
                file.
            scopes (Sequence[str]): The list of scopes to request during the
                flow.
            kwargs: Any additional parameters passed to
                :class:`requests_oauthlib.OAuth2Session`

        Returns:
            Flow: The constructed Flow instance.
        """
        with open(client_secrets_file, "r") as json_file:
            client_config = json.load(json_file)

        return cls.from_client_config(client_config, scopes=scopes, **kwargs) 
Example #4
Source File: config.py    From sroka with MIT License 6 votes vote down vote up
def set_google_credentials(authorized_user_file,
                           key_file_location,
                           scope):

    try:
        credentials = Credentials.from_authorized_user_file(authorized_user_file, scopes=[scope])
    except FileNotFoundError:
        flow = InstalledAppFlow.from_client_secrets_file(key_file_location, [scope])
        credentials = flow.run_console()
        os.makedirs(os.path.expanduser('~/.cache/'), exist_ok=True)
        with open(authorized_user_file, 'w') as file:
            json.dump({
                'client_id': credentials._client_id,
                'client_secret': credentials._client_secret,
                'refresh_token': credentials._refresh_token
            }, file)
        os.chmod(authorized_user_file, 0o600)
    return credentials 
Example #5
Source File: gdriveTools.py    From python-aria-mirror-bot with GNU General Public License v3.0 6 votes vote down vote up
def authorize(self):
        # Get credentials
        credentials = None
        if not USE_SERVICE_ACCOUNTS:
            if os.path.exists(self.__G_DRIVE_TOKEN_FILE):
                with open(self.__G_DRIVE_TOKEN_FILE, 'rb') as f:
                    credentials = pickle.load(f)
            if credentials is None or not credentials.valid:
                if credentials and credentials.expired and credentials.refresh_token:
                    credentials.refresh(Request())
                else:
                    flow = InstalledAppFlow.from_client_secrets_file(
                        'credentials.json', self.__OAUTH_SCOPE)
                    LOGGER.info(flow)
                    credentials = flow.run_console(port=0)

                # Save the credentials for the next run
                with open(self.__G_DRIVE_TOKEN_FILE, 'wb') as token:
                    pickle.dump(credentials, token)
        else:
            LOGGER.info(f"Authorizing with {SERVICE_ACCOUNT_INDEX}.json service account")
            credentials = service_account.Credentials.from_service_account_file(
                f'accounts/{SERVICE_ACCOUNT_INDEX}.json',
                scopes=self.__OAUTH_SCOPE)
        return build('drive', 'v3', credentials=credentials, cache_discovery=False) 
Example #6
Source File: by_email_oauth.py    From UoM-WAM-Spam with MIT License 6 votes vote down vote up
def __init__(self, address):
        """
        Initialise a GMail notifier object. Prompt the user to authenticate
        and provide mailing permissions if required.
        """
        self.address = address
        self.creds = None
        # if there's an access token from previous authentication, load it
        if os.path.exists(ACCESS_TOKEN_PATH):
            with open(ACCESS_TOKEN_PATH, 'rb') as tokenfile:
                self.creds = pickle.load(tokenfile)

        # if the credentials are invalid or non-existent, prompt to authenticate
        if not self.creds or not self.creds.valid:
            if self.creds and self.creds.expired and self.creds.refresh_token:
                self.creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    CLIENT_ID_PATH, SCOPES)
                self.creds = flow.run_local_server()
            # save the credentials for the next run
            with open(ACCESS_TOKEN_PATH, 'wb') as tokenfile:
                pickle.dump(self.creds, tokenfile)

        self.service = build('gmail', 'v1', credentials=self.creds) 
Example #7
Source File: _helpers.py    From folderclone with GNU General Public License v3.0 6 votes vote down vote up
def get_creds(credentials,token,scopes=['https://www.googleapis.com/auth/drive']):
    creds = None

    if path.exists(token):
        with open(token,'r') as t:
            creds = json_to_cred(t)
    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,scopes)
            creds = flow.run_local_server(port=0)
        with open(token,'w') as t:
            json.dump(cred_to_json(creds),t,indent=2)

    return creds 
Example #8
Source File: google_email.py    From trusat-backend with Apache License 2.0 5 votes vote down vote up
def send_recovery_email(to, message_text):
    SCOPES = ['https://www.googleapis.com/auth/gmail.send']

    creds = None

    try:
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        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_console()
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)

        message_to_send = create_recovery_message('kenan.oneal@consensys.net', to, 'TruSat - Recover Account', message_text)

        sent_message = send_message(service, 'me', message_to_send)
        if sent_message == False:
            return False
        return True
    except:
        return False 
Example #9
Source File: google_email.py    From trusat-backend with Apache License 2.0 5 votes vote down vote up
def send_email(to, message_text):
    SCOPES = ['https://www.googleapis.com/auth/gmail.send']

    creds = None

    try:
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        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_console()
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)

        message_to_send = create_message('kenan.oneal@consensys.net', to, 'TruSat - Save this email: Recovery Info', message_text)

        sent_message = send_message(service, 'me', message_to_send)
        if sent_message == False:
            return False
        return True
    except:
        return False 
Example #10
Source File: google_email.py    From trusat-backend with Apache License 2.0 5 votes vote down vote up
def stop_history_watch():
    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

    creds = None
    try:
        if os.path.exists('history_token.pickle'):
            with open('history_token.pickle', 'rb') as token:
                creds = pickle.load(token)

        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_console()
            with open('history_token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('gmail', 'v1', credentials=creds)

        results = service.users().stop(userId='me').execute()
        print(results)
        return True
    except Exception as e:
        print(e)
        return False 
Example #11
Source File: drive_api.py    From InfiniDrive with GNU General Public License v3.0 5 votes vote down vote up
def get_service():
	"""Shows basic usage of the Drive v3 API.
	Prints the names and ids of the first 10 files the user has access to.
	"""
	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.
	if os.path.exists('token.pickle'):
		with open('token.pickle', '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:
			flow = InstalledAppFlow.from_client_secrets_file(
				'credentials.json', SCOPES)
			creds = flow.run_local_server()
		# Save the credentials for the next run
		with open('token.pickle', 'wb') as token:
			pickle.dump(creds, token)

	service = build('drive', 'v3', credentials=creds)
	return service

#Creates the InfiniDrive root folder and returns its ID. 
Example #12
Source File: sheets_to_df.py    From CDSS with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, json_file):
        # Authenticate and connect

        # If modifying these scopes, delete the file token.pickle.
        SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

        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.
        if os.path.exists('token.pickle'):
            with open('token.pickle', '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:
                flow = InstalledAppFlow.from_client_secrets_file(
                    json_file,
                    SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        self.service = build('sheets', 'v4', credentials=creds) 
Example #13
Source File: verify_email.py    From forseti-security with Apache License 2.0 5 votes vote down vote up
def get_service(pickle_path):
    """Create the Gmail client service.

    Args:
        pickle_path (str): Path to the pickle file.

    Returns:
        Service: Returns the Gmail client service.
    """
    credentials = None

    # The file gmail_token.pickle 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(pickle_path):
        with open(pickle_path, 'rb') as token:
            credentials = pickle.load(token)

    # If there are no (valid) credentials available, let the user log in.
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json',
                SCOPES)
            credentials = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(pickle_path, 'wb') as token:
            pickle.dump(credentials, token)

    service = build('gmail', 'v1', credentials=credentials)
    return service 
Example #14
Source File: gbcommon.py    From addon-hassiogooglebackup with MIT License 5 votes vote down vote up
def getFlowFromClientSecret_Step2(saved_state):
    flow = Flow.from_client_secrets_file(
        CLIENT_SECRET,
        scopes=[OAUTH2_SCOPE],
        state=saved_state)
    return flow 
Example #15
Source File: gbcommon.py    From addon-hassiogooglebackup with MIT License 5 votes vote down vote up
def getFlowFromClientSecret():
    flow = InstalledAppFlow.from_client_secrets_file(
        CLIENT_SECRET,
        scopes=[OAUTH2_SCOPE])
    return flow 
Example #16
Source File: yt.py    From Youtube-Comment-Bot with GNU General Public License v3.0 5 votes vote down vote up
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) 
Example #17
Source File: countdown.py    From university-setup with MIT License 5 votes vote down vote up
def authenticate():
    print('Authenticating')
    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
    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.
    if os.path.exists('token.pickle'):
        with open('token.pickle', '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:
            print('Refreshing credentials')
            creds.refresh(Request())
        else:
            print('Need to allow access')
            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.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)
    return service 
Example #18
Source File: authenticate_in_web_application.py    From google-ads-python with Apache License 2.0 5 votes vote down vote up
def main(client_secrets_path, scopes):
    flow = InstalledAppFlow.from_client_secrets_file(
        client_secrets_path, scopes=scopes)

    flow.run_local_server()

    print('Access token: %s' % flow.credentials.token)
    print('Refresh token: %s' % flow.credentials.refresh_token) 
Example #19
Source File: authenticate_in_standalone_application.py    From google-ads-python with Apache License 2.0 5 votes vote down vote up
def main(client_secrets_path, scopes):
    flow = InstalledAppFlow.from_client_secrets_file(
        client_secrets_path, scopes=scopes)

    flow.run_console()

    print('Access token: %s' % flow.credentials.token)
    print('Refresh token: %s' % flow.credentials.refresh_token) 
Example #20
Source File: googlecal.py    From hemppa with GNU General Public License v3.0 5 votes vote down vote up
def matrix_start(self, bot):
        super().matrix_start(bot)
        self.bot = bot
        creds = None

        if not os.path.exists(self.credentials_file) or os.path.getsize(self.credentials_file) == 0:
            return  # No-op if not set up

        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
                self.logger.info('Loaded existing pickle file')
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            self.logger.warn('No credentials or credentials not valid!')
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(self.credentials_file, self.SCOPES)
                # urn:ietf:wg:oauth:2.0:oob
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
                self.logger.info('Pickle saved')

        self.service = build('calendar', 'v3', credentials=creds)

        try:
            calendar_list = self.service.calendarList().list().execute()['items']
            self.logger.info(f'Google calendar set up successfully with access to {len(calendar_list)} calendars:\n')
            for calendar in calendar_list:
                self.logger.info(f"{calendar['summary']} - + {calendar['id']}")
        except Exception:
            self.logger.error('Getting calendar list failed!') 
Example #21
Source File: googlephotos.py    From elodie with Apache License 2.0 5 votes vote down vote up
def set_session(self):
        # Try to load credentials from an auth file.
        # If it doesn't exist or is not valid then catch the 
        #  exception and reauthenticate.
        try:
            creds = Credentials.from_authorized_user_file(self.auth_file, self.scopes)
        except:
            try:
                flow = InstalledAppFlow.from_client_secrets_file(self.secrets_file, self.scopes)
                creds = flow.run_local_server()
                cred_dict = {
                    'token': creds.token,
                    'refresh_token': creds.refresh_token,
                    'id_token': creds.id_token,
                    'scopes': creds.scopes,
                    'token_uri': creds.token_uri,
                    'client_id': creds.client_id,
                    'client_secret': creds.client_secret
                }

                # Store the returned authentication tokens to the auth_file.
                with open(self.auth_file, 'w') as f:
                    f.write(json.dumps(cred_dict))
            except:
                return

        self.session = AuthorizedSession(creds)
        self.session.headers["Content-type"] = "application/octet-stream"
        self.session.headers["X-Goog-Upload-Protocol"] = "raw" 
Example #22
Source File: create_config.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def __init__(self, oauth_client_secrets_path):
    flow = InstalledAppFlow.from_client_secrets_file(
        oauth_client_secrets_path,
        scopes=['https://www.googleapis.com/auth/siteverification'])
    credentials = flow.run_console()

    http = google_auth_httplib2.AuthorizedHttp(
        credentials, http=httplib2.Http())

    self.api = discovery.build('siteVerification', 'v1', http=http) 
Example #23
Source File: youtube_api.py    From GraphiPy with MIT License 5 votes vote down vote up
def get_authenticated_service():
      flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
      credentials = flow.run_console()
      return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) 
Example #24
Source File: GoSyncModel.py    From gosync with GNU General Public License v2.0 4 votes vote down vote up
def DoAuthenticate(self):
        try:
            # If modifying these scopes, delete the file token.pickle.
            SCOPES = ['https://www.googleapis.com/auth/drive']
            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.
            if os.path.exists(self.client_pickle):
                with open(self.client_pickle, 'rb') as token:
                    self.SendlToLog(2, "Authenticate - Loading pickle file")
                    try:
                        creds = pickle.load(token)
                        self.SendlToLog(2, "Authenticate - Loading pickle file: SUCCESS")
                    except:
                        self.SendlToLog(2, "Authenticate - Failed to load pickle file")
                        creds = None

            # 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:
                    self.SendlToLog(2, "Authenticate - expired. Refreshing")
                    creds.refresh(Request())
                else:
                    self.SendlToLog(2, "Authenticate - New authentication")
                    self.SendlToLog(2, "Authenticate - File %s" % (self.credential_file))
                    flow = InstalledAppFlow.from_client_secrets_file(self.credential_file, SCOPES)
                    self.SendlToLog(2, "Authenticate - running local server")
                    creds = flow.run_local_server(port=0)
                self.SendlToLog(2, "Authenticate - Saving pickle file")
                # Save the credentials for the next run
                with open(self.client_pickle, 'wb') as token:
                    pickle.dump(creds, token)

            self.SendlToLog(2, "Authenticate - Building service")
            try:
                service = build('drive', 'v3', credentials=creds)
                self.SendlToLog(2, "Authenticate - service built successfully!")
            except:
                self.SendlToLog(2, "Authenticate - service built failed. Going for re-authentication")
                try:
                    flow = InstalledAppFlow.from_client_secrets_file(self.credential_file, SCOPES)
                    creds = flow.run_local_server(port=0)
                    service = build('drive', 'v3', credentials=creds)
                except:
                    raise AuthenticationFailed()

            self.drive = service
            self.is_logged_in = True
            return service
        except:
            dial = wx.MessageDialog(None, "Authentication Rejected!\n",
                                    'Information', wx.ID_OK | wx.ICON_EXCLAMATION)
            dial.ShowModal()
            self.is_logged_in = False
            pass 
Example #25
Source File: Private.py    From NSC_BUILDER with MIT License 4 votes vote down vote up
def __init__(self,SCOPES=None,token='drive',SCOPES_type='default',headless=True,apiver='v3',json_file=None):
		if SCOPES_type!='default':
			SCOPES=get_scopes(SCOPES_type)	
		if SCOPES!=None:
			if os.path.exists(tk):
				try: 
					os.remove(tk)
				except:pass	
		else:
			SCOPES = ['https://www.googleapis.com/auth/drive']				
		creds = None;json_auth=False		
		tk = os.path.join(credentials_dir, token)	
		alt_json=os.path.join(credentials_dir, (token+".json"))		
		if os.path.exists(alt_json):
			credentials_json=alt_json
		else:	
			credentials_json=os.path.join(credentials_dir, 'credentials.json')			
		if json_file!=None:		
			tk=json_file			
		if os.path.exists(tk):
			try:
				with open(tk) as jfile:						
					test=json.load(jfile)	
				json_auth=True
				apiver='v3'
			except:
				with open(tk, 'rb') as tok:
					creds = pickle.load(tok)							
		# If there are no (valid) credentials available, let the user log in.
		if json_auth==False:		
			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)
					if headless==False:	
						creds = flow.run_local_server(port=0)
					else:
						creds = flow.run_console()
				# Save the credentials for the next run
				with open(tk, 'wb') as tok:
					pickle.dump(creds, tok)
			self.drive_service = build('drive', apiver, credentials=creds)
			self.access_token = creds.token
		else:		
			if os.path.exists(token):				
				creds = ServiceAccountCredentials.from_json_keyfile_name(token, scopes=SCOPES)
			elif os.path.exists(tk):		
				creds = ServiceAccountCredentials.from_json_keyfile_name(tk, scopes=SCOPES)					
			self.drive_service = build('drive', apiver, credentials=creds)
			self.access_token = None 
Example #26
Source File: google_email.py    From trusat-backend with Apache License 2.0 4 votes vote down vote up
def init_history_watch():
    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

    creds = None
    try:
        if os.path.exists('history_token.pickle'):
            with open('history_token.pickle', 'rb') as token:
                creds = pickle.load(token)

        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_console()
            with open('history_token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        request = {
                'labelIds': ['Label_4696745878389955477'],
                'topicName': 'projects/trusat-256517/topics/TruSat'
            }
        service = build('gmail', 'v1', credentials=creds)


        results = service.users().labels().list(userId='me').execute()
        labels = results.get('labels', [])

        if not labels:
            print('No labels found.')
        else:
            print('Labels:')
            for label in labels:
                print(label['name'])
                print(label['id'])


        results = service.users().watch(userId='me', body=request).execute()
        print(results)
        return True
    except Exception as e:
        print(e)
        return False 
Example #27
Source File: download-2.py    From google-drive-folder-downloader with MIT License 4 votes vote down vote up
def main():

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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=1337)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('drive', 'v3', credentials=creds)

    folder_name = ''
    folder_id = ''
    location = ''
    if len(sys.argv) > 2:
        location = unicode(sys.argv[2], 'utf-8')
        if location[-1] != '/':
            location += '/'

    folder = service.files().list(
            q="name contains '{}' and mimeType='application/vnd.google-apps.folder'".format(unicode(sys.argv[1])),
            fields='files(id, name, parents)').execute()

    total = len(folder['files'])
    if total != 1:
        print('{} folders found'.format(total))
        if total == 0:
            sys.exit(1)
        prompt = 'Please select the folder you want to download:\n\n'
        for i in range(total):
            prompt += u'[{}]: {}\n'.format(i, get_full_path(service, folder['files'][i]))
        print prompt
        choice = int(raw_input('Your choice: '))
        if 0 <= choice and choice < total:
            folder_id = folder['files'][choice]['id']
            folder_name = folder['files'][choice]['name']
        else:
            sys.exit(1)
    else:
        folder_id = folder['files'][0]['id']
        folder_name = folder['files'][0]['name']

    print('{} {}'.format(folder_id, folder_name))
    download_folder(service, folder_id, location, unicode(folder_name, 'utf-8')) 
Example #28
Source File: download.py    From google-drive-folder-downloader with MIT License 4 votes vote down vote up
def main():

    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    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=1337)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token, protocol=0)
    service = build('drive', 'v3', credentials=creds)

    folder_name = ''
    folder_id = ''
    location = ''
    if len(sys.argv) > 2:
        location = sys.argv[2]
        if location[-1] != '/':
            location += '/'

    folder = service.files().list(
            q=f"name contains '{sys.argv[1]}' and mimeType='application/vnd.google-apps.folder'",
            fields='files(id, name, parents)').execute()

    total = len(folder['files'])
    if total != 1:
        print(f'{total} folders found')
        if total == 0:
            sys.exit(1)
        prompt = 'Please select the folder you want to download:\n\n'
        for i in range(total):
            prompt += f'[{i}]: {get_full_path(service, folder["files"][i])}\n'
        prompt += '\nYour choice: '
        choice = int(input(prompt))
        if 0 <= choice and choice < total:
            folder_id = folder['files'][choice]['id']
            folder_name = folder['files'][choice]['name']
        else:
            sys.exit(1)
    else:
        folder_id = folder['files'][0]['id']
        folder_name = folder['files'][0]['name']

    print(f'{folder_id} {folder_name}')
    download_folder(service, folder_id, location, folder_name)