-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadropicka.py
More file actions
461 lines (324 loc) · 13.9 KB
/
adropicka.py
File metadata and controls
461 lines (324 loc) · 13.9 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/env python3
#
# Adropicka - a very basic one-file-per-run console client-wrapper for DropBox
# Copyright (c) 2017 Sunkware
# Key FP = 6B6D C8E9 3438 6E9C 3D97 56E5 2CE9 A476 99EF 28F6
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ----------------------------------------------------------------
# WWW: sunkware.org
# E-mail: sunkware@gmail.com
# ----------------------------------------------------------------
#
import os
import optparse
import dropbox
APP_ROOT_KEY = "aocd70ng4f8xfjw"
APP_ROOT_SECRET = "quymsslrmgeqtv4"
APP_DIR_KEY = "w1bbm86307efcwb"
APP_DIR_SECRET = "r03i2ayet4yr1sm"
UPLOAD_CHUNK_SIZE = 16777216 # 16 Mb
UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE = 33554432 # 32 Mb (DropBox API mentions 150 (March 2016))
def main():
global APP_ROOT_KEY
global APP_ROOT_SECRET
global APP_DIR_KEY
global APP_DIR_SECRET
global UPLOAD_CHUNK_SIZE
global UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE
print("Adropicka v0.94")
op = optparse.OptionParser()
op.add_option("--authorize-root", action = "store_true", default = False, dest = "authorize_root", help = "Authorize the application for root access")
op.add_option("--authorize-dir", action = "store_true", default = False, dest = "authorize_dir", help = "Authorize the application for folder access")
op.add_option("-l", "--list", action = "store_true", default = False, dest = "enlist", help = "List content of folder")
op.add_option("-m", "--makedir", action = "store_true", default = False, dest = "makedir", help = "Create folder")
op.add_option("-u", "--upload", action = "store_true", default = False, dest = "upload", help = "Upload file")
op.add_option("-d", "--download", action = "store_true", default = False, dest = "download", help = "Download file")
op.add_option("-r", "--remove", action = "store_true", default = False, dest = "remove", help = "Remove file or folder")
op.add_option("-t", "--tokenpath", action = "store", default = "adropicka_token.txt", dest = "tokenpath", help = "Path to the text file with an access token")
op.add_option("-c", "--chunksize", action = "store", default = UPLOAD_CHUNK_SIZE, dest = "chunksize", help = "Size of upload chunk in bytes")
op.add_option("-s", "--singlemaxsize", action = "store", default = UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE, dest = "singlemaxsize", help = "Max size of file to be uploaded as a single data block")
opts, args = op.parse_args()
authorize_root = opts.authorize_root;
authorize_dir = opts.authorize_dir;
enlist = opts.enlist
makedir = opts.makedir
upload = opts.upload
download = opts.download
remove = opts.remove
actionsnum = int(authorize_root) + int(authorize_dir) + int(enlist) + int(makedir) + int(upload) + int(download) + int(remove)
if actionsnum == 0:
print("No action is specified! Run with --help or -h to get to know the syntax.")
return -1
if actionsnum > 1:
print("More than one action is specified!")
return -2
# Process authorizing (before checking for token)...
if authorize_root or authorize_dir:
# Taken from SDK/dropbox/oauth...
if authorize_root:
auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_ROOT_KEY, APP_ROOT_SECRET)
else:
auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_DIR_KEY, APP_DIR_SECRET)
authorize_url = auth_flow.start()
print("1. In your browser, go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
try:
access_token, user_id = auth_flow.finish(auth_code)
except Exception as e:
print("Error: %s" % (e,))
return -3
print("Access token obtained.")
try:
file = open(opts.tokenpath, "wt")
except IOError as err:
print("Cannot create token file " + "\"" + opts.tokenpath + "\"!")
print(err)
return -4
file.write(access_token)
file.close()
print("Token saved in " + "\"" + opts.tokenpath + "\".")
# Reading access token
tokenpath = opts.tokenpath
try:
tokenfile = open(tokenpath, "rt")
except IOError as err:
print("Cannot open token file " + "\"" + tokenpath + "\"!")
print(err)
print("If you haven't got a token yet, run with --authorize-dir or --authorize-root option.")
return -5
token = tokenfile.readline()
tokenfile.close()
if opts.chunksize > 0:
UPLOAD_CHUNK_SIZE = opts.chunksize
if opts.singlemaxsize > 0:
UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE = opts.singlemaxsize
dbx = dropbox.Dropbox(token)
if dbx is None:
print("Client hasn't been initialized!")
return -6
print("Client initialized.")
# Process list operation
if enlist:
if len(args) != 1:
print("Remote dir path must be specified!")
return -7
dirpath = args[0]
if not dirpath.startswith("/"):
dirpath = "/" + dirpath
if dirpath.endswith("/"):
dirpath = dirpath[0:len(dirpath) - 1] # particularly, root path should be represented by empty string
print("Listing content of " + "\"" + dirpath + "\"...")
try:
folder_res = dbx.files_list_folder(dirpath)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -8
entries_num = len(folder_res.entries)
for i in range(0, entries_num):
print(make_folder_entry_string(folder_res.entries[i]))
while folder_res.has_more:
try:
folder_res = dbx.files_list_folder_continue(folder_res.cursor)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -9
entries_num = len(folder_res.entries)
for i in range(0, entries_num):
print(make_folder_entry_string(folder_res.entries[i]))
# Process makedir operation
if makedir:
if len(args) != 1:
print("Remote dir path must be specified!")
return -10
dirpath = args[0]
if not dirpath.startswith("/"):
dirpath = "/" + dirpath
if dirpath.endswith("/"):
dirpath = dirpath[0:len(dirpath) - 1]
print("Creating " + "\"" + dirpath + "\" folder...")
folder_exists = False
try:
folder_res = dbx.files_create_folder(dirpath)
except dropbox.exceptions.ApiError as err:
# If the folder exists, don't interrupt with error (goal of making is attained already)
# Other API error-s are processed as usual
# Unwinding error stack...
if isinstance(err.error, dropbox.files.CreateFolderError):
if err.error.is_path():
if err.error.get_path().is_conflict():
if err.error.get_path().get_conflict().is_folder():
folder_exists = True
if not folder_exists:
print("API error!")
print(err)
return -11
if folder_exists:
print("Folder exists already.")
else:
print("Created folder")
# Process upload operation
if upload:
if len(args) != 2:
print("Local file path and remote dir path must be specified!")
return -12
srcfilepath = args[0]
destpath = args[1]
basename = os.path.basename(srcfilepath)
destfilepath = destpath;
if not destfilepath.startswith("/"):
destfilepath = "/" + destfilepath
if not destfilepath.endswith("/"):
destfilepath += "/"
destfilepath += basename
print("Uploading " + "\"" + basename + "\"...")
ub = upload_to_file(dbx, destfilepath, srcfilepath) # breaking file content into chunks if needed
if ub < 0:
print("Upload error!")
return -13
print("Uploaded " + "\"" + basename + "\"" + " (" + str(ub) + " bytes)")
# Process download operation
if download:
if len(args) != 2:
print("Remote file path and local dir path must be specified!")
return -14
srcfilepath = args[0]
if not srcfilepath.startswith("/"):
srcfilepath = "/" + srcfilepath
destpath = args[1]
basename = os.path.basename(srcfilepath)
destfilepath = destpath;
if not destpath.endswith("/"):
destfilepath += "/"
destfilepath += basename
print("Downloading " + "\"" + basename + "\"...")
try:
res = dbx.files_download_to_file(destfilepath, srcfilepath)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -15
print("Downloaded " + "\"" + basename + "\"" + " (" + str(res.size) + " bytes)")
# Process remove operation
if remove:
if len(args) != 1:
print("Remote file (or folder) path must be specified!")
return -16
filepath = args[0]
if not filepath.startswith("/"):
filepath = "/" + filepath
basename = os.path.basename(filepath)
print("Removing " + "\"" + basename + "\"...")
obj_not_found = False
try:
res = dbx.files_delete(filepath)
except dropbox.exceptions.ApiError as err:
# If file not found, show message but don't interrupt with error (goal of removal is attained already)
# Other ApiError-s are processed as usual
# Unwinding error stack...
if isinstance(err.error, dropbox.files.DeleteError):
if err.error.is_path_lookup():
if err.error.get_path_lookup().is_not_found():
obj_not_found = True
if not obj_not_found:
print("API error!")
print(err)
return -17
if obj_not_found:
print("File or folder not found, considered to be removed.")
else:
if hasattr(res, "size"):
print("Removed " + "\"" + basename + "\"" + " (" + str(res.size) + " bytes)")
else:
print("Removed " + "[" + basename + "]" + " folder")
return 0
def upload_to_file(dropbox_client, destfilepath, srcfilepath):
global UPLOAD_CHUNK_SIZE
global UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE
try:
file = open(srcfilepath, 'rb')
except IOError as err:
print("Cannot open file " + "\"" + basename + "\"" + "!")
print(err)
return -1
fsize = filesize(file)
if fsize <= UPLOAD_MAX_SINGLE_CHUNK_FILE_SIZE: # upload without chunks and session
data = file.read()
try:
res = dropbox_client.files_upload(data, destfilepath, dropbox.files.WriteMode.overwrite)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -2
file.close()
return fsize
# else --- start session, append to it, then finish...
fullchunks = fsize // UPLOAD_CHUNK_SIZE
lastchunksize = fsize % UPLOAD_CHUNK_SIZE
offset = 0
# upload 0 bytes to start session
data = file.read(0)
try:
session_start_res = dropbox_client.files_upload_session_start(data)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -3
offset += len(data)
# Appending full chunks...
for i in range(0, fullchunks):
data = file.read(UPLOAD_CHUNK_SIZE)
try:
dropbox_client.files_upload_session_append(data, session_start_res.session_id, offset)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -4
offset += len(data)
# Finishing session with the last chunk...
data = file.read(lastchunksize)
cursor = dropbox.files.UploadSessionCursor(session_start_res.session_id, offset)
commit = dropbox.files.CommitInfo(destfilepath, dropbox.files.WriteMode.overwrite)
try:
dropbox_client.files_upload_session_finish(data, cursor, commit)
except dropbox.exceptions.ApiError as err:
print("API error!")
print(err)
return -5
file.close()
return fsize
def filesize(f):
if f is not None:
curpos = f.tell()
size = f.seek(0, 2)
f.seek(curpos, 0)
return size
return -1
def make_folder_entry_string(en):
res = ""
if en is not None:
if isinstance(en, dropbox.files.FileMetadata):
res = "\"" + en.name + "\"" + " (" + str(en.size) + " B)"
elif isinstance(en, dropbox.files.FolderMetadata):
res = "[" + en.name + "]"
else:
res = "???"
return res
if __name__ == "__main__":
main()