From: Jakub Czajka Date: Tue, 12 Sep 2023 18:13:39 +0000 (+0200) Subject: Add a subprogram for uploading files to the drive. X-Git-Url: https://git.ekhem.eu.org/?a=commitdiff_plain;h=6bc9dd4a5d599f86ac559274d2ad712d02b69853;p=gdrive_knife.git Add a subprogram for uploading files to the drive. --- diff --git a/gdrive_knife.py b/gdrive_knife.py index 0d72528..31192c6 100644 --- a/gdrive_knife.py +++ b/gdrive_knife.py @@ -10,6 +10,7 @@ import tempfile import uuid import zipfile +from apiclient.http import MediaFileUpload from cryptography.fernet import Fernet from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials @@ -116,6 +117,42 @@ def download(args): shutil.move(path_in_tmp, args.output) print(f'Moved to {args.output}.') +def upload(args): + drive = get_drive_client(args.token) + + path = args.name if args.name else args.file + path_in_tmp = get_path_on_drive(path) + + if os.path.isdir(args.file): + archive = shutil.make_archive(base_name=path_in_tmp, format='zip', + root_dir=os.path.dirname(args.file), + base_dir=os.path.basename(args.file)) + os.rename(archive, path_in_tmp) + print(f'Archived {args.file} in {path_in_tmp}.') + else: + os.makedirs(os.path.dirname(path_in_tmp), exist_ok=True) + shutil.copy(args.file, path_in_tmp) + print(f'Copied {args.file} to {path_in_tmp}.') + + with open(path_in_tmp, 'r+b') as f: + token = args.key.encrypt(f.read()) + f.seek(0) + f.write(token) + f.truncate() + print(f'Encrypted {args.file} in {path_in_tmp}.') + + body = { 'name': path_in_tmp, 'originalFilename': path } + media = MediaFileUpload(path_in_tmp, resumable=True) + + maybe_id = get_file_id(drive, path) + if maybe_id: + drive.files().update(fileId=maybe_id, body=body, + media_body=media).execute() + print(f'Updated {path} on drive.') + else: + drive.files().create(body=body, media_body=media).execute() + print(f'Created {path} on drive.') + if __name__ == '__main__': parser = argparse.ArgumentParser(prog='gdrive_knife', description='Swiss ' 'army knife for working with Google Drive.') @@ -149,6 +186,19 @@ if __name__ == '__main__': 'authentication token.') download_parser.set_defaults(func=download) + upload_parser = subparsers.add_parser('upload', help='Upload a file. ' + 'Override if the file already exists.') + upload_parser.add_argument('file', help='File to upload.') + upload_parser.add_argument('name', help='Name of the file on the drive.', + nargs='?') + upload_parser.add_argument('-k', dest='key', required=True, + type=lambda x : fernet_key(parser, x), help='File with the ' + 'decryption key.') + upload_parser.add_argument('-t', dest='token', required=True, + type=lambda x : file_path(parser, x), help='File with the ' + 'authentication token.') + upload_parser.set_defaults(func=upload) + args = parser.parse_args() args.func(args)