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