-
Notifications
You must be signed in to change notification settings - Fork 0
/
drive_download.py
executable file
·84 lines (64 loc) · 2.38 KB
/
drive_download.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/env python3
# Download unseen files from a folder in Google Drive
import sys
if sys.version_info < (3, 3):
sys.stderr.write("Sorry, requires at least Python 3.3\n")
sys.exit(1)
import argparse
import collections
import os
import pickle
import shlex
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
def read_seen():
global seen
try:
with open(os.path.expanduser('~/.local/share/drive-download/seen.pickle'), 'rb') as f:
seen = pickle.load(f)
except FileNotFoundError:
seen = set()
def save_seen():
global seen
with open(os.path.expanduser('~/.local/share/drive-download/seen.pickle'), 'wb') as f:
pickle.dump(seen, f)
def folder_id(folder_name):
query = "title = '%s'" % folder_name
file1 = drive.ListFile({'q': query}).GetList()[0]
assert file1['mimeType'] == 'application/vnd.google-apps.folder'
return file1['id']
def main():
global seen, drive
parser = argparse.ArgumentParser(
description='Download unseen files from a folder in Google Drive')
parser.add_argument('folder', type=str, help='folder to download from')
args = parser.parse_args()
read_seen()
gauth = GoogleAuth(settings_file=os.path.expanduser('~/.config/drive-download/settings.yaml'))
gauth.CommandLineAuth()
drive = GoogleDrive(gauth)
file_query = "'%s' in parents and trashed=false" % folder_id(args.folder)
file_list = drive.ListFile({'q': file_query}).GetList()
file_names = [f['title'] for f in file_list]
file_names_dupes = [f for f, count in collections.Counter(file_names).items() if count > 1]
if len(file_names_dupes) > 0:
print('Duplicate filenames on Drive!')
for fn in sorted(file_names_dupes):
print(shlex.quote(fn))
sys.exit(1)
for file1 in file_list:
if file1['mimeType'] == 'application/vnd.google-apps.folder':
continue
if file1['id'] in seen: # XXX could update the file if it needs updating
continue
local_filename = file1['title']
print(shlex.quote(local_filename))
if not os.path.exists(local_filename):
file1.GetContentFile(local_filename)
seen.add(file1['id'])
save_seen()
else:
print("{} exists locally!".format(shlex.quote(local_filename)))
sys.exit(2)
main()
# vim:tw=100: