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',
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):
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.')
'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)