# License: GPL-3.0 or later.
import argparse
+import os.path
+
+from google.auth.transport.requests import Request
+from google.oauth2.credentials import Credentials
+from google_auth_oauthlib.flow import InstalledAppFlow
+
+SCOPES = ['https://www.googleapis.com/auth/drive.metadata',
+ 'https://www.googleapis.com/auth/drive',
+ 'https://www.googleapis.com/auth/drive.file']
+
+def file_path(parser, path):
+ if not os.path.isfile(path):
+ return parser.error(f'{path} does not exist!')
+ return path
+
+def auth(args):
+ creds = None
+ if os.path.exists(args.token):
+ print(f'{args.token} exists. Trying to authenticate with it.')
+ creds = Credentials.from_authorized_user_file(args.token, SCOPES)
+ if not creds or not creds.valid:
+ if creds and creds.expired and creds.refresh_token:
+ print(f'{args.token} has expired. Refreshing.')
+ creds.refresh(Request())
+ else:
+ print(f'{args.token} does not exist. Obtaining a new token.')
+ flow = InstalledAppFlow.from_client_secrets_file(args.credentials,
+ SCOPES)
+ creds = flow.run_local_server(port=0)
+ print(f'Writing new token to {args.token}.')
+ with open(args.token, 'w') as token:
+ token.write(creds.to_json())
+ print('Authentication successful.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='gdrive_knife', description='Swiss '
'army knife for working with Google Drive.')
+
+ subparsers = parser.add_subparsers()
+
+ auth_parser = subparsers.add_parser('auth', help='Authenticate and obtain a '
+ 'token.')
+ auth_parser.add_argument('-c', dest='credentials', required=True,
+ type=lambda x : file_path(parser, x), help='File with credentials.')
+ auth_parser.add_argument('-t', dest='token', default='token.json',
+ required=True, help='Path where the authentication token should be '
+ 'saved.')
+ auth_parser.set_defaults(func=auth)
+
+ args = parser.parse_args()
+
+ args.func(args)