forked from PeterDing/iScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pan.baidu.com.py
executable file
·3543 lines (3151 loc) · 126 KB
/
pan.baidu.com.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 python2
# vim: set fileencoding=utf8
import os
import sys
import functools
import requests
requests.packages.urllib3.disable_warnings() # disable urllib3's warnings https://urllib3.readthedocs.org/en/latest/security.html#insecurerequestwarning
from requests_toolbelt import MultipartEncoder
import urllib
import json
import cPickle as pk
import re
import time
import argparse
from random import SystemRandom
random = SystemRandom()
import select
import base64
import md5
import rsa
from zlib import crc32
import cStringIO
import signal
############################################################
# Defines that should never be changed
OneK = 1024
OneM = OneK * OneK
OneG = OneM * OneK
OneT = OneG * OneK
OneP = OneT * OneK
OneE = OneP * OneK
############################################################
# Default values
MinRapidUploadFileSize = 256 * OneK
DefaultSliceSize = 10 * OneM
MaxSliceSize = 2 * OneG
MaxSlicePieces = 1024
ENoError = 0
CIPHERS = [
"aes-256-cfb", "aes-128-cfb", "aes-192-cfb",
"aes-256-ofb", "aes-128-ofb", "aes-192-ofb",
"aes-128-ctr", "aes-192-ctr", "aes-256-ctr",
"aes-128-cfb8", "aes-192-cfb8", "aes-256-cfb8",
"aes-128-cfb1", "aes-192-cfb1", "aes-256-cfb1",
"bf-cfb", "camellia-128-cfb", "camellia-192-cfb",
"camellia-256-cfb", "cast5-cfb", "chacha20",
"idea-cfb", "rc2-cfb", "rc4-md5", "salsa20", "seed-cfb"
]
############################################################
# wget exit status
wget_es = {
0: "No problems occurred.",
2: "User interference.",
1<<8: "Generic error code.",
2<<8: "Parse error - for instance, when parsing command-line " \
"optio.wgetrc or .netrc...",
3<<8: "File I/O error.",
4<<8: "Network failure.",
5<<8: "SSL verification failure.",
6<<8: "Username/password authentication failure.",
7<<8: "Protocol errors.",
8<<8: "Server issued an error response."
}
############################################################
# file extensions
mediatype = [
".wma", ".wav", ".mp3", ".aac", ".ra", ".ram", ".mp2", ".ogg", \
".aif", ".mpega", ".amr", ".mid", ".midi", ".m4a", ".m4v", ".wmv", \
".rmvb", ".mpeg4", ".mpeg2", ".flv", ".avi", ".3gp", ".mpga", ".qt", \
".rm", ".wmz", ".wmd", ".wvx", ".wmx", ".wm", ".swf", ".mpg", ".mp4", \
".mkv", ".mpeg", ".mov", ".mdf", ".iso", ".asf", ".vob"
]
imagetype = [
".jpg", ".jpeg", ".gif", ".bmp", ".png", ".jpe", ".cur", ".svg", \
".svgz", ".tif", ".tiff", ".ico"
]
doctype = [
".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".vsd", ".txt", ".pdf", \
".ods", ".ots", ".odt", ".rtf", ".dot", ".dotx", ".odm", ".pps", ".pot", \
".xlt", ".xltx", ".csv", ".ppsx", ".potx", ".epub", ".apk", ".exe", \
".msi", ".ipa", ".torrent", ".mobi"
]
archivetype = [
".7z", ".a", ".ace", ".afa", ".alz", ".android", ".apk", ".ar", \
".arc", ".arj", ".b1", ".b1", ".ba", ".bh", ".bz2", ".cab", ".cab", \
".cfs", ".chm", ".cpio", ".cpt", ".cqm", ".dar", ".dd", ".dgc", ".dmg", \
".ear", ".ecc", ".eqe", ".exe", ".f", ".gca", ".gz", ".ha", ".hki", \
".html", ".ice", ".id", ".infl", ".iso", ".jar", ".kgb", ".lbr", \
".lha", ".lqr", ".lz", ".lzh", ".lzma", ".lzo", ".lzx", ".mar", ".ms", \
".net", ".package", ".pak", ".paq6", ".paq7", ".paq8", ".par", ".par2", \
".partimg", ".pea", ".pim", ".pit", ".qda", ".rar", ".rk", ".rz", \
".s7z", ".sda", ".sea", ".sen", ".sfark", ".sfx", ".shar", ".sit", \
".sitx", ".sqx", ".tar", ".tbz2", ".tgz", ".tlz", ".tqt", ".uc", \
".uc0", ".uc2", ".uca", ".ucn", ".ue2", ".uha", ".ur2", ".war", ".web", \
".wim", ".x", ".xar", ".xp3", ".xz", ".yz1", ".z", ".zip", ".zipx", \
".zoo", ".zpaq", ".zz"
]
s = '\x1b[%s;%sm%s\x1b[0m' # terminual color template
cookie_file = os.path.join(os.path.expanduser('~'), '.bp.cookies')
upload_datas_path = os.path.join(os.path.expanduser('~'), '.bp.pickle')
save_share_path = os.path.join(os.path.expanduser('~'), '.bp.ss.pickle')
headers = {
"Accept": "application/json, text/javascript, text/html, */*; q=0.01",
"Accept-Encoding":"gzip, deflate, sdch",
"Accept-Language":"en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2",
"Referer":"http://pan.baidu.com/disk/home",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Connection": "keep-alive",
}
ss = requests.session()
ss.headers.update(headers)
def import_shadowsocks():
try:
global encrypt
from shadowsocks import encrypt
except ImportError:
print s % (1, 93, ' !! you don\'t install shadowsocks for python2.')
print s % (1, 97, ' install shadowsocks:')
print s % (1, 92, ' pip2 install shadowsocks')
sys.exit(1)
def get_abspath(pt):
if '~' == pt[0]:
path = os.path.expanduser(pt)
else:
path = os.path.abspath(pt)
if os.path.exists(path):
return path
else:
print s % (1, 91, ' !! path isn\'t existed.'), pt
return None
def make_server_path(cwd, path):
def cd(cwd, part):
if part == '..':
cwd = os.path.dirname(cwd)
elif part == '.':
pass
elif part == '':
pass
elif part == '...':
cwd = os.path.dirname(cwd)
cwd = os.path.dirname(cwd)
else:
cwd = os.path.join(cwd, part)
return cwd
if not path or path[0] == '/':
return path
else:
parts = path.split('/')
for p in parts:
cwd = cd(cwd, p)
return cwd
def fast_pcs_server(j):
if 'fs' not in args.type_:
return j
do = lambda dlink: \
re.sub(r'://[^/]+?/', '://www.baidupcs.com/', dlink)
#re.sub(r'://[^/]+?/', '://c.pcs.baidu.com/', dlink)
if isinstance(j, dict) and j.get('info') and len(j['info']) > 0:
for i in xrange(len(j['info'])):
if j['info'][i].get('dlink'):
j['info'][i]['dlink'] = do(j['info'][i]['dlink'])
else:
j = do(j)
return j
def is_wenxintishi(dlink):
while True:
try:
res = ss.head(dlink)
break
except requests.exceptions.ConnectionError:
time.sleep(2)
location = res.headers.get('location', '')
if 'wenxintishi' in location:
return True
else:
return False
# https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
def sizeof_fmt(num):
for x in ['B','KB','MB','GB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
return "%3.1f%s" % (num, 'TB')
def print_process_bar(point, total, slice_size,
start_time=None, pre='', suf='', msg=''):
length = 20
nowpoint = point / (total + 0.0)
percent = round(100 * nowpoint, 1)
now = time.time()
speed = sizeof_fmt(slice_size / (now - start_time)) + '/s'
t = int(nowpoint*length)
msg = '\r' + ' '.join([pre, '|%s%s|' % ('='*t, ' '*(length - t)), \
str(percent) + '%', speed, msg, suf])
sys.stdout.write(msg)
sys.stdout.flush()
return now
class panbaiducom_HOME(object):
def __init__(self):
self._download_do = self._play_do if args.play else self._download_do
self.ondup = 'overwrite'
self.accounts = self._check_cookie_file()
self.dsign = None
self.timestamp = None
self.highlights = []
if any([args.tails, args.heads, args.includes]):
for tail in args.tails:
self.highlights.append({'text': tail.decode('utf8', 'ignore'),
'is_regex': 0})
for head in args.heads:
self.highlights.append({'text': head.decode('utf8', 'ignore'),
'is_regex': 0})
for include in args.includes:
self.highlights.append({'text': include.decode('utf8', 'ignore'),
'is_regex': 1})
if 'ec' in args.type_ or 'dc' in args.type_ or args.comd == 'dc':
import_shadowsocks()
def _request(self, method, url, action, **kwargs):
i = 0
while i < 3:
i += 1
response = ss.request(method, url, **kwargs)
if not (response.ok is True and response.status_code == 200):
continue
else:
return response
self.save_cookies()
print s % (1, 91, ' ! [{}] Server error'.format(action))
sys.exit()
@staticmethod
def _check_cookie_file():
def correct_do():
with open(cookie_file, 'wb') as g:
pk.dump({}, g)
print s % (1, 97, ' please login')
return
if not os.path.exists(cookie_file):
correct_do()
return {}
try:
j = pk.load(open(cookie_file))
except:
correct_do()
return {}
if type(j) != type({}):
correct_do()
return {}
for i in j:
if type(j[i]) != type({}):
del j[i]
else:
if not j[i].get('cookies'):
del j[i]
return j
def init(self):
if self.accounts:
j = self.accounts
u = [u for u in j if j[u]['on']]
if u:
user = u[0]
self.user = user
self.cwd = j[user]['cwd'] if j[user].get('cwd') else '/'
ss.cookies.update(j[user]['cookies'])
else:
print s % (1, 91, ' !! no account is online, please login or userchange')
sys.exit(1)
if not self.check_login():
print s % (1, 91, ' !! cookie is invalid, please login.'), u[0]
del j[u[0]]
with open(cookie_file, 'w') as g:
pk.dump(j, g)
sys.exit(1)
else:
print s % (1, 97, ' no account, please login')
sys.exit(1)
@staticmethod
def save_img(url, ext):
path = os.path.join(os.path.expanduser('~'), 'vcode.%s' % ext)
with open(path, 'w') as g:
res = ss.get(url)
data = res.content
g.write(data)
print " ++ 验证码已保存至", s % (1, 97, path)
input_code = raw_input(s % (2, 92, " 输入验证码: "))
return input_code
def check_login(self):
html_string = self._request('GET', 'http://pan.baidu.com/disk/home', 'check_login').content
if '"loginstate":1' not in html_string:
print s % (1, 91, ' -- check_login fail\n')
return False
else:
#print s % (1, 92, ' -- check_login success\n')
#self.get_dsign()
#self.save_cookies()
return True
def login(self, username, password):
print s % (1, 97, '\n -- login')
# error_message: at _check_account_exception from
# https://github.com/ly0/baidupcsapi/blob/master/baidupcsapi/api.py
login_error_msg = {
'-1': '系统错误, 请稍后重试',
'1': '输入的帐号格式不正确',
'3': '验证码不存在或已过期,请重新输入',
'4': '输入的帐号或密码有误',
'5': '请重新登录',
'6': '验证码输入错误',
'16': '帐号因安全问题已被限制登录',
'257': '需要验证码',
'100005': '系统错误, 请稍后重试',
'120016': '未知错误 120016',
'120019': '近期登录次数过多, 请先通过 passport.baidu.com 解除锁定',
'120021': '登录失败,重新登录',
'500010': '登录过于频繁,请24小时后再试',
'400031': '账号异常',
'401007': '手机号关联了其他帐号,请选择登录'
}
self._request('GET', 'http://www.baidu.com', 'login')
# Get token
# token = self._get_bdstoken()
resp = self._request('GET', 'https://passport.baidu.com/v2/api/?getapi&tpl=netdisk'
'&apiver=v3&tt={}&class=login&logintype=basicLogin'.format(int(time.time())),
'login')
_json = json.loads(resp.content.replace('\'', '"'))
if _json['errInfo']['no'] != "0":
print s % (1, 91, ' ! Can\'t get token')
sys.exit(1)
token = _json['data']['token']
code_string = _json['data']['codeString']
# get publickey
# url = ('https://passport.baidu.com/v2/getpublickey?&token={}'
# '&tpl=netdisk&apiver=v3&tt={}').format(token, int(time.time()))
# r = ss.get(url)
# j = json.loads(r.content.replace('\'', '"'))
# pubkey = j['pubkey']
# key = rsa.PublicKey.load_pkcs1_openssl_pem(pubkey)
# password_encoded = base64.b64encode(rsa.encrypt(password, key))
# rsakey = j['key']
# Construct post body
verifycode = ''
while True:
data = {
"staticpage": "http://pan.baidu.com/res/static/thirdparty/pass_v3_jump.html",
"charset": "utf-8",
"token": token,
"tpl": "netdisk",
"subpro": "",
"apiver": "v3",
"tt": int(time.time()),
"codestring": code_string,
"safeflg": "0",
"u": "http://pan.baidu.com/",
"isPhone": "",
"quick_user": "0",
"logintype": "basicLogin",
"logLoginType": "pc_loginBasic",
"idc": "",
"loginmerge": "true",
"username": username,
"password": password,
"verifycode": verifycode,
"mem_pass": "on",
"rsakey": "",
"crypttype": "",
"ppui_logintime": "2602",
"callback": "parent.bd__pcbs__ahhlgk",
}
# Post!
# XXX : do not handle errors
url = 'https://passport.baidu.com/v2/api/?login'
r = ss.post(url, data=data)
# Callback for verify code if we need
#code_string = r.content[r.content.index('(')+1:r.content.index(')')]
errno = re.search(r'err_no=(\d+)', r.content).group(1)
if ss.cookies.get('BDUSS'):
# ss.get("http://pan.baidu.com/disk/home")
break
elif errno in ('257', '3', '6'):
print s % (1, 91, ' ! Error %s:' % errno), \
login_error_msg[errno]
t = re.search('codeString=(.+?)&', r.content)
code_string = t.group(1) if t else ""
vcurl = 'https://passport.baidu.com/cgi-bin/genimage?' + code_string
verifycode = self.save_img(vcurl, 'jpg') if code_string != "" else ""
data['codestring'] = code_string
data['verifycode'] = verifycode
#self.save_cookies()
else:
print s % (1, 91, ' ! Error %s:' % errno), \
login_error_msg.get(errno, "unknow, please feedback to author")
sys.exit(1)
def save_cookies(self, username=None, on=0, tocwd=False):
if not username: username = self.user
accounts = self.accounts
accounts[username] = accounts.get(username, {})
accounts[username]['cookies'] = \
accounts[username].get('cookies', ss.cookies.get_dict())
accounts[username]['on'] = on
quota = self._get_quota()
capacity = '%s/%s' % (sizeof_fmt(quota['used']), sizeof_fmt(quota['total']))
accounts[username]['capacity'] = capacity
if hasattr(self, 'cwd'):
if not accounts[username].get('cwd'):
accounts[username]['cwd'] = '/'
if tocwd: accounts[username]['cwd'] = self.cwd
else:
accounts[username]['cwd'] = '/'
for u in accounts:
if u != username and on:
accounts[u]['on'] = 0
with open(cookie_file, 'w') as g:
pk.dump(accounts, g)
def _get_bdstoken(self):
if hasattr(self, 'bdstoken'):
return self.bdstoken
resp = self._request('GET', 'http://pan.baidu.com/disk/home',
'_get_bdstoken')
html_string = resp.content
mod = re.search(r'"bdstoken":"(.+?)"', html_string)
if mod:
self.bdstoken = mod.group(1)
return self.bdstoken
else:
print s % (1, 91, ' ! Can\'t get bdstoken')
sys.exit(1)
# self.bdstoken = md5.new(str(time.time())).hexdigest()
#def _sift(self, fileslist, name=None, size=None, time=None, head=None, tail=None, include=None, exclude=None):
def _sift(self, fileslist, **arguments):
"""
a filter for time, size, name, head, tail, include, exclude, shuffle
support regular expression
"""
# for shuffle
if 's' in args.type_:
random.shuffle(fileslist)
return fileslist
# for time
elif arguments.get('name'):
reverse = None
if arguments['name'] == 'reverse':
reverse = True
elif arguments['name'] == 'no_reverse':
reverse = False
fileslist = sorted(fileslist, key=lambda k: k['server_filename'],
reverse=reverse)
# for size
elif arguments.get('size'):
reverse = None
if arguments['size'] == 'reverse':
reverse = True
elif arguments['size'] == 'no_reverse':
reverse = False
fileslist = sorted(fileslist, key=lambda k: k['size'],
reverse=reverse)
# for time
elif arguments.get('time'):
reverse = None
if arguments['time'] == 'reverse':
reverse = True
elif arguments['time'] == 'no_reverse':
reverse = False
fileslist = sorted(fileslist, key=lambda k: k['server_mtime'],
reverse=reverse)
# for head, tail, include, exclude
heads = args.heads
tails = args.tails
includes = args.includes
excludes = args.excludes
keys1, keys2, keys3, keys4 = [], [], [], []
if heads or tails or includes or excludes:
tdict = {
fileslist[i]['server_filename'] : i for i in xrange(len(fileslist))
}
for head in heads:
keys1 += [
i for i in tdict.keys()
if i.lower().startswith(
head.decode('utf8', 'ignore').lower()
)
]
for tail in tails:
keys2 += [
i for i in tdict.keys()
if i.lower().endswith(
tail.decode('utf8', 'ignore').lower()
)
]
for include in includes:
keys3 += [
i for i in tdict.keys()
if re.search(
include.decode('utf8', 'ignore'), i, flags=re.I
)
]
for exclude in excludes:
keys4 += [
i for i in tdict.keys()
if not re.search(
exclude.decode('utf8', 'ignore'), i, flags=re.I
)
]
# intersection
keys = [set(i) for i in [keys1, keys2, keys3, keys4] if i]
if len(keys) > 1:
tkeys = keys[0]
for i in keys:
tkeys &= i
keys = tkeys
elif len(keys) == 1:
keys = keys[0]
elif len(keys) == 0:
keys = []
return []
indexs = [tdict[i] for i in keys]
indexs.sort()
fileslist = [fileslist[i] for i in indexs]
dirs = [i for i in fileslist if i['isdir']]
t, tt = [], []
if 'e' in args.type_:
for i in dirs:
d = i['path'].encode('utf8')
j = self._get_file_list('name', None, d, 1, all=False)
if not j['list']:
t.append(i)
else:
tt.append(i)
if 'e' in args.type_: dirs = t
if 'ne' in args.type_: dirs = tt
files = [i for i in fileslist if not i['isdir']]
if arguments.get('desc') == 1:
dirs.reverse()
files.reverse()
if 'f' in args.type_:
fileslist = files
elif 'd' in args.type_:
fileslist = dirs
else:
fileslist = dirs + files
return fileslist
def _get_path(self, url):
t = re.search(r'path=(.+?)(&|$)', url)
if t:
t = t.group(1)
t = urllib.unquote_plus(t)
t = urllib.unquote_plus(t)
return t
else:
return url
def _get_quota(self):
url = 'http://pan.baidu.com/api/quota'
resp = self._request('GET', url, '_get_quota')
j = resp.json()
if j['errno'] != 0:
print s % (1, 92, ' !! Error at _get_quota')
sys.exit(1)
else:
return j
def _get_file_list(self, order, desc, dir_, num, all=True):
t = {'Referer':'http://pan.baidu.com/disk/home'}
theaders = headers
theaders.update(t)
p = {
"channel": "chunlei",
"clienttype": 0,
"web": 1,
"showempty": 1,
"num": num, ## max amount is 10000
"t": int(time.time()*1000),
"dir": dir_,
"page": 1,
"desc": 1, ## reversely
"order": order, ## sort by name, or size, time
"_": int(time.time()*1000),
# "bdstoken": self._get_bdstoken(),
}
if not desc: del p['desc']
url = 'http://pan.baidu.com/api/list'
infos = []
while True:
# r = ss.get(url, params=p, headers=theaders)
r = ss.get(url, params=p)
j = r.json()
if j['errno'] != 0:
print s % (1, 91, ' error: _get_file_list'), '--', j
sys.exit(1)
else:
infos += j['list']
if not all: return j
if len(infos) == num:
p['page'] += 1
else:
j['list'] = infos
return j
def _get_dsign(self):
# if self.dsign is not None:
# return None
url = 'http://pan.baidu.com/disk/home'
r = self._request('GET', url, '_get_dsign')
html = r.content
sign1 = re.search(r'"sign1":"(.+?)"', html).group(1)
sign3 = re.search(r'"sign3":"(.+?)"', html).group(1)
timestamp = re.search(r'"timestamp":(\d+)', html).group(1)
# following javascript code from http://pan.baidu.com/disk/home
#yunData.sign2 = function s(j, r) {
# var a = [];
# var p = [];
# var o = \x22\ x22;
# var v = j.length;
# for (var q = 0; q < 256; q++) {
# a[q] = j.substr((q % v), 1).charCodeAt(0);
# p[q] = q
# }
# for (var u = q = 0; q < 256; q++) {
# u = (u + p[q] + a[q]) % 256;
# var t = p[q];
# p[q] = p[u];
# p[u] = t
# }
# for (var i = u = q = 0; q < r.length; q++) {
# i = (i + 1) % 256;
# u = (u + p[i]) % 256;
# var t = p[i];
# p[i] = p[u];
# p[u] = t;
# k = p[((p[i] + p[u]) % 256)];
# o += String.fromCharCode(r.charCodeAt(q) ^ k)
# }
# return o
#};
def sign2(j, r):
a = []
p = []
o = ''
v = len(j)
for q in xrange(256):
a.append(ord(j[q % v]))
p.append(q)
u = 0
for q in xrange(256):
u = (u + p[q] + a[q]) % 256
t = p[q]
p[q] = p[u]
p[u] = t
i = 0
u = 0
for q in xrange(len(r)):
i = (i + 1) % 256
u = (u + p[i]) % 256
t = p[i]
p[i] = p[u]
p[u] = t
k = p[((p[i] + p[u]) % 256)]
o += chr(ord(r[q]) ^ k)
return base64.b64encode(o)
self.dsign = sign2(sign3, sign1)
self.timestamp = timestamp
def _get_dlink(self, path):
dlink = ('http://c.pcs.baidu.com/rest/2.0/pcs/file?method=download'
'&app_id=250528&path={}').format(urllib.quote(path))
dlink = fast_pcs_server(dlink)
return dlink
def _get_dlink3(self, fs_id):
while True:
dsign, timestamp = self._get_dsign()
params = {
"channel": "chunlei",
"clienttype": 0,
"app_id": "250528",
"web": 1,
# "bdstoken": self._get_bdstoken(),
"sign": self.dsign,
"timestamp": self.timestamp,
"fidlist": '[{}]'.format(fs_id),
"type": "dlink",
}
url = 'http://pan.baidu.com/api/download'
r = ss.get(url, params=params)
j = r.json()
print(j)
if j['errno'] == 0:
dlink = j['dlink'][0]['dlink'].encode('utf8')
# dlink = re.sub(r'prisign=.+?(&|$)', r'prisign=unknow\1', dlink)
# dlink = dlink.replace('chkbd=0', 'chkbd=1')
# dlink = dlink.replace('chkv=0', 'chkv=1')
dlink = fast_pcs_server(dlink)
return dlink
else:
print s % (1, 91, ' !! Error at _get_dlink, can\'t get dlink')
continue
def _get_dlink2(self, i):
j = self._meta([i['path'].encode('utf8')], dlink=1)
if j:
return j['info'][0]['dlink'].encode('utf8')
else:
print s % (1, 91, ' !! Error at _get_dlink2')
sys.exit(1)
def _get_m3u8(self, info):
p = {
"method": "streaming",
"path": info['path'].encode('utf8'),
"type": "M3U8_AUTO_720",
"app_id": "250528",
#"bdstoken": self._get_bdstoken(),
}
url = "https://pcs.baidu.com/rest/2.0/pcs/file"
r = ss.get(url, params=p, verify=VERIFY)
m3u8 = r.content
if '#EXTM3U' not in m3u8[:7]:
return None
#m3u8 = fast_pcs_server(m3u8)
return m3u8
def download(self, paths):
for path in paths:
path = self._get_path(path) if path[0] != '/' else path
path = make_server_path(self.cwd, path)
base_dir = '' if os.path.split(path)[0] == '/' \
else os.path.split(path)[0]
meta = self._meta([path], dlink=0)
if meta:
if meta['info'][0]['isdir']:
dir_loop = [path]
for d in dir_loop:
j = self._get_file_list('name', None, d, 10000)
if j['list']:
if args.recursive:
for i in j['list']:
dir_loop.append(i['path'].encode('utf8')) \
if i['isdir'] else None
if args.play:
j['list'] = [
i for i in j['list'] \
if not i['isdir'] \
and os.path.splitext(
i['server_filename']
)[-1].lower() in mediatype]
if 's' in args.type_:
j['list'] = self._sift(j['list'])
if args.heads or args.tails or args.includes \
or args.excludes:
j['list'] = self._sift(j['list'])
total_file = len([i for i in j['list'] \
if not i['isdir']])
if args.from_ - 1:
j['list'] = j['list'][args.from_-1:] \
if args.from_ else j['list']
nn = args.from_
for i in j['list']:
if i['isdir']: continue
t = i['path'].encode('utf8')
t = t.replace(base_dir, '')
t = t[1:] if t[0] == '/' else t
t = os.path.join(os.getcwd(), t)
i['dlink'] = self._get_dlink(i['path'].encode('utf8'))
infos = {
'file': t,
'path': i['path'].encode('utf8'),
'dir_': os.path.split(t)[0],
'dlink': i['dlink'].encode('utf8'),
'm3u8': self._get_m3u8(i) \
if 'm3' in args.type_ else None,
'name': i['server_filename'].encode('utf8'),
'size': i['size'],
'nn': nn,
'total_file': total_file
}
nn += 1
self._download_do(infos)
if 'dc' in args.type_:
self.decrypt([infos['file']])
elif not meta['info'][0]['isdir']:
t = os.path.join(
os.getcwd(), meta['info'][0]['server_filename'].encode('utf8')
)
infos = {
'file': t,
'path': meta['info'][0]['path'].encode('utf8'),
'dir_': os.path.split(t)[0],
'dlink': self._get_dlink(meta['info'][0]['path'].encode('utf8')),
'm3u8': self._get_m3u8(meta['info'][0]) \
if 'm3' in args.type_ else None,
# 'dlink': meta['info'][0]['dlink'].encode('utf8'),
'name': meta['info'][0]['server_filename'].encode('utf8'),
'size': meta['info'][0]['size'],
}
if args.play:
if not os.path.splitext(infos['name'])[-1].lower() in mediatype:
continue
self._download_do(infos)
if 'dc' in args.type_:
self.decrypt([infos['file']])
else:
print s % (1, 91, ' !! path is not existed.\n'), \
' --------------\n ', path
@staticmethod
def _download_do(infos):
## make dirs
if not os.path.exists(infos['dir_']):
os.makedirs(infos['dir_'])
else:
if os.path.exists(infos['file']):
return
num = random.randint(0, 7) % 8
col = sizeof_fmt(infos['size']) + ' # ' + s % (2, num + 90, infos['path']) \
if args.view else s % (2, num + 90, infos['name'])
infos['nn'] = infos['nn'] if infos.get('nn') else 1
infos['total_file'] = infos['total_file'] if infos.get('total_file') else 1
print '\n ++ download: #', s % (1, 97, infos['nn']), '/', \
s % (1, 97, infos['total_file']), '#', col
if '8s' in args.type_ and is_wenxintishi(infos['dlink']):
print s % (1, 93, ' !! 百度8秒 !!')
return
cookie = 'Cookie: ' + '; '.join([
k + '=' + v for k, v in ss.cookies.get_dict().items()])
if args.aria2c:
quiet = ' --quiet=true' if args.quiet else ''
taria2c = ' -x %s -s %s' % (args.aria2c, args.aria2c)
tlimit = ' --max-download-limit %s' % args.limit if args.limit else ''
#'--user-agent "netdisk;4.4.0.6;PC;PC-Windows;6.2.9200;WindowsBaiduYunGuanJia" ' \
#'--user-agent "netdisk;5.3.1.3;PC;PC-Windows;5.1.2600;WindowsBaiduYunGuanJia" ' \
#'--header "Referer:http://pan.baidu.com/disk/home " ' \
cmd = 'aria2c -c -k 1M%s%s%s ' \
'-o "%s.tmp" -d "%s" ' \
'--user-agent "%s" ' \
'--header "%s" ' \
'"%s"' \
% (quiet, taria2c, tlimit, infos['name'],
infos['dir_'], headers['User-Agent'], cookie, infos['dlink'])
else:
quiet = ' -q' if args.quiet else ''
tlimit = ' --limit-rate %s' % args.limit if args.limit else ''
cmd = 'wget -c%s%s ' \
'-O "%s.tmp" ' \
'--user-agent "%s" ' \
'--header "Referer:http://pan.baidu.com/disk/home" ' \
'--header "%s" ' \
'"%s"' \
% (quiet, tlimit, infos['file'],
headers['User-Agent'], cookie, infos['dlink'])
status = os.system(cmd)
exit = True
if 'ie' in args.type_:
if status == 2 and not args.aria2c:
pass
elif status == (7 << 8) and args.aria2c:
pass
else:
exit = False
if status != 0: # other http-errors, such as 302.
#wget_exit_status_info = wget_es[status]
print('\n\n ---### \x1b[1;91mEXIT STATUS\x1b[0m ==> '\
'\x1b[1;91m%d\x1b[0m ###--- \n\n' % status)
print s % (1, 91, ' ===> '), cmd
if exit: sys.exit(1)
else:
os.rename('%s.tmp' % infos['file'], infos['file'])
@staticmethod
def _play_do(infos):
num = random.randint(0, 7) % 8
col = sizeof_fmt(infos['size']) \
+ ' # ' \
+ s % (2, num + 90, infos['path']) \
if args.view else s % (2, num + 90, infos['name'])
infos['nn'] = infos['nn'] if infos.get('nn') else 1
infos['total_file'] = infos['total_file'] \
if infos.get('total_file') else 1
print '\n ++ play%s: #' \
% (s % (1, 92, ' m3u8') if infos.get('m3u8') else ''), \
s % (1, 97, infos['nn']), '/', \
s % (1, 97, infos['total_file']), '#', col
if is_wenxintishi(infos['dlink']):
print s % (1, 93, ' !! 百度8秒 !!')
return
if infos.get('m3u8'):
with open('/tmp/tmp_pan.baidu.com.py.m3u8', 'w') as g:
g.write(infos['m3u8'])
infos['dlink'] = '/tmp/tmp_pan.baidu.com.py.m3u8'
cookie = 'Cookie: ' + '; '.join([
k + '=' + v for k, v in ss.cookies.get_dict().items()])
quiet = ' --really-quiet' if args.quiet else ''
cmd = 'mpv%s --no-ytdl --cache-default 20480 --cache-secs 120 ' \
'--http-header-fields "%s" ' \
'--http-header-fields "%s" ' \
'"%s"' \
% (quiet, headers['User-Agent'], cookie, infos['dlink'])
os.system(cmd)
timeout = 1
ii, _, _ = select.select([sys.stdin], [], [], timeout)