Skip to content
This repository has been archived by the owner on Mar 24, 2020. It is now read-only.

Commit

Permalink
优化 cookie 加载流程
Browse files Browse the repository at this point in the history
  • Loading branch information
wizardforcel committed Mar 6, 2020
1 parent 43f0546 commit 9ffb362
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 28 deletions.
15 changes: 5 additions & 10 deletions BiliDriveEx/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ def login_handle(args):
info = api.get_user_info()
if info: log_info(info)
else: log("用户信息获取失败")
with open(os.path.join(bundle_dir, "cookies.json"), "w", encoding="utf-8") as f:
f.write(json.dumps(api.get_cookies(), ensure_ascii=False, indent=2))


def upload_handle(args):
def core(index, block):
Expand All @@ -69,7 +68,7 @@ def core(index, block):
for _ in range(10):
if terminate_flag.is_set():
return
response = api.image_upload(full_block, cookies)
response = api.image_upload(full_block)
if response:
if response['code'] == 0:
url = response['data']['image_url']
Expand Down Expand Up @@ -109,12 +108,8 @@ def core(index, block):
log(f"文件已于{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(history[first_4mb_sha1]['time']))}上传, 共有{len(history[first_4mb_sha1]['block'])}个分块")
log(f"META URL -> {api.meta_string(url)}")
return url
try:
with open(os.path.join(bundle_dir, "cookies.json"), "r", encoding="utf-8") as f:
cookies = json.loads(f.read())
except:
log("Cookies加载失败, 请先登录")
return None

# TODO: 判断 Cookie 是否有效
log(f"线程数: {args.thread}")
done_flag = threading.Semaphore(0)
terminate_flag = threading.Event()
Expand Down Expand Up @@ -145,7 +140,7 @@ def core(index, block):
meta = json.dumps(meta_dict, ensure_ascii=False).encode("utf-8")
full_meta = encoder.encode(meta)
for _ in range(10):
response = api.image_upload(full_meta, cookies)
response = api.image_upload(full_meta)
if response and response['code'] == 0:
url = response['data']['image_url']
log("元数据上传完毕")
Expand Down
38 changes: 20 additions & 18 deletions BiliDriveEx/bilibili.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,10 @@ class Bilibili:
meta_string = lambda self, url: ("bdex://" + re.findall(r"[a-fA-F0-9]{40}", url)[0]) if re.match(r"^http(s?)://i0.hdslb.com/bfs/album/[a-fA-F0-9]{40}.png$", url) else url

get_cookies = lambda self: self.cookies
get_uid = lambda self: self.get_cookies().get("DedeUserID", "")

def __init__(self):
self.cookies = {}
self._session = requests.Session()
self._session.headers.update({'User-Agent': "Mozilla/5.0 BiliDroid/5.51.1 (bbcallen@gmail.com)"})

def _requests(self, method, url, decode_level=0, retry=0, timeout=10, **kwargs):
for _ in range(retry + 1):
try:
response = getattr(self._session, method.lower())(url, timeout=timeout, **kwargs)
return response.json() if decode_level == 2 else response.content if decode_level == 1 else response
except:
pass
self.load_cookies()

def _solve_captcha(self, image):
url = "https://bili.dev:2233/captcha"
Expand Down Expand Up @@ -102,7 +92,7 @@ def login(self, username, password):
captcha = None
while True:
response = self.login_once(username, password, captcha)
print(response, self.cookies)
# print(response, self.cookies)

if not response or 'code' not in response:
log(f"当前IP登录过于频繁, 1分钟后重试")
Expand All @@ -127,6 +117,7 @@ def login(self, username, password):
for cookie in response['data']['cookie_info']['cookies']:
self.cookies[cookie['name']] = cookie['value']
log("登录成功")
self.save_cookies()
return True

log(f"登录失败 {response}")
Expand All @@ -137,8 +128,7 @@ def login(self, username, password):
def get_user_info(self):
url = f"https://api.bilibili.com/x/space/myinfo?jsonp=jsonp"
headers = {
'Host': "api.bilibili.com",
'Referer': f"https://space.bilibili.com/{self.get_uid()}/",
'Referer': f"https://space.bilibili.com",
}
response = request_retry("get", url,
headers=headers,
Expand All @@ -147,7 +137,6 @@ def get_user_info(self):

if not response or response.get("code") != 0:
return False
print(response)

info = {
'ban': False,
Expand All @@ -171,7 +160,16 @@ def get_user_info(self):
info['uid'] = response['data']['mid']
return info


def save_cookies(self):
with open(os.path.join(bundle_dir, "cookies.json"), "w", encoding="utf-8") as f:
f.write(json.dumps(self.cookies, ensure_ascii=False, indent=2))

def load_cookies(self):
try:
with open(os.path.join(bundle_dir, "cookies.json"), "r", encoding="utf-8") as f:
self.cookies = json.loads(f.read())
except:
pass

def exist(self, sha1):
try:
Expand All @@ -186,7 +184,7 @@ def exist(self, sha1):
return None


def image_upload(self, data, cookies):
def image_upload(self, data):
sha1 = calc_sha1(data)
url = self.exist(sha1)
if url: return {'code': 0, 'data': {'image_url': url}}
Expand All @@ -205,7 +203,11 @@ def image_upload(self, data, cookies):
'category': "daily",
}
try:
response = requests.post(url, data=data, headers=headers, cookies=cookies, files=files, timeout=300).json()
response = requests.post(url, data=data,
headers=headers,
cookies=self.cookies,
files=files, timeout=300
).json()
except:
response = None
return response

0 comments on commit 9ffb362

Please sign in to comment.