forked from houtianze/bypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bypy.py
executable file
·2451 lines (2136 loc) · 78.8 KB
/
bypy.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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# encoding: utf-8
# === IMPORTANT ====
# NOTE: In order to support no-ASCII file names,
# your system's locale MUST be set to 'utf-8'
# CAVEAT: DOESN'T work with proxy, the underlying reason being
# the 'requests' package used for http communication doesn't seem
# to work properly with proxies, reason unclear.
# NOTE: It seems Baidu doesn't handle MD5 quite right after combining files,
# so it may return erroneous MD5s. Perform a rapidupload again may fix the problem.
# That's why I changed default behavior to no-verification.
# TODO: syncup / upload, syncdown / downdir are partially duplicates
# the difference: syncup/down compare and perform actions
# while down/up just proceed to download / upload (but still compare during actions)
# so roughly the same, except that sync can delete extra files
# TODO: Use batch functions for better performance
# TODO: Use posixpath for path handling
# TODO: Dry run?
# TODO: Insecure (http) operations for better performance?
# TODO: Better logic for __request() with retry (also use decorator maybe?)
'''
bypy -- Python client for Baidu Yun
---
Copyright 2013 Hou Tianze (GitHub: houtianze, Twitter: @ibic, G+: +TianzeHou)
Licensed under the GPLv3
https://www.gnu.org/licenses/gpl-3.0.txt
bypy is a Baidu Yun client written in Python (2.7).
(NOTE: You need to install the 'requests' library by running 'pip install requests')
It offers some file operations like: list, download, upload, syncup, syncdown, etc.
The main purpose is to utilize Baidu Yun in Linux environment (e.g. Raspberry Pi)
It uses a server for OAuth authorization, to conceal the Application's Secret Key.
Alternatively, you can create your own App at Baidu and replace the 'ApiKey' and 'SecretKey' with your copies,
and then, change 'ServerAuth' to 'False'
---
@author: Hou Tianze (GitHub: houtianze, Twitter: @ibic, G+: +TianzeHou)
@copyright: 2013 Hou Tianze. All rights reserved.
@license: GPLv3
@contact: None
@deffield updated: Updated
'''
# it takes days just to fix you, unicode ...
# some references
# https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3
# https://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python
# http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/
# https://stackoverflow.com/questions/11741574/how-to-set-the-default-encoding-to-utf-8-in-python
# https://stackoverflow.com/questions/2276200/changing-default-encoding-of-python
from __future__ import unicode_literals
import os
import sys
#reload(sys)
#sys.setdefaultencoding(SystemEncoding)
import locale
SystemLanguageCode, SystemEncoding = locale.getdefaultlocale()
if SystemEncoding.upper() != 'UTF-8':
err = "You MUST set system locale to 'UTF-8' to support unicode file names."
ex = Exception(err)
print(err)
raise ex
import codecs
# no idea who is the asshole that screws the sys.stdout.encoding
# the locale is 'UTF-8', sys.stdin.encoding is 'UTF-8',
# BUT, sys.stdout.encoding is 'None' ...
if not (sys.stdout.encoding and sys.stdout.encoding.lower() == 'utf-8'):
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
import signal
import time
import shutil
import posixpath
#import types
import traceback
import inspect
import logging
import httplib
import urllib
import json
import hashlib
import binascii
import re
import cPickle as pickle
import pprint
#from collections import OrderedDict
from os.path import expanduser
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
try:
# non-standard python library, needs 'pip install requests'
import requests
except:
print "Fail to import the 'requests' library\n" \
"You need to install the 'requests' python library\n" \
"You can install it by running 'pip install requests'"
raise
# non-standard python library, needs 'pip install requesocks'
#import requesocks as requests # if you need socks proxy
# Defines that should never be changed
OneK = 1024
OneM = OneK * OneK
OneG = OneM * OneK
OneT = OneG * OneK
OneP = OneT * OneK
OneE = OneP * OneK
# special variables
__all__ = []
__version__ = 0.1
__date__ = '2013-10-25'
__updated__ = '2014-01-13'
# ByPy default values
DefaultSliceInMB = 20
DefaultSliceSize = 20 * OneM
DefaultDlChunkSize = OneM
RetryDelayInSec = 10
# Baidu PCS constants
MinRapidUploadFileSize = 256 * OneK
MaxSliceSize = 2 * OneG
MaxSlicePieces = 1024
# return (error) codes
ENoError = 0 # plain old OK, fine, no error.
EApiNotConfigured = 10 # ApiKey, SecretKey and AppPcsPath not properly configured
EArgument = 10 # invalid program command argument
EAbort = 20 # aborted
EException = 30 # unhandled exception occured
EParameter = 40 # invalid parameter passed to ByPy
EInvalidJson = 50
EHashMismatch = 60 # MD5 hashes of the local file and remote file don't match each other
EFileWrite = 70
EFileTooBig = 80 # file too big to upload
EFailToCreateLocalDir = 90
EFailToCreateLocalFile = 100
EFailToDeleteDir = 110
EFailToDeleteFile = 120
EFileNotFound = 130
EMaxRetry = 140
ERequestFailed = 150 # request failed
ECacheNotLoaded = 160
EFatal = -1 # No way to continue
# internal errors
IEMD5NotFound = 31079 # corresponds to "File md5 not found, you should use upload API to upload the whole file." error at Baidu PCS
# PCS configuration constants
# ==== NOTE ====
# I use server auth, because it's the only possible method to protect the SecretKey.
# If you don't like that and want to perform local authorization using 'Device' method, you need to:
# - Change to: ServerAuth = 0
# - Paste your own ApiKey and SecretKey.
# - Change the AppPcsPath to your own App's directory at Baidu PCS
# Then you are good to go
ServerAuth = True # change it to 'False' if you use your own appid
GaeUrl = 'https://bypyoauth.appspot.com'
OpenShiftUrl = 'https://bypy-tianze.rhcloud.com'
GaeRedirectUrl = GaeUrl + '/auth'
GaeRefreshUrl = GaeUrl + '/refresh'
OpenShiftRedirectUrl = OpenShiftUrl + '/auth'
OpenShiftRefreshUrl = OpenShiftUrl + '/refresh'
ApiKey = 'q8WE4EpCsau1oS0MplgMKNBn' # replace with your own ApiKey if you use your own appid
SecretKey = '' # replace with your own SecretKey if you use your own appid
# NOTE: no trailing '/'
AppPcsPath = '/apps/bypy' # change this to the App's direcotry you specified when creating the app
AppPcsPathLen = len(AppPcsPath)
# Program setting constants
HomeDir = expanduser('~')
TokenFilePath = HomeDir + os.sep + '.bypy.json'
HashCachePath = HomeDir + os.sep + '.bypy.pickle'
#UserAgent = 'Mozilla/5.0'
# Baidu PCS URLs etc.
OpenApiUrl = "https://openapi.baidu.com"
OpenApiVersion = "2.0"
OAuthUrl = OpenApiUrl + "/oauth/" + OpenApiVersion
ServerAuthUrl = OAuthUrl + "/authorize"
DeviceAuthUrl = OAuthUrl + "/device/code"
TokenUrl = OAuthUrl + "/token"
PcsUrl = 'https://pcs.baidu.com/rest/2.0/pcs/'
CPcsUrl = 'https://c.pcs.baidu.com/rest/2.0/pcs/'
DPcsUrl = 'https://d.pcs.baidu.com/rest/2.0/pcs/'
# when was your last time flushing a toilet?
__last_flush = time.time()
#__last_flush = 0
PrintFlushPeriodInSec = 5.0
# save cache if more than 10 minutes passed
last_cache_save = time.time()
CacheSavePeriodInSec = 10 * 60.0
def pr(msg):
print msg
# we need to flush the output periodically to see the latest status
global __last_flush
now = time.time()
if now - __last_flush >= PrintFlushPeriodInSec:
sys.stdout.flush()
__last_flush = now
def plog(tag, msg, showtime = True, showdate = False, prefix = '', suffix = ''):
if showtime or showdate:
now = time.localtime()
if showtime:
tag += time.strftime("[%H:%M:%S] ", now)
if showdate:
tag += time.strftime("[%Y-%m-%d] ", now)
if prefix:
pr("{}{}".format(tag, prefix))
pr("{}{}".format(tag, msg))
if suffix:
pr("{}{}".format(tag, suffix))
def perr(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<E> ', msg, showtime, showdate, prefix, suffix)
def pwarn(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<W> ', msg, showtime, showdate, prefix, suffix)
def pinfo(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<I> ', msg, showtime, showdate, prefix, suffix)
def pdbg(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<D> ', msg, showtime, showdate, prefix, suffix)
def si_size(num, precision = 3):
''' DocTests:
>>> si_size(1000)
'1000B'
>>> si_size(1025)
'1.001KB'
'''
numa = abs(num)
if numa < OneK:
return str(num) + 'B'
elif numa < OneM:
return str(round(float(num) / float(OneK), precision)) + 'KB'
elif numa < OneG:
return str(round(float(num) / float(OneM), precision)) + 'MB'
elif numa < OneT:
return str(round(float(num) / float(OneG), precision)) + 'GB'
elif numa < OneP:
return str(round(float(num) / float(OneT), precision)) + 'TB'
elif numa < OneE:
return str(round(float(num) / float(OneP), precision)) + 'PB'
else :
return str(num) + 'B'
si_table = {
'K' : OneK,
'M' : OneM,
'G' : OneG,
'T' : OneT,
'E' : OneE }
def interpret_size(si):
'''
>>> interpret_size(10)
10
>>> interpret_size('10')
10
>>> interpret_size('10b')
10
>>> interpret_size('10k')
10240
>>> interpret_size('10K')
10240
>>> interpret_size('10kb')
10240
>>> interpret_size('10kB')
10240
>>> interpret_size('a10')
Traceback (most recent call last):
ValueError
>>> interpret_size('10a')
Traceback (most recent call last):
KeyError: 'A'
'''
m = re.match(r"\s*(\d+)\s*([ac-z]?)(b?)\s*$", str(si), re.I)
if m:
if not m.group(2) and m.group(3):
times = 1
else:
times = si_table[m.group(2).upper()] if m.group(2) else 1
return int(m.group(1)) * times
else:
raise ValueError
def remove_backslash(s):
return s.replace(r'\/', r'/')
def rb(s):
return s.replace(r'\/', r'/')
# no leading, trailing '/'
# remote path rule:
# - all public methods of ByPy shall accept remote path as "partial path"
# (before calling get_pcs_path())
# - all private methods of ByPy shall accept remote path as "full path"
# (after calling get_pcs_path())
def get_pcs_path(path):
if not path or path == '/' or path == '\\':
return AppPcsPath
return (AppPcsPath + '/' + path.strip('/')).rstrip('/')
# guarantee no-exception
def removefile(path, verbose = False):
result = ENoError
try:
if verbose:
pr("Removing local file '{}'".format(path))
if path:
os.remove(path)
except Exception:
perr("Fail to remove local fle '{}'.\nException:{}\n".format(path, traceback.format_exc()))
result = EFailToDeleteFile
return result
def removedir(path, verbose = False):
result = ENoError
try:
if verbose:
pr("Removing local directory '{}'".format(path))
if path:
shutil.rmtree(path)
except Exception:
perr("Fail to remove local directory '{}'.\nException:{}\n".format(path, traceback.format_exc()))
result = EFailToDeleteDir
return result
def makedir(path, verbose = False):
result = ENoError
try:
if verbose:
pr("Creating local directory '{}'".format(path))
if not (not path or path == '.'):
os.makedirs(path)
except os.error:
perr("Failed at creating local dir '{}'.\nException:\n'{}'".format(path, traceback.format_exc()))
result = EFailToCreateLocalDir
return result
# guarantee no-exception
def getfilesize(path):
size = -1
try:
size = os.path.getsize(path)
except os.error:
perr("Exception occured while getting size of '{}'. Exception:\n{}".format(path, traceback.format_exc()))
return size
# guarantee no-exception
def getfilemtime(path):
mtime = -1
try:
mtime = os.path.getmtime(path)
except os.error:
perr("Exception occured while getting modification time of '{}'. Exception:\n{}".format(path, traceback.format_exc()))
return mtime
# https://stackoverflow.com/questions/10883399/unable-to-encode-decode-pprint-output
class MyPrettyPrinter(pprint.PrettyPrinter):
def format(self, obj, context, maxlevels, level):
if isinstance(obj, unicode):
#return (obj.encode('utf8'), True, False)
return (obj, True, False)
if isinstance(obj, str):
convert = False
#for c in obj:
# if ord(c) >= 128:
# convert = True
# break
try:
codecs.decode(obj)
except:
convert = True
if convert:
return ("0x{}".format(binascii.hexlify(obj)), True, False)
return pprint.PrettyPrinter.format(self, obj, context, maxlevels, level)
# there is room for more space optimization (like using the tree structure),
# but it's not added at the moment. for now, it's just simple pickle.
# SQLite might be better for portability
# NOTE: file names are case-sensitive
class cached(object):
''' simple decorator for hash caching (using pickle) '''
usecache = True
verbose = False
debug = False
cache = {}
cacheloaded = False
dirty = False
# we don't do cache loading / unloading here because it's an decorator,
# and probably multiple instances are created for md5, crc32, etc
# it's a bit complex, and i thus don't have the confidence to do it in ctor/dtor
def __init__(self, f):
self.f = f
def __call__(self, *args):
assert len(args) > 0
result = None
path = args[0]
dir, file = os.path.split(path) # the 'filename' parameter
absdir = os.path.abspath(dir)
if absdir in cached.cache:
entry = cached.cache[absdir]
if file in entry:
info = entry[file]
if self.f.__name__ in info \
and info['size'] == getfilesize(path) \
and info['mtime'] == getfilemtime(path) \
and self.f.__name__ in info \
and cached.usecache:
result = info[self.f.__name__]
if cached.debug:
pdbg("Cache hit for file '{}',\n{}: {}\nsize: {}\nmtime: {}".format(
path, self.f.__name__,
result if isinstance(result, (int, long, float, complex)) else binascii.hexlify(result),
info['size'], info['mtime']))
else:
result = self.f(*args)
self.__store(info, path, result)
else:
result = self.f(*args)
entry[file] = {}
info = entry[file]
self.__store(info, path, result)
else:
result = self.f(*args)
cached.cache[absdir] = {}
entry = cached.cache[absdir]
entry[file] = {}
info = entry[file]
self.__store(info, path, result)
return result
def __store(self, info, path, value):
cached.dirty = True
info['size'] = getfilesize(path)
info['mtime'] = getfilemtime(path)
info[self.f.__name__] = value
if cached.debug:
situation = "Storing cache"
if cached.usecache:
situation = "Cache miss"
pdbg((situation + " for file '{}',\n{}: {}\nsize: {}\nmtime: {}").format(
path, self.f.__name__,
value if isinstance(value, (int, long, float, complex)) else binascii.hexlify(value),
info['size'], info['mtime']))
# periodically save to prevent loss in case of system crash
global last_cache_save
now = time.time()
if now - last_cache_save >= CacheSavePeriodInSec:
cached.savecache()
last_cache_save = now
if cached.debug:
pdbg("Periodically saving Hash Cash")
@staticmethod
def loadcache():
# load cache even we don't use cached hash values,
# because we will save (possibly updated) and hash values
if not cached.cacheloaded: # no double-loading
if cached.verbose:
pr("Loading Hash Cache File '{}'...".format(HashCachePath))
if os.path.exists(HashCachePath):
try:
with open(HashCachePath, 'rb') as f:
cached.cache = pickle.load(f)
cached.cacheloaded = True
if cached.verbose:
pr("Hash Cache File loaded.")
except pickle.PickleError:
perr("Fail to load the Hash Cache, no caching. Exception:\n{}".format(traceback.format_exc()))
cached.cache = {}
else:
if cached.verbose:
pr("Hash Cache File not found, no caching")
else:
if cached.verbose:
pr("Not loading Hash Cache since 'cacheloaded' is '{}'".format( cached.cacheloaded))
return cached.cacheloaded
@staticmethod
def savecache(force_saving = False):
saved = False
# even if we were unable to load the cache, we still save it.
if cached.dirty or force_saving:
if cached.verbose:
pr("Saving Hash Cache...")
try:
with open(HashCachePath, 'wb') as f:
pickle.dump(cached.cache, f)
if cached.verbose:
pr("Hash Cache saved.")
saved = True
cached.dirty = False
except Exception:
perr("Failed to save Hash Cache. Exception:\n".format(traceback.format_exc()))
else:
if cached.verbose:
pr("Not saving Hash Cache since 'dirty' is '{}' and 'force_saving' is '{}'".format(
cached.dirty, force_saving))
return saved
@staticmethod
def cleancache():
if cached.loadcache():
for absdir in cached.cache.keys():
if not os.path.exists(absdir):
if cached.verbose:
pr("Directory: '{}' no longer exists, removing the cache entries".format(absdir))
cached.dirty = True
del cached.cache[absdir]
else:
oldfiles = cached.cache[absdir]
files = {}
needclean = False
for f in oldfiles.keys():
p = os.path.join(absdir, f)
if os.path.exists(p):
files[f] = oldfiles[f]
else:
if cached.verbose:
needclean = True
pr("File '{}' no longer exists, removing the cache entry".format(p))
if needclean:
cached.dirty = True
cached.cache[absdir] = files
cached.savecache()
@cached
def md5(filename, slice = OneM):
m = hashlib.md5()
with open(filename, "rb") as f:
while True:
buf = f.read(slice)
if buf:
m.update(buf)
else:
break
return m.digest()
# slice md5 for baidu rapidupload
@cached
def slice_md5(filename):
m = hashlib.md5()
with open(filename, "rb") as f:
buf = f.read(256 * OneK)
m.update(buf)
return m.digest()
@cached
def crc32(filename, slice = OneM):
with open(filename, "rb") as f:
buf = f.read(slice)
crc = binascii.crc32(buf)
while True:
buf = f.read(slice)
if buf:
crc = binascii.crc32(buf, crc)
else:
break
return crc & 0xffffffff
def enable_http_logging():
httplib.HTTPConnection.debuglevel = 1
logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
def ls_type(isdir):
return 'D' if isdir else 'F'
def ls_time(itime):
return time.strftime('%Y-%m-%d, %H:%M:%S', time.localtime(itime))
def print_pcs_list(json, foundmsg = "Found:", notfoundmsg = "Nothing found."):
list = json['list']
if list:
pr(foundmsg)
for f in list:
pr("{} {} {} {} {} {}".format(
ls_type(f['isdir']),
f['path'],
f['size'],
ls_time(f['ctime']),
ls_time(f['mtime']),
f['md5']))
else:
pr(notfoundmsg)
# tree represented using dictionary, (Obsolete: OrderedDict no longer required)
# NOTE: No own-name is kept, so the caller needs to keep track of that
# NOTE: Case-sensitive, as I don't want to waste time wrapping up a case-insensitive one
# single-linked-list, no backwards travelling capability
class PathDictTree(dict):
def __init__(self, type = 'D', **kwargs):
self.type = type
self.extra = {}
for k, v in kwargs.items():
self.extra[k] = v
super(PathDictTree, self).__init__()
def __str__(self):
return self.__str('')
def __str(self, prefix):
result = ''
for k, v in self.iteritems():
result += "{} - {}{} - size: {} - md5: {} \n".format(
v.type, prefix, k,
v.extra['size'] if 'size' in v.extra else '',
binascii.hexlify(v.extra['md5']) if 'md5' in v.extra else '')
for k, v in self.iteritems():
if v.type == 'D':
result += v.__str(prefix + '/' + k)
return result
def add(self, name, child):
self[name] = child
return child
# returns the child tree at the given path
# assume that path is only separated by '/', instead of '\\'
def get(self, path):
place = self
if path:
assert '\\' not in path
route = filter(None, path.split('/'))
for part in route:
if part in place:
sub = place[part]
assert place.type == 'D' # sanity check
place = sub
else:
return None
return place
# return a string list of all 'path's in the tree
def allpath(self):
result = []
for k, v in self.items():
if v.type == 'F':
result.append(k)
elif v.type == 'D':
for p in self.get(k).allpath():
result.append(k + '/' + p)
else:
assert False # why are you here?
return result
class ByPy(object):
'''The main class of the bypy program'''
# public static properties
HelpMarker = "Usage:"
ListFormatDict = {
'$t' : (lambda json: ls_type(json['isdir'])),
'$f' : (lambda json: json['path'].split('/')[-1]),
'$c' : (lambda json: ls_time(json['ctime'])),
'$m' : (lambda json: ls_time(json['mtime'])),
'$d' : (lambda json: str(json['md5'] if 'md5' in json else '')),
'$s' : (lambda json: str(json['size'])),
'$i' : (lambda json: str(json['fs_id'])),
'$b' : (lambda json: str(json['block_list'] if 'block_list' in json else '')),
'$u' : (lambda json: 'HasSubDir' if 'ifhassubdir' in json and json['ifhassubdir'] else 'NoSubDir'),
'$$' : (lambda json: '$')
}
def __init__(self,
slice_size = DefaultSliceSize, dl_chunk_size = DefaultDlChunkSize,
verify = True, secure = True,
retry = 5, timeout = None,
quit_when_fail = False,
listfile = None,
verbose = 0, debug = False):
self.__slice_size = slice_size
self.__dl_chunk_size = dl_chunk_size
self.__verify = verify
self.__retry = retry
self.__quit_when_fail = quit_when_fail
self.__timeout = timeout
self.__secure = secure
self.__listfile = listfile
self.Verbose = verbose
self.Debug = debug
# guru said: thou shalt initialize
self.__json = {}
self.__access_token = ''
self.__remote_json = {}
self.__slice_md5s = []
if self.__listfile and os.path.exists(self.__listfile):
with open(self.__listfile, 'r') as f:
self.__list_file_contents = f.read()
else:
self.__list_file_contents = None
# only if user specifies '-ddd' or more 'd's, the following
# debugging information will be shown, as it's very talkative.
if self.Debug >= 3:
# these two lines enable debugging at httplib level (requests->urllib3->httplib)
# you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# the only thing missing will be the response.body which is not logged.
enable_http_logging()
if not self.__load_local_json():
# no need to call __load_local_json() again as __auth() will load the json & acess token.
result = self.__auth()
if result != ENoError:
perr("Program authorization FAILED.\n" + \
"You need to authorize this program before using any PCS functions.\n" + \
"Quitting...\n")
onexit(result)
def pv(self, msg, **kwargs):
if self.Verbose:
pr(msg)
def pd(self, msg, level = 1, **kwargs):
if self.Debug >= level:
pdbg(msg, kwargs)
def __print_error_json(self, r):
try:
dj = r.json()
if 'error_code' in dj and 'error_msg' in dj:
ec = dj['error_code']
pf = perr
if ec == IEMD5NotFound:
pf = pinfo
pf('Error code: ' + str(ec))
pf('Error Description: ' + dj['error_msg'])
except Exception:
perr('Error parsing JSON Error Code from:\n{}'.format(rb(r.text)))
perr('Exception: {}'.format(traceback.format_exc()))
def __dump_exception(self, ex, url, pars, r, act):
if self.Debug or self.Verbose:
perr("Error accessing '{}'".format(url))
if ex and isinstance(ex, Exception) and self.Debug:
perr("Exception: {}".format(ex))
pr(traceback.format_exc())
perr("Function: {}".format(act.__name__))
perr("Website parameters: {}".format(pars))
if r:
perr("HTTP Status Code: {}".format(r.status_code))
self.__print_error_json(r)
perr("Website returned: {}".format(rb(r.text)))
# always append / replace the 'access_token' parameter in the https request
def __request_work(self, url, pars, act, method, actargs = None, addtoken = True, **kwargs):
result = ENoError
r = None
parsnew = pars.copy()
if addtoken:
parsnew['access_token'] = self.__access_token
try:
self.pd(method + ' ' + url)
self.pd("actargs: {}".format(actargs))
self.pd("Params: {}".format(pars))
if method.upper() == 'GET':
r = requests.get(url,
#headers = { 'User-Agent': UserAgent },
params = parsnew, timeout = self.__timeout, verify = False, **kwargs)
elif method.upper() == 'POST':
r = requests.post(url,
#headers = { 'User-Agent': UserAgent },
params = parsnew, timeout = self.__timeout, verify = False, **kwargs)
# BUGFIX: DON'T do this, if we are downloading a big file, the program sticks and dies
#self.pd("Request Headers: {}".format(
# pprint.pformat(r.request.headers)), 2)
sc = r.status_code
self.pd("HTTP Status Code: {}".format(sc))
# BUGFIX: DON'T do this, if we are downloading a big file, the program sticks and dies
#self.pd("Header returned: {}".format(pprint.pformat(r.headers)), 2)
#self.pd("Website returned: {}".format(rb(r.text)), 3)
if sc == requests.codes.ok:
self.pd("Request OK, processing action")
result = act(r, actargs)
if result == ENoError:
self.pd("Request all goes fine")
else:
ec = 0
try:
j = r.json()
ec = j['error_code']
self.__print_error_json(r)
except ValueError:
perr("Not valid error JSON")
# 6 (sc: 403): No permission to access user data
# 110 (sc: 401): Access token invalid or no longer valid
# 111 (sc: 401): Access token expired
if ec == 111 or ec == 110 or ec == 6: # and sc == 401:
self.pd("Need to refresh token, refreshing")
if ENoError == self.__refresh_token(): # refresh the token and re-request
# TODO: avoid dead recursive loops
# TODO: properly pass retry
result = self.__request(url, pars, act, method, actargs, True, addtoken, **kwargs)
else:
result = EFatal
perr("FATAL: Token refreshing failed, can't continue.\nQuitting...\n")
onexit(result)
# File md5 not found, you should use upload API to upload the whole file.
elif ec == IEMD5NotFound: # and sc == 404:
self.pd("MD5 not found, rapidupload failed")
result = ec
# errors that make retrying meaningless
elif (
ec == 31061 or # sc == 400 file already exists
ec == 31062 or # sc == 400 file name is invalid
ec == 31063 or # sc == 400 file parent path does not exist
ec == 31064 or # sc == 403 file is not authorized
ec == 31065 or # sc == 400 directory is full
ec == 31066): # sc == 403 (indeed 404) file does not exist
result = ec
self.__dump_exception(None, url, pars, r, act)
else:
result = ERequestFailed
self.__dump_exception(None, url, pars, r, act)
except requests.exceptions.RequestException as ex:
self.__dump_exception(ex, url, pars, r, act)
result = ERequestFailed
except Exception as ex: # shall i quit? i think so.
self.__dump_exception(ex, url, pars, r, act)
result = EFatal
perr("Fatal Exception.\nQuitting...\n")
onexit(result)
# we eat the exception, and use return code as the only
# error notification method, we don't want to mix them two
#raise # must notify the caller about the failure
return result
def __request(self, url, pars, act, method, actargs = None, retry = True, addtoken = True, **kwargs):
tries = 1
if retry:
tries = self.__retry
i = 0
result = ERequestFailed
while True:
result = self.__request_work(url, pars, act, method, actargs, addtoken, **kwargs)
i += 1
# only ERequestFailed needs retry, other error still directly return
if result == ERequestFailed:
if i < tries:
# algo changed: delay more after each failure
delay = RetryDelayInSec * i
perr("Waiting {} seconds before retrying...".format(delay))
time.sleep(delay)
perr("Request Try #{} / {}".format(i + 1, tries))
else:
perr("Maximum number ({}) of tries failed.".format(tries))
if self.__quit_when_fail:
onexit(EMaxRetry)
break
else:
break
return result
def __get(self, url, pars, act, actargs = None, retry = True, addtoken = True, **kwargs):
return self.__request(url, pars, act, 'GET', actargs, retry, addtoken, **kwargs)
def __post(self, url, pars, act, actargs = None, retry = True, addtoken = True, **kwargs):
return self.__request(url, pars, act, 'POST', actargs, retry, addtoken, **kwargs)
def __replace_list_format(self, fmt, j):
output = fmt
for k, v in ByPy.ListFormatDict.iteritems():
output = output.replace(k, v(j))
return output
def __load_local_json(self):
try:
with open(TokenFilePath, 'rb') as infile:
self.__json = json.load(infile)
self.__access_token = self.__json['access_token']
self.pd("Token loaded:")
self.pd(self.__json)
return True
except IOError:
perr('Error while loading baidu pcs token:')
perr(traceback.format_exc())
return False
def __store_json_only(self, j):
self.__json = j
self.__access_token = self.__json['access_token']
self.pd("access token: " + self.__access_token)
self.pd("Authorize JSON:")
self.pd(self.__json)
try:
with open(TokenFilePath, 'wb') as outfile:
json.dump(self.__json, outfile)
return ENoError
except Exception:
perr("Exception occured while trying to store access token:\n" \
"Exception:\n{}".format(traceback.format_exc()))
return EFileWrite
def __store_json(self, r):
return self.__store_json_only(r.json())
def __server_auth_act(self, r, args):
return self.__store_json(r)
def __server_auth(self):
params = {
'client_id' : ApiKey,
'response_type' : 'code',
'redirect_uri' : 'oob',
'scope' : 'basic netdisk' }
pars = urllib.urlencode(params)
pr('Please visit:\n{}\nAnd authorize this app'.format(ServerAuthUrl + '?' + pars))
pr('Paste the Authorization Code here and then press [Enter] within 10 minutes.')
auth_code = raw_input().strip()
self.pd("auth_code: {}".format(auth_code))
pr('Authorizing, please be patient, it may take upto {} seconds...'.format(self.__timeout))
pars = {
'code' : auth_code,
'redirect_uri' : 'oob' }
result = self.__get(GaeRedirectUrl, pars, self.__server_auth_act, retry = False, addtoken = False)
if result != ENoError:
pr("I think you are WALLed, trying OpenShift server to auth...")
result = self.__get(OpenShiftRedirectUrl, pars, self.__server_auth_act, retry = True, addtoken = False)
if result != ENoError:
perr("Fatal: Both GAE & OpenShift server authorizations failed.")
return result
def __device_auth_act(self, r, args):
dj = r.json()
return self.__get_token(dj)
def __device_auth(self):
pars = {
'client_id' : ApiKey,
'response_type' : 'device_code',
'scope' : 'basic netdisk'}
return self.__get(DeviceAuthUrl, pars, self.__device_auth_act, addtoken = False)
def __auth(self):
if ServerAuth:
return self.__server_auth()
else:
return self.__device_auth()
def __get_token_act(self, r, args):
return self.__store_json(r)
def __get_token(self, deviceJson):
pr('Please visit:\n' + deviceJson['verification_url'] + \