forked from houtianze/bypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bypy.py
executable file
·2910 lines (2528 loc) · 93.1 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/env python
# encoding: utf-8
# === IMPORTANT ====
# NOTE: In order to support non-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.
# NOTE: 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: Dry run?
# TODO: Use batch functions for better performance
'''
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 and not sys.platform.startswith('win32'):
sysenc = SystemEncoding.upper()
if sysenc != 'UTF-8' and sysenc != 'UTF8':
err = "You MUST set system locale to 'UTF-8' to support unicode file names.\n" + \
"Current locale is '{}'".format(SystemEncoding)
ex = Exception(err)
print(err)
raise ex
if not SystemEncoding:
# ASSUME UTF-8 encoding, if for whatever reason,
# we can't get the default system encoding
print("*WARNING*: Cannot detect the system encoding, assume it's 'UTF-8'")
SystemEncoding = 'utf-8'
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
import socket
#from collections import OrderedDict
from os.path import expanduser
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
# https://urllib3.readthedocs.org/en/latest/security.html
# prevents the InsecureRequestWarning from appearing in rare case
try:
import urllib3
urllib3.disable_warnings()
except:
pass
# 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 = 20 * 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.
EIncorrectPythonVersion = 1
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 # File md5 not found, you should use upload API to upload the whole file.
# 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 = False
# - 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
if not SecretKey:
ServerAuth = True
# 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'
#UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)"
# According to seanlis@github, this User-Agent string affects the download.
UserAgent = None
# 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/'
vi = sys.version_info
if vi.major != 2 or vi.minor < 7:
print("Error: Incorrect Python version. " + \
"You need 2.7 or above (but not 3)")
sys.exit(EIncorrectPythonVersion)
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
requests_version = requests.__version__.split('.')
if int(requests_version[0]) < 1:
print("You Python Requests Library version is to lower than 1.\n" + \
"You can run 'pip install requests' to upgrade it.")
raise
# non-standard python library, needs 'pip install requesocks'
#import requesocks as requests # if you need socks proxy
# 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
# https://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
# https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
# 0 - black, 1 - red, 2 - green, 3 - yellow
# 4 - blue, 5 - magenta, 6 - cyan 7 - white
class TermColor:
NumOfColors = 8
Black, Red, Green, Yellow, Blue, Magenta, Cyan, White = range(NumOfColors)
Nil = -1
def colorstr(msg, fg, bg):
CSI = '\x1b['
fgs = ''
bgs = ''
if fg >=0 and fg <= 7:
fgs = str(fg + 30)
if bg >= 0 and bg <=7:
bgs = str(bg + 40)
cs = ';'.join([fgs, bgs]).strip(';')
if cs:
return CSI + cs + 'm' + msg + CSI + '0m'
else:
return msg
def prc(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
pr = prc
def prcolorc(msg, fg, bg):
if sys.stdout.isatty() and not sys.platform.startswith('win32'):
pr(colorstr(msg, fg, bg))
else:
pr(msg)
prcolor = prcolorc
def plog(tag, msg, showtime = True, showdate = False,
prefix = '', suffix = '', fg = TermColor.Nil, bg = TermColor.Nil):
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:
prcolor("{}{}".format(tag, prefix), fg, bg)
prcolor("{}{}".format(tag, msg), fg, bg)
if suffix:
prcolor("{}{}".format(tag, suffix), fg, bg)
def perr(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<E> ', msg, showtime, showdate, prefix, suffix, TermColor.Red)
def pwarn(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<W> ', msg, showtime, showdate, prefix, suffix, TermColor.Yellow)
def pinfo(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<I> ', msg, showtime, showdate, prefix, suffix, TermColor.Green)
def pdbg(msg, showtime = True, showdate = False, prefix = '', suffix = ''):
return plog('<D> ', msg, showtime, showdate, prefix, suffix, TermColor.Cyan)
def askc(msg, enter = True):
pr(msg)
if enter:
pr('Press [Enter] when you are done')
return raw_input()
ask = askc
# print progress
# https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console
def pprgrc(finish, total, start_time = None, existing = 0,
prefix = '', suffix = '', seg = 20):
# we don't want this goes to the log, so we use stderr
segth = seg * finish // total
percent = 100 * finish // total
eta = ''
now = time.time()
if start_time is not None and percent > 5 and finish > 0:
finishf = float(finish) - float(existing)
totalf = float(total)
remainf = totalf - float(finish)
elapsed = now - start_time
speed = human_speed(finishf / elapsed)
eta = 'ETA: ' + human_time(elapsed * remainf / finishf) + \
' (' + speed + ', ' + \
human_time(elapsed) + ' gone)'
msg = '\r' + prefix + '[' + segth * '=' + (seg - segth) * '_' + ']' + \
" {}% ({}/{})".format(percent, si_size(finish), si_size(total)) + \
' ' + eta + suffix
sys.stderr.write(msg + ' ') # space is used as a clearer
sys.stderr.flush()
pprgr = pprgrc
def si_size(num, precision = 3):
''' DocTests:
>>> si_size(1000)
u'1000B'
>>> si_size(1025)
u'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 human_time(seconds):
''' DocTests:
>>> human_time(0)
u''
>>> human_time(122.1)
u'2m2s'
>>> human_time(133)
u'2m13s'
>>> human_time(12345678)
u'20W2D21h21m18s'
'''
isec = int(seconds)
s = isec % 60
m = isec / 60 % 60
h = isec / 60 / 60 % 24
d = isec / 60 / 60 / 24 % 7
w = isec / 60 / 60 / 24 / 7
result = ''
for t in [ ('W', w), ('D', d), ('h', h), ('m', m), ('s', s) ]:
if t[1]:
result += str(t[1]) + t[0]
return result
def human_speed(speed, precision = 0):
''' DocTests:
'''
# https://stackoverflow.com/questions/15263597/python-convert-floating-point-number-to-certain-precision-then-copy-to-string/15263885#15263885
numfmt = '{{:.{}f}}'.format(precision)
if speed < OneK:
return numfmt.format(speed) + 'B/s'
elif speed < OneM:
return numfmt.format(speed / float(OneK)) + 'KB/s'
elif speed < OneG:
return numfmt.format(speed / float(OneM)) + 'MB/s'
elif speed < OneT:
return numfmt.format(speed / float(OneG)) + 'GB/s'
else:
return 'HAHA'
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
# seems os.path.join() doesn't handle Unicode well
def joinpath(first, second, sep = os.sep):
head = ''
if first:
head = first.rstrip(sep) + sep
tail = ''
if second:
tail = second.lstrip(sep)
return head + tail
def donothing():
pass
# 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)
p = joinpath(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:
# Linux can have file / folder names with '\\'?
if sys.platform.startswith('win32'):
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():
result.append(k)
if v.type == 'D':
for p in self.get(k).allpath():
result.append(k + '/' + p)
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,
retry = 5, timeout = None,
quit_when_fail = False,
listfile = None,
resumedownload = True,
extraupdate = lambda: (),
incregex = '',
ondup = '',
followlink = True,
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.__listfile = listfile
self.__resumedownload = resumedownload
self.__extraupdate = extraupdate
self.__incregex = incregex
self.__incregmo = re.compile(incregex)
if ondup and len(ondup) > 0:
self.__ondup = ondup[0].upper()
else:
self.__ondup = 'O' # O - Overwrite* S - Skip P - Prompt
self.__followlink = followlink;
self.Verbose = verbose
self.Debug = debug
# the prophet said: thou shalt initialize
self.__existing_size = 0
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 shalloverwrite(self, prompt):
if self.__ondup == 'S':
return False
elif self.__ondup == 'P':
ans = ask(prompt, False).upper()
if not ans.startswith('Y'):
return False
return True
def __print_error_json(self, r):
try:
dj = r.json()
if 'error_code' in dj and 'error_msg' in dj:
ec = dj['error_code']
et = dj['error_msg']
msg = ''
if ec == IEMD5NotFound:
pf = pinfo
msg = et
else:
pf = perr
msg = "Error code: {}\nError Description: {}".format(ec, et)
pf(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))
tb = traceback.format_exc()
if tb:
pr(tb)
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, dumpex = True, **kwargs):
result = ENoError
r = None
self.__extraupdate()
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':