From: Jakub Czajka Date: Tue, 12 Sep 2023 18:06:43 +0000 (+0200) Subject: Add a subprogram for listing file on the drive. X-Git-Url: https://git.ekhem.eu.org/?a=commitdiff_plain;h=aab00c1466e7b5bbd22d50ff480e592c7b62eb8e;p=gdrive_knife.git Add a subprogram for listing file on the drive. --- diff --git a/gdrive_knife.py b/gdrive_knife.py index 1172c8a..9543ab9 100644 --- a/gdrive_knife.py +++ b/gdrive_knife.py @@ -3,10 +3,12 @@ import argparse import os.path +import sys 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 SCOPES = ['https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive', @@ -17,6 +19,15 @@ def file_path(parser, path): return parser.error(f'{path} does not exist!') return path +def get_drive_client(authentication_token): + creds = Credentials.from_authorized_user_file(authentication_token, SCOPES) + if not creds or not creds.valid: + print(f'{authentication_token} is not valid. Use `auth` to obtain a new ' + 'one.') + sys.exit(1) + + return build('drive', 'v3', credentials=creds) + def auth(args): creds = None if os.path.exists(args.token): @@ -36,6 +47,15 @@ def auth(args): token.write(creds.to_json()) print('Authentication successful.') +def list(args): + drive = get_drive_client(args.token) + + files_on_drive = drive.files().list(q='trashed=false', + fields='files(id, originalFilename)').execute() + + for file_on_drive in files_on_drive['files']: + print(file_on_drive['originalFilename']) + if __name__ == '__main__': parser = argparse.ArgumentParser(prog='gdrive_knife', description='Swiss ' 'army knife for working with Google Drive.') @@ -51,6 +71,12 @@ if __name__ == '__main__': 'saved.') auth_parser.set_defaults(func=auth) + list_parser = subparsers.add_parser('list', help='List files.') + list_parser.add_argument('-t', dest='token', required=True, + type=lambda x : file_path(parser, x), help='File with the ' + 'authentication token.') + list_parser.set_defaults(func=list) + args = parser.parse_args() args.func(args) diff --git a/requirements.txt b/requirements.txt index 8b3b6a3..67480db 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ +google-api-python-client==2.84.0 google-auth-httplib2==0.1.0 google-auth-oauthlib==1.0.0