forked from Backblaze/B2_Command_Line_Tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb2.py
executable file
·881 lines (716 loc) · 26.8 KB
/
b2.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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
#!/usr/bin/env python3
######################################################################
#
# File: b2
#
# Copyright 2015 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
"""
This is a B2 command-line tool. See the USAGE message for details.
"""
from codecs import open
from os import path
import base64
import datetime
import docopt
import getpass
import hashlib
import json
import sys
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'VERSION'), encoding='utf-8') as f:
VERSION = f.read().strip()
with open(path.join(here, 'usage.txt'), encoding='utf-8') as f:
USAGE = f.read()
def message_and_exit(message):
"""Prints a message, and exits with error status.
"""
print(message, file=sys.stderr)
sys.exit(1)
def usage_and_exit():
"""Prints a usage message, and exits with an error status.
"""
message_and_exit(USAGE)
def decode_sys_argv():
"""
Returns the command-line arguments as unicode strings, decoding
whatever format they are in.
https://stackoverflow.com/questions/846850/read-unicode-characters-from-command-line-arguments-in-python-2-x-on-windows
"""
encoding = sys.getfilesystemencoding()
return [arg.decode(encoding) for arg in sys.argv]
class StoredAccountInfo(object):
"""Manages the file that holds the account ID and stored auth tokens.
When an instance of this class is created, it reads the account
info file in the home directory of the user, and remembers the info.
When any changes are made, they are written out to the file.
"""
ACCOUNT_AUTH_TOKEN = 'account_auth_token'
ACCOUNT_ID = 'account_id'
API_URL = 'api_url'
BUCKET_NAMES_TO_IDS = 'bucket_names_to_ids'
BUCKET_UPLOAD_DATA = 'bucket_upload_data'
BUCKET_UPLOAD_URL = 'bucket_upload_url'
BUCKET_UPLOAD_AUTH_TOKEN = 'bucket_upload_auth_token'
DOWNLOAD_URL = 'download_url'
def __init__(self):
self.filename = os.path.expanduser('~/.b2_account_info')
self.data = self._try_to_read_file()
if self.BUCKET_UPLOAD_DATA not in self.data:
self.data[self.BUCKET_UPLOAD_DATA] = {}
if self.BUCKET_NAMES_TO_IDS not in self.data:
self.data[self.BUCKET_NAMES_TO_IDS] = {}
def clear(self):
"""Removes all stored information.
"""
self.data = {}
self._write_file()
def _try_to_read_file(self):
try:
with open(self.filename, 'rb') as f:
return json.loads(f.read())
except Exception as e:
return {}
def get_account_id(self):
return self._get_account_info_or_exit(self.ACCOUNT_ID)
def get_account_auth_token(self):
return self._get_account_info_or_exit(self.ACCOUNT_AUTH_TOKEN)
def get_api_url(self):
return self._get_account_info_or_exit(self.API_URL)
def get_download_url(self):
return self._get_account_info_or_exit(self.DOWNLOAD_URL)
def _get_account_info_or_exit(self, key):
"""Returns the named field from the account data, or errors and exits.
"""
result = self.data.get(key)
if result is None:
message_and_exit('ERROR: No account. Use: b2 authorize_account')
return result
def set_account_id_and_auth_token(self, account_id, auth_token, api_url, download_url):
self.data[self.ACCOUNT_ID] = account_id
self.data[self.ACCOUNT_AUTH_TOKEN] = auth_token
self.data[self.API_URL] = api_url
self.data[self.DOWNLOAD_URL] = download_url
self._write_file()
def set_bucket_upload_data(self, bucket_id, upload_url, upload_auth_token):
self.data[self.BUCKET_UPLOAD_DATA][bucket_id] = {self.BUCKET_UPLOAD_URL : upload_url, self.BUCKET_UPLOAD_AUTH_TOKEN : upload_auth_token}
self._write_file()
def get_bucket_upload_data(self, bucket_id):
return self.data[self.BUCKET_UPLOAD_DATA].get(bucket_id)
def clear_bucket_upload_data(self, bucket_id):
upload_data = self.data[self.BUCKET_UPLOAD_DATA]
if bucket_id in upload_data:
del upload_data[bucket_id]
def save_bucket_name(self, bucket_name, bucket_id):
names_to_ids = self.data[self.BUCKET_NAMES_TO_IDS]
if bucket_name not in names_to_ids:
names_to_ids[bucket_name] = bucket_id
self._write_file()
def refresh_entire_bucket_name_cache(self, name_id_iterable):
names_to_ids = self.data[self.BUCKET_NAMES_TO_IDS]
new_cache = dict(name_id_iterable)
if names_to_ids != new_cache:
self.data[self.BUCKET_NAMES_TO_IDS] = new_cache
self._write_file()
def remove_bucket_name(self, bucket_name):
names_to_ids = self.data[self.BUCKET_NAMES_TO_IDS]
if bucket_name in names_to_ids:
del names_to_ids[bucket_name]
self._write_file()
def get_bucket_id_or_none_from_bucket_name(self, bucket_name):
names_to_ids = self.data[self.BUCKET_NAMES_TO_IDS]
return names_to_ids.get(bucket_name)
def _write_file(self):
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
if os.name == 'nt':
flags |= os.O_BINARY
with os.fdopen(os.open(self.filename, flags, 0o600), 'wb') as f:
json.dump(self.data, f, indent=4, sort_keys=True)
def report_http_error_and_exit(e, url, data, headers):
print('Error returned from server:')
print()
print('URL:', url)
print('Params:', data)
print('Headers:', headers)
print()
print(e.read())
sys.exit(1)
class OpenUrl(object):
"""
Context manager that handles an open urllib2.Request, and provides
the file-like object that is the response.
"""
def __init__(self, url, data, headers, exit_on_error=True):
self.url = url
self.data = data
self.headers = headers
self.file = None
self.exit_on_error = exit_on_error
def __enter__(self):
try:
request = urllib.request.Request(self.url, self.data, self.headers)
self.file = urllib.request.urlopen(request)
return self.file
except urllib.error.HTTPError as e:
if self.exit_on_error:
report_http_error_and_exit(e, self.url, self.data, self.headers)
else:
raise e
def __exit__(self, exception_type, exception, traceback):
if self.file is not None:
self.file.close()
def post_json(url, params, auth_token=None):
"""Coverts params to JSON and posts them to the given URL.
Returns the resulting JSON, decoded into a dict.
"""
data = json.dumps(params)
headers = {}
if auth_token is not None:
headers['Authorization'] = auth_token
with OpenUrl(url, data, headers) as f:
json_text = f.read()
return json.loads(json_text)
def post_file(url, headers, file_path, exit_on_error=True):
"""Posts the contents of the file to the URL.
"""
with open(file_path, 'rb') as data_file:
if 'Content-Length' not in headers:
headers['Content-Length'] = str(os.path.getsize(file_path))
with OpenUrl(url, data_file, headers, exit_on_error) as response_file:
json_text = response_file.read()
return json.loads(json_text)
def clear_account(args):
if len(args) != 0:
usage_and_exit()
info = StoredAccountInfo()
info.clear()
def url_for_api(info, api_name):
if api_name in ['b2_download_file_by_id']:
base = info.get_download_url()
else:
base = info.get_api_url()
return base + '/b2api/v1/' + api_name
def b2_url_encode(s):
"""URL-encodes a unicode string to be sent to B2 in an HTTP header.
"""
return urllib.parse.quote(s.encode('utf-8'))
def b2_url_decode(s):
"""Decodes a Unicode string returned from B2 in an HTTP header.
Returns a Python unicode string.
"""
# Use str() to make sure that the input to unquote is a str, not
# unicode, which ensures that the result is a str, which allows
# the decoding to work properly.
return urllib.parse.unquote_plus(str(s)).decode('utf-8')
def authorize_account(args):
auth_urls = {'--production':'https://api.backblaze.com','--dev':'http://api.test.blaze:8180','--staging':'https://api.backblaze.net'}
option = '--production'
url = auth_urls[option]
while 0 < len(args) and args[0][0] == '-':
option = args[0]
args = args[1:]
if option in auth_urls:
url = auth_urls[option]
break
else:
print('ERROR: unknown option', option)
usage_and_exit()
print('Using %s' % url)
if 2 < len(args):
usage_and_exit()
if 0 < len(args):
accountId = args[0]
else:
accountId = input('Backblaze account ID: ')
if 1 < len(args):
applicationKey = args[1]
else:
applicationKey = getpass.getpass('Backblaze application key: ')
url += '/b2api/v1/b2_authorize_account'
auth = 'Basic '+ base64.b64encode('%s:%s' % (accountId, applicationKey))
response = post_json(url, {}, auth)
info = StoredAccountInfo()
info.clear()
info.set_account_id_and_auth_token(
response['accountId'],
response['authorizationToken'],
response['apiUrl'],
response['downloadUrl']
)
def call_list_buckets(info):
"""Calls b2_list_buckets and returns the JSON for *all* buckets.
"""
account_id = info.get_account_id()
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_list_buckets')
params = {'accountId': account_id}
response = post_json(url, params, auth_token)
info.refresh_entire_bucket_name_cache(
(bucket['bucketName'], bucket['bucketId'])
for bucket in response['buckets']
)
return response
def get_bucket_id_from_bucket_name(info, bucket_name):
"""
Returns the bucket_id for the given bucket_name.
If we don't already know it from the info, try fetching it from
the B2 service.
"""
# If we can get it from the stored info, do that.
result = info.get_bucket_id_or_none_from_bucket_name(bucket_name)
if result is not None:
return result
# Call list_buckets to get the IDs of *all* buckets for this
# account.
response = call_list_buckets(info)
result = info.get_bucket_id_or_none_from_bucket_name(bucket_name)
if result is None:
print('No such bucket:', bucket_name)
sys.exit(1)
return result
def list_buckets(args):
if len(args) != 0:
usage_and_exit()
info = StoredAccountInfo()
response = call_list_buckets(info)
for bucket in response['buckets']:
bucket_name = bucket['bucketName']
bucket_id = bucket['bucketId']
bucket_type = bucket['bucketType']
print('%s %-10s %s' % (bucket_id, bucket_type, bucket_name))
def create_bucket(args):
if len(args) != 2:
usage_and_exit()
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
bucket_name = args[0]
bucket_type = args[1]
url = url_for_api(info, 'b2_create_bucket')
params = {
'accountId' : info.get_account_id(),
'bucketName' : bucket_name,
'bucketType' : bucket_type
}
response = post_json(url, params, auth_token)
print(response['bucketId'])
info.save_bucket_name(bucket_name, response['bucketId'])
def delete_bucket(args):
if len(args) != 1:
usage_and_exit()
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
bucket_name = args[0]
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
url = url_for_api(info, 'b2_delete_bucket')
params = {
'accountId' : info.get_account_id(),
'bucketId' : bucket_id
}
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=4, sort_keys=True))
def update_bucket(args):
if len(args) != 2:
usage_and_exit()
info = StoredAccountInfo()
account_id = info.get_account_id()
bucket_name = args[0]
bucket_type = args[1]
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_update_bucket')
params = {
'accountId' : account_id,
'bucketId' : bucket_id,
'bucketType' : bucket_type
}
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=4, sort_keys=True))
def list_file_names(args):
if len(args) < 1 or 3 < len(args):
usage_and_exit()
bucket_name = args[0]
if 2 <= len(args):
firstFileName = args[1]
else:
firstFileName = None
if 3 <= len(args):
count = int(args[2])
else:
count = 100
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_list_file_names')
params = {
'bucketId' : bucket_id,
'startFileName' : firstFileName,
'maxFileCount' : count
}
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=2, sort_keys=True))
def list_file_versions(args):
if len(args) < 1 or 4 < len(args):
usage_and_exit()
bucket_name = args[0]
if 2 <= len(args):
firstFileName = args[1]
else:
firstFileName = None
if 3 <= len(args):
firstFileId = args[2]
else:
firstFileId = None
if 4 <= len(args):
count = int(args[3])
else:
count = 100
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_list_file_versions')
params = {
'bucketId' : bucket_id,
'startFileName' : firstFileName,
'startFileId' : firstFileId,
'maxFileCount' : count
}
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=2, sort_keys=True))
def ensure_upload_data(bucket_id, info):
"""
Makes sure that we have an upload URL and auth token for the given bucket and
returns it.
"""
upload_data = info.get_bucket_upload_data(bucket_id)
if upload_data is None:
print('Getting upload URL...')
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_get_upload_url')
params = { 'bucketId' : bucket_id }
response = post_json(url, params, auth_token)
upload_url = response['uploadUrl']
upload_auth_token = response['authorizationToken']
info.set_bucket_upload_data(bucket_id, upload_url, upload_auth_token)
upload_data = info.get_bucket_upload_data(bucket_id)
return upload_data
def get_file_info(args):
if len(args) != 1:
usage_and_exit()
file_id = args[0]
bucket_id = file_id[3:27]
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_get_file_info')
params = { 'fileId' : file_id }
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=2, sort_keys=True))
def delete_file_version(args):
if len(args) != 2:
usage_and_exit()
file_name = args[0]
file_id = args[1]
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_delete_file_version')
params = { 'fileName' : file_name, 'fileId' : file_id }
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=2, sort_keys=True))
def hide_file(args):
if len(args) != 2:
usage_and_exit()
bucket_name = args[0]
file_name = args[1]
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_hide_file')
params = {
'bucketId' : bucket_id,
'fileName' : file_name
}
response = post_json(url, params, auth_token)
print(json.dumps(response, indent=2, sort_keys=True))
def hex_sha1_of_file(path):
with open(path, 'rb') as f:
block_size = 1024 * 1024
digest = hashlib.sha1()
while True:
data = f.read(block_size)
if len(data) == 0:
break
digest.update(data)
return digest.hexdigest()
def parse_file_info(item, file_infos):
parts = item.split('=')
if len(parts) != 2:
print('ERROR: bad file info:', item, file=sys.stdout)
sys.exit(1)
file_infos[parts[0]] = parts[1]
def upload_file(args):
content_type = 'b2/x-auto'
file_infos = {}
while 0 < len(args) and args[0][0] == '-':
option = args[0]
if option == '--contentType':
if len(args) < 2:
usage_and_exit()
content_type = args[1]
args = args[2:]
elif option == '--info':
if len(args) < 2:
usage_and_exit()
parse_file_info(args[1], file_infos)
args = args[2:]
else:
usage_and_exit()
if len(args) != 3:
usage_and_exit()
bucket_name = args[0]
local_file = args[1]
b2_file = args[2]
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
# Try 5 times to upload the file. If one fails, get a different
# upload URL for the next try.
for i in range(5):
bucket_upload_data = ensure_upload_data(bucket_id, info)
url = bucket_upload_data[StoredAccountInfo.BUCKET_UPLOAD_URL]
headers = {
'Authorization': bucket_upload_data[StoredAccountInfo.BUCKET_UPLOAD_AUTH_TOKEN],
'X-Bz-File-Name': b2_url_encode(b2_file),
'Content-Type': content_type,
'X-Bz-Content-Sha1': hex_sha1_of_file(local_file)
}
for (k, v) in file_infos.items():
headers['X-Bz-Info-' + k] = b2_url_encode(v)
try:
response = post_file(url, headers, local_file, exit_on_error=False)
print(json.dumps(response, indent=4, sort_keys=True))
if 'fileId' in response:
print("URL by file name: " + info.get_download_url() + "/file/" + bucket_name + "/" + b2_file)
print("URL by fileId: " + info.get_download_url() + "/b2api/v1/b2_download_file_by_id?fileId=" + response['fileId'])
return
except urllib.error.HTTPError as e:
if 500 <= e.code and e.code < 600:
info.clear_bucket_upload_data(bucket_id)
else:
report_http_error_and_exit(e, url, None, headers)
print('FAILED to upload after 5 tries')
sys.exit(1)
def download_file_from_url(url, request_body, encoded_headers, local_file_name):
with OpenUrl(url, request_body, encoded_headers) as response:
info = response.info()
file_size = int(info['content-length'])
file_sha1 = info['x-bz-content-sha1']
print('File name: ', info['x-bz-file-name'])
print('File size: ', file_size)
print('Content type:', info['content-type'])
print('Content sha1:', file_sha1)
for name in info:
if name.startswith('x-bz-info-'):
print('INFO', name[10:] + ':', info[name])
block_size = 4096
digest = hashlib.sha1()
bytes_read = 0
with open(local_file_name, 'wb') as f:
while True:
data = response.read(block_size)
if len(data) == 0:
break
f.write(data)
digest.update(data)
bytes_read += len(data)
if bytes_read != int(info['content-length']):
print('ERROR: only %d of %d bytes read' % (bytes_read, file_size))
if digest.hexdigest() != file_sha1:
print('ERROR: sha1 checksum mismatch -- bad data')
print('checksum matches')
def download_file_by_id(args):
if len(args) != 2:
usage_and_exit()
file_id = args[0]
local_file_name = args[1]
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
url = url_for_api(info, 'b2_download_file_by_id')
headers = { 'Authorization' : auth_token }
params = { 'fileId' : file_id }
request_body = json.dumps(params)
download_file_from_url(url, request_body, headers, local_file_name)
def download_file_by_name(args):
if len(args) != 3:
usage_and_exit()
bucket_name = args[0]
file_name = args[1]
local_file_name = args[2]
info = StoredAccountInfo()
auth_token = info.get_account_auth_token()
url = info.get_download_url() + '/file/' + b2_url_encode(bucket_name) + '/' + b2_url_encode(file_name)
headers = { 'Authorization' : auth_token }
download_file_from_url(url, None, headers, local_file_name)
def make_url(args):
if len(args) != 1:
usage_and_exit()
file_id = args[0]
bucket_id = file_id[3:27]
info = StoredAccountInfo()
url = url_for_api(info, 'b2_download_file_by_id')
print('%s?fileId=%s' % (url, file_id))
def print_ls_entry(is_long, is_folder, name, file):
# if not long, it's easy
if not is_long:
print(name)
else:
# order is file_id, action, date, time, size, name
format = '%83s %6s %10s %8s %9d %s'
if is_folder:
print(format % ('-', '-', '-', '-', 0, name))
else:
file_id = file['fileId']
action = file['action']
dt = datetime.datetime.utcfromtimestamp(file['uploadTimestamp'] / 1000)
date_str = dt.strftime('%Y-%m-%d')
time_str = dt.strftime('%H:%M:%S')
size = file['size']
print(format % (file_id, action, date_str, time_str, size, name))
def ls(args):
# Parse arguments
long_format = False
show_versions = False
while len(args) != 0 and args[0][0] == '-':
option = args[0]
args = args[1:]
if option == '--long':
long_format = True
elif option == '--versions':
show_versions = True
else:
print('Unknown option:', option)
usage_and_exit()
if len(args) < 1 or 2 < len(args):
usage_and_exit()
bucket_name = args[0]
if len(args) == 1:
prefix = ""
else:
prefix = args[1]
if not prefix.endswith('/'):
prefix += '/'
# Get authorization
info = StoredAccountInfo()
bucket_id = get_bucket_id_from_bucket_name(info, bucket_name)
auth_token = info.get_account_auth_token()
# Loop until all files in the named directory have been listed.
# The starting point of the first list_file_names request is the
# prefix we're looking for. The prefix ends with '/', which is
# now allowed for file names, so no file name will match exactly,
# but the first one after that point is the first file in that
# "folder". If the first search doesn't produce enough results,
# then we keep callig list_file_names until we get all of the
# names in this "folder".
current_dir = None
if show_versions:
api_name = 'b2_list_file_versions'
else:
api_name = 'b2_list_file_names'
start_file_name = prefix
start_file_id = None
while True:
url = url_for_api(info, api_name)
params = {
'bucketId' : bucket_id,
'startFileName' : start_file_name
}
if start_file_id is not None:
params['startFileId'] = start_file_id
response = post_json(url, params, auth_token)
for file in response['files']:
name = file['fileName']
if not name.startswith(prefix):
# We're past the files we care about
return
after_prefix = name[len(prefix):]
if '/' not in after_prefix:
# This is not a folder, so we'll print it out and
# continue on.
file_id = file['fileId']
size = file['size']
print_ls_entry(long_format, False, name, file)
current_dir = None
else:
# This is a folder. If it's different than the folder
# we're already in, then we can print it. This check
# is needed, because all of the files in the folder
# will be in the list.
folder_with_slash = after_prefix.split('/')[0] + '/'
if folder_with_slash != current_dir:
folder_name = prefix + folder_with_slash
print_ls_entry(long_format, True, folder_name, file)
current_dir = folder_with_slash
if response['nextFileName'] is None:
# The response says there are no more files in the bucket,
# so we can stop.
return
# Now we need to set up the next search. The response from
# B2 has the starting point to continue with the next file,
# but if we're in the middle of a "folder", we can skip ahead
# to the end of the folder. The character after '/' is '0',
# so we'll replace the '/' with a '0' and start there.
if current_dir is None:
start_file_name = response.get('nextFileName')
start_file_id = response.get('nextFileId')
else:
start_file_name = max(
response['nextFileName'],
prefix + current_dir[:-1] + '0'
)
def main():
if len(sys.argv) < 2:
usage_and_exit()
decoded_argv = decode_sys_argv()
action = decoded_argv[1]
args = decoded_argv[2:]
if action == 'authorize_account':
authorize_account(args)
elif action == 'clear_account':
clear_account(args)
elif action == 'create_bucket':
create_bucket(args)
elif action == 'delete_bucket':
delete_bucket(args)
elif action == 'delete_file_version':
delete_file_version(args)
elif action == 'download_file_by_id':
download_file_by_id(args)
elif action == 'download_file_by_name':
download_file_by_name(args)
elif action == 'get_file_info':
get_file_info(args)
elif action == 'hide_file':
hide_file(args)
elif action == 'list_buckets':
list_buckets(args)
elif action == 'list_file_names':
list_file_names(args)
elif action == 'list_file_versions':
list_file_versions(args)
elif action == 'ls':
ls(args)
elif action == 'make_url':
make_url(args)
elif action == 'update_bucket':
update_bucket(args)
elif action == 'upload_file':
upload_file(args)
elif action == 'version':
print('b2 command line tool, version', VERSION)
else:
usage_and_exit()
if __name__ == '__main__':
main()