]> git.ekhem.eu.org Git - gdrive_knife.git/commitdiff
Add a subprogram for listing file on the drive.
authorJakub Czajka <jakub@ekhem.eu.org>
Tue, 12 Sep 2023 18:06:43 +0000 (20:06 +0200)
committerJakub Czajka <jakub@ekhem.eu.org>
Sun, 19 Nov 2023 12:28:36 +0000 (13:28 +0100)
gdrive_knife.py
requirements.txt

index 1172c8a6512d12f8f1f48cc9d95a0bcff18db3d2..9543ab995adfed41809c00ed09f9851886862cef 100644 (file)
@@ -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)
index 8b3b6a3856c9ae6d1b607352bf6c29ce345c9cc4..67480dbd1d6be6636f58813b78ae79dd797a6ed7 100644 (file)
@@ -1,2 +1,3 @@
+google-api-python-client==2.84.0
 google-auth-httplib2==0.1.0
 google-auth-oauthlib==1.0.0