-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository-download.py
executable file
·743 lines (591 loc) · 28.1 KB
/
repository-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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#!/usr/bin/env python3
# Copyright 2018-2019 SURFsara B.V.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, os, getopt, time
class Config:
DEBUG = False
DEBUG_COLORS = True
VERBOSE = False
QUIET = False
def message(msg, mtype=None, color=37, showstack=False, out=sys.stdout, addNewLine=True):
''' Print message'''
if (mtype == 'debug' and not Config.DEBUG) \
or (mtype == 'verbose' and not Config.VERBOSE) \
or Config.QUIET:
return
if Config.DEBUG and Config.DEBUG_COLORS:
out.write("\x1b[%sm" % color)
if Config.DEBUG:
frames = inspect.stack()
try:
out.write('%% %s():%d: ' % (frames[2][3], frames[2][2]))
finally:
# this breaks reference cycles in Python interpreter
del frames
elif mtype is not None:
out.write("%s: " % mtype)
if Config.DEBUG_COLORS:
out.write('\x1b[0m')
out.write("%s" % msg)
if addNewLine:
out.write("\n")
def error(msg, exitCode=None):
message("%s" % msg, 'error', 31, True, out=sys.stderr)
if not exitCode is None:
sys.exit(exitCode)
def debug(msg):
message(msg, 'debug', color=32)
def note(msg):
message(msg, 'note', color=36)
def verbose(msg):
message(msg, 'verbose', color=33)
def warning(msg):
message(msg, 'warning', color=31)
try:
import signal, requests, inspect, copy, cchardet, re, math, simplejson, subprocess, timeit
except ModuleNotFoundError as e:
error("%s found, please install the module by running the command: pip install %s" % (e, str(e).split(' ')[-1].strip('\'')), 1)
SERVICE = "SURF Data Repository"
TITLE = SERVICE + " download tool"
VERSION = "1.0.1"
TDR_API = 'api'
TDR_API_OBJECTS = 'api/objects/%s'
TDR_API_STATUS = 'api/objects/%s/%s/status'
TDR_API_STAGE = 'api/objects/%s/%s/stage'
TDR_API_STAGE_FILE = 'api/objects/%s/%s/stage/%s'
VALID_SOURCES = ['basket', 'favourites']
STATUS_ONLINE = ['REG', 'DUL']
STATUS_OFFLINE = ['OFL', 'MIG']
STATUS_STAGING = ['UNM']
def bytesize(size):
p = int(math.floor(math.log(abs(size), 10) / 3)) if abs(size) else 0
return ("%%%s %%s" % (".1f" if p else "d")) % (size / math.pow(1000, p), ['B','KB','MB','GB','TB','PB','EB'][p])
class FileStatus:
UNKNOWN = 0
STAGE = 1
STAGING = 2
DOWNLOAD = 3
DOWNLOADING = 4
CHECKSUM = 5
CHECKSUMMING = 6
FINISHED = 7
SKIP = 254
ERROR = 255
class FileObject(object):
def __init__(self, container, fileObject, status=FileStatus.UNKNOWN):
self.container = container
self.object = fileObject
self.status = status
class DownloadManager(object):
def __init__(self, token=None, options={}):
self.setToken(token)
self.setOptions(options)
self.objects = None
self.processed = []
self.cache = {}
self.files = {}
self.request = None
self.rdata = ""
self.stageObjects = {}
self.statusObjects = {}
self.reset()
requests.packages.urllib3.disable_warnings()
def reset(self):
self.cache = {}
self.report = {
'total-download-size': 0,
'bytes-downloaded': 0
}
def setToken(self, token):
self.token = token
if not token is None:
debug("token: " + token)
def setOutputDir(self, directory):
path = "%s/%s" % (os.getcwd(), directory)
if not os.path.exists(path):
note("path created: %s" % path)
os.mkdir(path)
self.options.update({'outputdir': directory})
def setOptions(self, options):
self.options = options
for k, v in options.items():
try:
index = map(str.lower, dir(self)).index(("set%s" % k).lower())
method = getattr(self, dir(self)[index])
method(v)
except Exception as e:
self.options.update({k: v})
debug("target: %s" % self.options['target'])
def downloadObjectList(self):
if self.options['source'] not in VALID_SOURCES:
error("invalid source '%s'" % self.options['source'])
message("Downloading your %s from %s" % (self.options['source'], self.options['target']))
data = self._requestAuthenticated('GET', "%s/%s" % (TDR_API, self.options['source']))
self.objects = data['result']
verbose(self.objects)
def _requestStatus(self, pid, fileID = None):
pids = pid.split(':')
url = TDR_API_STATUS % (pids[0], pids[1])
if fileID:
url += "/%s" % fileID
return self._requestAuthenticated('GET', url)
def _requestStage(self, pid, fileID = None):
pids = pid.split(':')
url = TDR_API_STAGE % (pids[0], pids[1])
if fileID:
url += "/%s" % fileID
return self._requestAuthenticated('POST', url)
def _requestAuthenticated(self, method, endpoint, headers={}, params={}):
params['token'] = self.token
return self._request(endpoint, headers, params, method=method)
def _request(self, uri, headers={}, params={}, method='GET'):
url = "%s/%s" % (self.options['target'], uri) if self.options['target'] not in uri else uri
try:
self.request = requests.request(method, url, headers=headers, params=params, verify=not self.options['no-verify'], timeout=self.options['request-timeout'])
except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout) as e:
error("request time out after %d seconds" % self.options['request-timeout'], 2)
except requests.exceptions.SSLError as e:
error(e, 2)
debug("%s %s" % (method, self.request.url))
if self.request is None:
error('internal request failed', 3)
# determine the encoding of the response text
if self.request.encoding is None:
self.request.encoding = cchardet.detect(self.request.content)['encoding']
verbose("%s %s" % (self.request.status_code, self.request.text))
if 'content-type' in self.request.headers:
ct = re.search('([a-z]+\/[a-z]+)', self.request.headers['content-type'], re.I)
if ct.group(1) in ['application/json', 'text/json']:
try:
self.rdata = self.request.json() if self.request.text > "" else {}
except simplejson.errors.JSONDecodeError as e:
error("internal JSON decode error: %s" % e.message, 2)
else:
self.rdata = self.request.text
if self.request.status_code == 200:
return self.rdata
elif self.request.status_code in [401, 403]:
error("could not authenticate using token '%s'" % params['token'], 2)
elif self.request.status_code >= 300:
error("request failed: %s %s" % (self.request.status_code, self.request.reason), 2)
elif self.rdata is dict and "error" in self.rdata:
error(self.rdata["error"])
else:
return None
def processObjectList(self):
if not self.objects:
error("%s is empty" % self.options['source'], 1)
for b in self.objects:
pid = b['object']
self._processObject(pid, b.get('deposit', None), b.get('fileID', None))
def _processObject(self, pid, deposit=None, fileID=None):
if pid in self.cache:
debug("in cache: %s" % pid)
objectInfo = self.cache[pid]
else:
message("Processing %s" % pid)
data = self._request(TDR_API_OBJECTS % pid.replace(':', '/'))
if data is None:
return False
objectInfo = data['result']
if pid not in self.cache:
self.cache[pid] = copy.copy(objectInfo)
if objectInfo['type'] in ['collection', 'deposit']:
if objectInfo['type'] == 'collection':
# process collections, limit if optioned
objects = objectInfo['collections'][:self.options['max-childs']] if self.options['max-childs'] > 0 else objectInfo['collections']
for c in objects:
if deposit and c['pid'] != deposit:
continue
self._processObject(c, deposit)
# process deposits, limit if optioned
objects = objectInfo['deposits'][:self.options['max-childs']] if self.options['max-childs'] > 0 else objectInfo['deposits']
for d in objects:
if deposit and d['pid'] != deposit:
continue
self._processObject(d, deposit)
elif objectInfo['type'] == 'deposit':
# process deposits, limit if optioned
objects = objectInfo['files'][:self.options['max-files']] if self.options['max-files'] > 0 else objectInfo['files']
for f in objects:
if fileID and f['id'] != fileID:
continue
if f['status'] in STATUS_OFFLINE:
f['dstatus'] = FileStatus.STAGE if not self.options['skip-staging'] else FileStatus.SKIP
else:
f['dstatus'] = FileStatus.DOWNLOAD if not self.options['skip-download'] else FileStatus.SKIP
f['parent'] = pid
self.files[f['url']] = f
else:
message("Skipping %s" % pid)
return True
# report before processes are initiated
def preReport(self):
counts = {}
for f in self.files.values():
if not f['parent'] in counts:
counts[f['parent']] = 0
counts[f['parent']] += 1
self.report['total-download-size'] = sum(int(i['size']) for _,i in self.files.items())
message("Total download size: %s in %d files (%d objects)" % (bytesize(self.report['total-download-size']), len(self.files.values()), len(counts)))
# report after processes are completed
def postReport(self):
if not self.files:
return
finished = filter(lambda x: x['dstatus'] == FileStatus.FINISHED, self.files.values())
counts = {}
for f in finished:
if not f['parent'] in counts:
counts[f['parent']] = 0
counts[f['parent']] += 1
# report if any objects
if counts:
message("Finished (%d objects, %d files): %s" % (len(counts), sum(i for _,i in counts.items()), ", ".join(map(lambda x: "%s (%s)" % x, counts.items()))))
else:
message("None of objects finished")
errors = filter(lambda x: x['dstatus'] == FileStatus.ERROR, self.files.values())
counts = {}
for f in errors:
if not f['parent'] in counts:
counts[f['parent']] = 0
counts[f['parent']] += 1
# report if any errors
if counts:
message("Errors (%d objects, %d files): %s" % (len(counts), sum(i for _,i in counts.items()), ", ".join(map(lambda x: "%s (%s)" % x, counts.items()))))
else:
message("No errors")
# initiate download and stage processes
def startProcesses(self):
if not self.files:
note("there are no files to be processed")
return True
while len([*filter(lambda x: not x['dstatus'] in [FileStatus.FINISHED, FileStatus.ERROR, FileStatus.SKIP], self.files.values())]) > 0:
if len([*filter(lambda x: x['dstatus'] in [FileStatus.STAGE], self.files.values())]) > 0:
self._processStaging()
if len([*filter(lambda x: x['dstatus'] in [FileStatus.STAGING, FileStatus.DOWNLOAD], self.files.values())]) > 0:
self._processDownloads()
if len([*filter(lambda x: x['dstatus'] in [FileStatus.CHECKSUM], self.files.values())]) > 0:
self._processChecksums()
time.sleep(0.5)
# process all files and objects to be staged
def _processStaging(self):
for f in self.files.values():
if f['dstatus'] == FileStatus.STAGE:
# check if deposit has already been staged recently
if not 'stage_request' in f:
self._stageDepositFile(f)
# if not self._processStageRequest(f):
# f['dstatus'] = FileStatus.ERROR
return True
def _processStageRequest(self, fileObject):
# if no status has been found
if not 'stage_request' in fileObject or not fileObject['stage_request']['result']:
return False
# check when last attempt was made
if time.time() - fileObject['stage_request']['updated'] <= self.options['stage-interval']:
return True
debug(' Check stage request for file %s %s' % (fileObject['name'], fileObject['stage_request']['result']['code']))
# check stage result, if successful set to staging
if fileObject['stage_request']['result']['code'] == 200:
fileObject['dstatus'] = FileStatus.STAGING
return True
def _processStatusCheck(self, fileObject):
# if no status has been found
if not 'status_request' in fileObject or not fileObject['status_request']['result']:
return False
debug(' Check status for file %s' % fileObject['name'])
if fileObject['status_request']['result']['code'] == 200:
if fileObject['status_request']['result']['result'] in STATUS_ONLINE:
fileObject['dstatus'] = FileStatus.DOWNLOAD
# remove current status result
del fileObject['status_request']
return True
def _processDownloads(self):
for (i, f) in enumerate(self.files.values()):
if f['dstatus'] == FileStatus.STAGING:
# check if deposit has already been checked for status recently
if not 'status_request' in f:
self._statusDepositFile(f)
elif 'updated' in f['status_request'] and time.time() - f['status_request']['updated'] <= self.options['status-interval']:
continue
# check if status has changed
if not self._processStatusCheck(f):
f['dstatus'] = FileStatus.ERROR
elif f['dstatus'] == FileStatus.DOWNLOAD:
if self._downloadFile(f):
f['dstatus'] = FileStatus.CHECKSUM if not self.options['skip-checksum'] else FileStatus.FINISHED
else:
f['dstatus'] = FileStatus.ERROR
return True
def _processChecksums(self):
for (i, f) in enumerate(self.files.values()):
if f['dstatus'] == FileStatus.CHECKSUM:
if self._checksumFile(f):
f['dstatus'] = FileStatus.FINISHED
else:
f['dstatus'] = FileStatus.ERROR
return True
def _stageDeposit(self, pid):
if len(self.stageObjects) >= self.options['stage-max-count']:
debug('maximum number of stage requests exceeded')
return False
message('Staging object %s' % pid)
success = self._requestStage(pid)
# add to stage cache
self.stageObjects.update({pid: {'updated': time.time(), 'result': None}})
if not success:
error('staging of object %s failed (%s): %s' % (pid, self.request.status_code, self.rdata['error']))
return False
self.stageObjects[pid]['result'] = self.rdata
return True
def _stageDepositFile(self, fileObject):
message("Staging file '%s' of object %s" % (fileObject['name'], fileObject['parent']))
success = self._requestStage(fileObject['parent'], fileObject['id'])
# add to stage cache
fileObject['stage_request'] = {'updated': time.time(), 'result': None}
if not success:
error('object staging of %s failed (%s): %s' % (fileObject['parent'], self.request.status_code, self.rdata['error']))
return False
fileObject['stage_request']['result'] = self.rdata
return True
def _statusDeposit(self, pid):
message('Status %s' % pid)
success = self._requestStatus(pid)
# add to status cache
self.statusObjects.update({pid: {'updated': time.time(), 'result': None}})
if not success:
error('object status of %s failed (%s): %s' % (pid, self.request.status_code, self.rdata['error']))
return False
self.statusObjects[pid]['result'] = self.rdata
return True
def _statusDepositFile(self, fileObject):
message("Status file '%s' of object %s" % (fileObject['name'], fileObject['parent']))
success = self._requestStatus(fileObject['parent'], fileObject['id'])
# add to status cache
fileObject['status_request'] = {'updated': time.time(), 'result': None}
if not success:
error('object status of %s failed (%s): %s' % (fileObject['parent'], self.request.status_code, self.rdata['error']))
return False
fileObject['status_request']['result'] = self.rdata
return True
# download a file and compare the checksum
# if the target file exists, compare size and checksum
def _downloadFile(self, fileObject):
# define the target output dir
targetdir = "%s/%s" % (self.options['outputdir'], fileObject['parent'].replace(':', '/'))
fileObject['target'] = "%s/%s" % (targetdir, fileObject['name'])
headers = {}
mode = 'wb'
localfilesize = 0
# check if file is present
if not self.options['force-overwrite'] and os.path.exists(fileObject['target']):
# compare size, if equal return
localfilesize = os.path.getsize(fileObject['target'])
# add to reported total download size
self.report['bytes-downloaded'] += localfilesize
if localfilesize == int(fileObject['size']):
message("File '%s' of object %s already downloaded" % (fileObject['name'], fileObject['parent']))
return True
elif not self.options['no-resume'] and localfilesize > 0:
debug("Resuming download of file '%s' of object %s at byte offset %d" % (fileObject['name'], fileObject['parent'], localfilesize))
headers.update({'Range': "bytes=%d-" % localfilesize})
mode = 'a+b'
# request streaming data
try:
self.request = requests.get(fileObject['url'], headers=headers, params={'token': self.token}, stream=True, verify=not self.options['no-verify'])
except Exception as e:
error(e)
if self.request.status_code not in [200, 206]:
error("download of file '%s' failed: %s" % (fileObject['name'], self.request.reason))
return False
debug("%s %s" % (self.request.request.method, self.request.url))
# get file size
filesize = int(self.request.headers.get('content-length')) if 'content-length' in self.request.headers else 1
totsize = localfilesize
downsize = 0
# create the output dir
try:
if not os.path.exists(targetdir):
os.makedirs(targetdir)
except OSError as e:
error(e, 101)
# download the file in chunks (append if resuming)
try:
with open(fileObject['target'], mode) as fout:
fout.seek(localfilesize, os.SEEK_SET)
start = timeit.default_timer()
for chunk in self.request.iter_content(chunk_size=self.options['buffer-size']):
if chunk:
size = len(chunk)
downsize += size
totsize += size
fout.write(chunk)
# print progress
percentage = totsize * 100. / int(fileObject['size'])
self.report['bytes-downloaded'] += size
progress = "(%d%% of %s, %s/s, %d%% of %s)" % (percentage, bytesize(int(fileObject['size'])), bytesize(int(size / (timeit.default_timer() - start))), (self.report['bytes-downloaded'] * 100. / int(self.report['total-download-size'])), bytesize(self.report['total-download-size'])) if filesize else ""
if totsize == filesize or (self.options['test'] and percentage > 1):
message("\rFile '%s' of object %s downloaded %s" % (fileObject['name'], fileObject['parent'], progress))
break
else:
message("\rDownloading file '%s' of object %s %s" % (fileObject['name'], fileObject['parent'], progress), addNewLine=False)
sys.stdout.flush()
start = timeit.default_timer()
except Exception as e:
error(e, 3)
return True
# check the checksum of a downloaded file
def _checksumFile(self, fileObject):
text = "Comparing local checksum of file '%s' of object %s" % (fileObject['name'], fileObject['parent'])
message(text, addNewLine=False)
# calculate the local checksum
try:
output = subprocess.check_output("md5sum %s | awk '{print $1}'" % (fileObject['target']), shell=True).strip().decode()
except subprocess.CalledProcessError as e:
error(e, 102)
# locate checksum
if 'md5' in fileObject:
checksum = fileObject['md5']
elif 'checksum' in fileObject:
checksum = fileObject['checksum']
else:
message("\nwarning: no checksum found for file '%s' in object %s" % (fileObject['name'], fileObject['parent']))
return False
# compare with retrieved checksum
if output == checksum:
message("\r" + text + " PASS")
else:
message("\n FAIL (%s (local) vs %s (remote))" % (output, checksum))
# store checksum if requested
if self.options['store-checksum']:
with open("%s.md5" % fileObject['target'], 'w') as f:
f.write(output)
f.close()
return output == fileObject['md5']
def signalHandler(signal, frame):
error('execution interrupted', 1)
def bools(b):
return "yes" if b else "no"
def allorn(d):
return "all" if not d else str(d)
def usage():
print("usage: %s [options] token" % sys.argv[0])
def help(options):
""" Show usage information """
print("%s v%s: massively download collections, deposits and individual files from the %s\n" % (TITLE, VERSION, SERVICE))
usage()
print("\nwhere token is your personal API access token. If you do not have an API token yet, create one on the %s website." % SERVICE)
print("\nOptions:")
print("--target -t set the target instance of %s (default: '%s')" % (SERVICE, options['target']))
print("--source specify source (default: %s)" % options['source'])
print("--output -o set target download directory (default: '%s')" % options['outputdir'])
print("--buffer-size -b set download buffer size (bytes, default: %d)" % options['buffer-size'])
print("--force-overwrite force overwrite of existing files (default: %s)" % bools(options['force-overwrite']))
print("--skip-staging skip staging of objects (default: %s)" % bools(options['skip-staging']))
print("--skip-download skip downloading of files (default: %s)" % bools(options['skip-download']))
print("--skip-checksum skip checksum check after download (default: %s)" % bools(options['skip-checksum']))
print("--no-resume do not resume partially downloaded files, redownload instead (default: %s)" % bools(options['no-resume']))
print("--store-checksum store generated checksum after download (default: %s)" % bools(options['store-checksum']))
print("--max-childs -m maximum number of childs to process per collection (default: %s)" % allorn(options['max-childs']))
print("--max-files maximum number of files to download per deposit (default: %s)" % allorn(options['max-files']))
print("--no-verify -k do not verify server certificate (default: %s)" % bools(options['no-verify']))
print("--debug -d set debuglevel to max (default: %s)" % bools(Config.DEBUG))
print("--test test mode, limits data downloads (default: %s)" % bools(options['test']))
print("--dry-run -n dry-run mode, simulate staging, downloads and further processing (default: %s)" % bools(options['dry-run']))
print("--quiet -q quiet mode, no output at all (default: %s)" % bools(Config.QUIET))
print("--version prints '%s %s'" % (TITLE, VERSION))
print("--help -h help mode")
print(" -v verbose mode")
# parse arguments
def main(argv):
options = {
'store-checksum': False,
'force-overwrite': False,
'skip-staging': False,
'skip-download': False,
'skip-checksum': False,
'no-resume': False,
'source': "basket",
'request-timeout': 15,
'status-interval': 30,
'stage-interval': 10,
'stage-max-count': 10,
'buffer-size': 1024 * 1024,
'outputdir': "download",
'max-childs': 0,
'max-files': 0,
'target': "https://repository.surfsara.nl",
'test': False,
'no-verify': False,
'dry-run': False
}
# handle arguments
try:
opts, args = getopt.gnu_getopt(argv, "hdqb:vo:t:nkm:s:", \
["help", "version", "debug", "verbose", "quiet", "output=", "target=", "no-verify", "favourites", "skip-checksum", "store-checksum",
"buffer-size=", "dry-run", "no-resume", "force-overwrite", "skip-download", "skip-staging", "test", "source=",
"max-childs=", "max-files="])
except getopt.GetoptError as err:
error(err, 1)
if not args and len(set(sum(opts, ())).intersection(set(['-h', '--help']))) == 0:
error("missing token")
usage()
sys.exit(1)
# parse other
for opt, arg in opts:
if opt in ["-h", "--help"]:
help(options)
sys.exit()
elif opt == "--version":
print("%s %s" % (TITLE, VERSION))
sys.exit(1)
elif opt in ["--no-verify", "--skip-checksum", "--store-checksum", "--skip-download", "--skip-staging", "--no-resume", "--force-overwrite", "--test"]:
options.update({opt[2:]: True})
elif opt in ["-m", "--max-childs"]:
options.update({'max-childs': int(arg)})
elif opt in ["--max-files"]:
options.update({'max-files': int(arg)})
elif opt in ["--source"]:
options.update({"source": arg})
elif opt in ["--favourites", "--basket"]:
options.update({"source": opt[2:]})
elif opt in ["-k"]:
options.update({'no-verify': True})
elif opt in ["-d", "--debug"]:
Config.DEBUG = True
elif opt in ["-n", "--dry-run"]:
options.update({'dry-run': True})
elif opt in ["-v", "--verbose"]:
Config.VERBOSE = True
elif opt in ["-q", "--quiet"]:
Config.QUIET = True
elif opt in ["-b", "--buffer-size"]:
options.update({'buffer-size', int(arg)})
elif opt in ["-o", "--output"]:
options.update({'outputdir': arg})
elif opt in ["-t", "--target"]:
if not re.match(r"https?:\/\/[a-z0-9\.\-]{4,}", arg):
error('invalid target: %s' % arg, 1)
options.update({'target': arg})
# allow graceful exit on interrupt
signal.signal(signal.SIGINT, signalHandler)
# start procedures
dm = DownloadManager(args[0], options)
dm.downloadObjectList()
dm.processObjectList()
dm.preReport()
dm.startProcesses()
dm.postReport()
if __name__ == "__main__":
main(sys.argv[1:])