Skip to content
This repository has been archived by the owner on Oct 6, 2024. It is now read-only.

Master #49

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 82 additions & 44 deletions baidupcsapi/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import random
import base64
from hashlib import sha1, md5
from urllib import urlencode, quote
from urllib.parse import urlencode, quote
from zlib import crc32
from requests_toolbelt import MultipartEncoder
import requests
Expand Down Expand Up @@ -99,8 +99,8 @@ def wrapper(*args, **kwargs):
ret = func(*args, **kwargs)
if type(ret) == requests.Response:
try:
foo = json.loads(ret.content)
if foo.has_key('errno') and foo['errno'] == -6:
foo = json.loads(ret.content.decode())
if ('errno' in foo) and foo['errno'] == -6:
logging.debug(
'Offline, deleting cookies file then relogin.')
path = '.{0}.cookies'.format(args[0].username)
Expand Down Expand Up @@ -156,7 +156,7 @@ def get_fastest_pcs_server(self):
"""
url = 'http://pcs.baidu.com/rest/2.0/pcs/file?app_id=250528&method=locateupload'
ret = requests.get(url).content
foo = json.loads(ret)
foo = json.loads(ret.decode())
return foo['host']

def set_pcs_server(self, server):
Expand Down Expand Up @@ -192,21 +192,22 @@ def _initiate(self):
self.user['token'] = self._get_token()

def _save_cookies(self):
#liuxin 将baidukey写入cookies
cookies_file = '.{0}.cookies'.format(self.username)
with open(cookies_file, 'w') as f:
with open(cookies_file, 'wb') as cookies_file:
pickle.dump(
requests.utils.dict_from_cookiejar(self.session.cookies), f)
requests.utils.dict_from_cookiejar(self.session.cookies), cookies_file)

def _load_cookies(self):
#liuxin 读取cookies中的baidukey
cookies_file = '.{0}.cookies'.format(self.username)
logging.debug('cookies file:' + cookies_file)
if os.path.exists(cookies_file):
logging.debug('%s cookies file has already existed.' %
self.username)
with open(cookies_file) as cookies_file:
with open(cookies_file,'rb') as cookies_file:
cookies = requests.utils.cookiejar_from_dict(
pickle.load(cookies_file))
logging.debug(str(cookies))
self.session.cookies = cookies
self.user['BDUSS'] = self.session.cookies['BDUSS']
return True
Expand All @@ -216,8 +217,9 @@ def _load_cookies(self):
def _get_token(self):
# Token
ret = self.session.get(
'https://passport.baidu.com/v2/api/?getapi&tpl=mn&apiver=v3&class=login&tt=%s&logintype=dialogLogin&callback=0' % int(time.time())).text.replace('\'', '\"')
foo = json.loads(ret)
'https://passport.baidu.com/v2/api/?getapi&tpl=netdisk'
'&apiver=v3&tt={}&class=login&logintype=basicLogin'.format(int(time.time())))
foo = json.loads(ret.content.decode().replace('\'', '"'))
logging.info('token %s' % foo['data']['token'])
return foo['data']['token']

Expand All @@ -232,63 +234,99 @@ def _get_captcha(self, code_string):

def show_captcha(self, url_verify_code):
print(url_verify_code)
verify_code = raw_input('open url aboved with your web browser, then input verify code > ')
verify_code = input('open url aboved with your web browser, then input verify code > ')

return verify_code

def _get_publickey(self):
url = 'https://passport.baidu.com/v2/getpublickey?token=' + \
self.user['token']
content = self.session.get(url).content
jdata = json.loads(content.replace('\'','"'))
jdata = json.loads(content.decode().replace('\'','"'))
return (jdata['pubkey'], jdata['key'])

def _login(self):
# Login
#code_string, captcha = self._get_captcha()

captcha = ''
code_string = ''
pubkey, rsakey = self._get_publickey()
key = rsa.PublicKey.load_pkcs1_openssl_pem(pubkey)
password_rsaed = base64.b64encode(rsa.encrypt(self.password, key))
password_rsaed = base64.b64encode(rsa.encrypt(self.password.encode('utf-8'), key))
isCheck=False
while True:
login_data = {'staticpage': 'http://www.baidu.com/cache/user/html/v3Jump.html',
'charset': 'UTF-8',
'token': self.user['token'],
'tpl': 'pp',
'subpro': '',
'apiver': 'v3',
'tt': str(int(time.time())),
'codestring': code_string,
'isPhone': 'false',
'safeflg': '0',
'u': 'https://passport.baidu.com/',
'quick_user': '0',
'logLoginType': 'pc_loginBasic',
'loginmerge': 'true',
'logintype': 'basicLogin',
'username': self.username,
'password': password_rsaed,
'verifycode': captcha,
'mem_pass': 'on',
'rsakey': str(rsakey),
'crypttype': 12,
'ppui_logintime': '50918',
'callback': 'parent.bd__pcbs__oa36qm'}

login_data = {
# 'staticpage': 'http://www.baidu.com/cache/user/html/v3Jump.html',
# 'charset': 'UTF-8',
# 'token': self.user['token'],
# 'tpl': 'pp',
# 'subpro': '',
# 'apiver': 'v3',
# 'tt': str(int(time.time())),
# 'codestring': code_string,
# 'isPhone': 'false',
# 'safeflg': '0',
# 'u': 'https://passport.baidu.com/',
# 'quick_user': '0',
# 'logLoginType': 'pc_loginBasic',
# 'loginmerge': 'true',
# 'logintype': 'basicLogin',
# 'username': self.username,
# 'password': password_rsaed,
# 'verifycode': captcha,
# 'mem_pass': 'on',
# 'rsakey': str(rsakey),
# 'crypttype': 12,
# 'ppui_logintime': '50918',
# 'callback': 'parent.bd__pcbs__oa36qm'
"staticpage": "http://pan.baidu.com/res/static/thirdparty/pass_v3_jump.html",
"charset": "utf-8",
"token": self.user['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": self.username,
"password": self.password,
"verifycode": captcha,
"mem_pass": "on",
"rsakey": str(rsakey),
"crypttype": "",
"ppui_logintime": "2602",
"callback": "parent.bd__pcbs__ahhlgk",
}
# if captcha=='':
# del login_data['verifycode']
result = self.session.post(
'https://passport.baidu.com/v2/api/?login', data=login_data)

if self.user['token'].find('the fisrt two args should be string')!=-1:
self._initiate()
break

# 是否需要验证码
if 'err_no=257' in result.content or 'err_no=6' in result.content:
code_string = re.findall('codeString=(.*?)&', result.content)[0]
if 'err_no=257' in result.content.decode() or 'err_no=6' in result.content.decode():
code_string = re.findall('codeString=(.*?)&', result.content.decode())[0]
logging.debug('need captcha, codeString=' + code_string)
captcha = self._get_captcha(code_string)
continue

isCheck=True
break

# check exception
self._check_account_exception(result.content)
if isCheck:
self._check_account_exception(result.content)

if not result.ok:
raise LoginFailed('Logging failed.')
Expand All @@ -304,7 +342,7 @@ def _login(self):
self._save_cookies()

def _check_account_exception(self, content):
err_id = re.findall('err_no=([\d]+)', content)[0]
err_id = re.findall('err_no=([\d]+)', content.decode())[0]

if err_id == '0':
return
Expand Down Expand Up @@ -332,7 +370,7 @@ def _check_account_exception(self, content):

def _params_utf8(self, params):
for k, v in params.items():
if isinstance(v, unicode):
if isinstance(v, str):
params[k] = v.encode('utf-8')

@check_login
Expand Down Expand Up @@ -680,7 +718,7 @@ def get_url(dlink):
if not hasattr(self, 'dsign'):
self.get_sign()

if isinstance(remote_path, str) or isinstance(remote_path, unicode):
if isinstance(remote_path, bytes) or isinstance(remote_path, str):
remote_path = [remote_path]

file_list = []
Expand Down Expand Up @@ -1065,7 +1103,7 @@ def rename(self, rename_pair_list, **kwargs):
}

url = 'http://{0}/api/filemanager'.format(BAIDUPAN_SERVER)
print '请求url', url
print('请求url', url)
logging.debug('rename ' + str(data) + 'URL:' + url)
return self._request('filemanager', 'rename', url=url, data=data, extra_params=params, **kwargs)

Expand Down