Skip to content

Commit 1bd7e98

Browse files
committed
[0.8.6] add more cookie
1 parent 50d12f4 commit 1bd7e98

File tree

8 files changed

+99
-11
lines changed

8 files changed

+99
-11
lines changed

app_state/__init__.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from dataclasses import dataclass, field
22
from functools import partial
33
from json import dumps, loads
4+
from platform import node
45
from queue import Queue
56
from typing import Optional, Any, List
67

@@ -129,10 +130,14 @@ def create_session(h_type: HeadersType) -> Session:
129130
session.headers.update(constant.HEADERS_WEB)
130131
elif h_type == HeadersType.APP:
131132
session.headers.update(constant.HEADERS_APP)
132-
cookiejar_from_dict(cookies_dict,
133-
cookiejar=session.cookies)
134133
session.cookies.set("appkey", constant.APP_KEY, domain="bilibili.com",
135134
path="/")
135+
session.cookies.set("device_name", node(), domain="bilibili.com",
136+
path="/")
137+
session.cookies.set("device_platform", "Windows Version: 10.0 x86_64",
138+
domain="bilibili.com", path="/")
139+
cookiejar_from_dict(cookies_dict,
140+
cookiejar=session.cookies)
136141
session.headers.update({
137142
"buvid": app_settings.app_buvid,
138143
})

models/workers/credentials/credential_manager.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def reset_default():
4646
app_state.stream_status_default()
4747

4848
@staticmethod
49-
def add_cookie():
49+
def add_cookie(allow_duplicate: bool = False) -> str:
5050
"""
5151
Adds a new cookie credential to the credential manager.
5252
@@ -64,9 +64,11 @@ def add_cookie():
6464
cookie_key = f"cookies|{uid}"
6565
CredentialManagerWorker.get_cookie_indices()
6666
if cookie_key in app_state.cookie_indices:
67-
raise CredentialDuplicatedError(cookie_key)
68-
app_state.cookie_indices.append(cookie_key)
69-
app_state.usernames[cookie_key] = cookie_key
67+
if not allow_duplicate:
68+
raise CredentialDuplicatedError(cookie_key)
69+
if cookie_key not in app_state.cookie_indices:
70+
app_state.cookie_indices.append(cookie_key)
71+
app_state.usernames[cookie_key] = cookie_key
7072
set_password(KEYRING_SERVICE_NAME, cookie_key,
7173
dumps(app_state.cookies_dict))
7274
set_password(KEYRING_SERVICE_NAME, KEYRING_COOKIES_INDEX,

models/workers/login/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1+
from .buvid_ticket import TicketFetchWorker
12
from .fetch_login import FetchLoginWorker
23
from .fetch_qr import FetchQRWorker
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from time import time
2+
from urllib.parse import quote
3+
4+
from PySide6.QtCore import Slot
5+
6+
# local package import
7+
import app_state
8+
from constant import *
9+
from models.log import get_logger
10+
from models.workers.base import BaseWorker, run_wrapper
11+
from sign import ticket_hmac_sha256
12+
13+
14+
class TicketFetchWorker(BaseWorker):
15+
def __init__(self):
16+
super().__init__(name="ticket获取", headers_type=HeadersType.WEB)
17+
self.logger = get_logger(self.__class__.__name__)
18+
19+
@Slot()
20+
@run_wrapper
21+
def run(self, /):
22+
if int(app_state.cookies_dict.get("bili_ticket_expires", 0)) < int(
23+
time()):
24+
self.logger.info("buvid_ticket Request")
25+
ticket_param = {
26+
"key_id": "ec02",
27+
"hexsign": ticket_hmac_sha256(int(time())),
28+
"context[ts]": int(time()),
29+
"csrf": app_state.cookies_dict.get("bili_jct", "")
30+
}
31+
response = self._session.post(
32+
"https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket",
33+
params=ticket_param)
34+
self.logger.info("buvid_ticket Response")
35+
response = response.json()
36+
app_state.cookies_dict["bili_ticket"] = response["data"]["ticket"]
37+
app_state.cookies_dict["bili_ticket_expires"] = str(
38+
response["data"][
39+
"created_at"] + \
40+
response["data"][
41+
"ttl"])
42+
43+
if not app_state.cookies_dict.get(
44+
"buvid3") or not app_state.cookies_dict.get("buvid4"):
45+
self.logger.info("buvid3 Request")
46+
response = self._session.get(
47+
"https://api.bilibili.com/x/frontend/finger/spi")
48+
self.logger.info("buvid3 Response")
49+
response = response.json()
50+
app_state.cookies_dict["buvid3"] = response["data"]["b_3"]
51+
app_state.cookies_dict["buvid4"] = quote(response["data"]["b_4"])
52+
53+
@Slot()
54+
def on_finished(self):
55+
from models.workers.credentials.credential_manager import \
56+
CredentialManagerWorker
57+
58+
CredentialManagerWorker.add_cookie(True)
59+
self._session.close()

models/workers/login/fetch_login.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from models.workers.announce import FetchAnnounceWorker
1515
from models.workers.area import FetchAreaWorker
1616
from models.workers.base import LongLiveWorker, run_wrapper
17+
from models.workers.login.buvid_ticket import TicketFetchWorker
1718
from models.workers.pre_live import FetchPreLiveWorker, FetchRoomStatusWorker
1819
from models.workers.usernames import FetchUsernamesWorker
1920

@@ -28,6 +29,11 @@ def __init__(self, state: LoginState):
2829
@staticmethod
2930
def post_login(parent: "MainWindow", state: LoginState):
3031
if app_state.scan_status["scanned"]:
32+
fetch_ticket = TicketFetchWorker()
33+
parent.add_thread(
34+
fetch_ticket,
35+
on_finished=fetch_ticket.on_finished,
36+
)
3137
fetch_status = FetchRoomStatusWorker()
3238
parent.add_thread(
3339
fetch_status,

models/workers/usernames/fetch_usernames.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
# local package import
99
import app_state
10-
import constant
1110
from constant import *
1211
from models.log import get_logger
1312
from models.workers.base import BaseWorker, run_wrapper
@@ -34,11 +33,7 @@ def run(self, /) -> None:
3433
sleep(1)
3534
cookies = loads(cookies)
3635
self.logger.info(f"fetch username of {key} Request")
37-
self._session.cookies.clear()
3836
self._session.cookies.update(cookies)
39-
self._session.cookies.set("appkey", constant.APP_KEY,
40-
domain="bilibili.com",
41-
path="/")
4237
response = self._session.get(
4338
url,
4439
params=livehime_sign({},

sign/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
from .app_sign import livehime_sign, order_payload
2+
from .bili_ticket import ticket_hmac_sha256
23
from .gen_buvid import gen_buvid

sign/bili_ticket.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import hashlib
2+
import hmac
3+
4+
5+
def ticket_hmac_sha256(timestamp: int) -> str:
6+
# 将密钥和消息转换为字节串
7+
key = "XgwSnGZ1p".encode('utf-8')
8+
message = f"ts{timestamp}".encode('utf-8')
9+
10+
# 创建HMAC对象,使用SHA256哈希算法
11+
hmac_obj = hmac.new(key, message, hashlib.sha256)
12+
13+
# 计算哈希值
14+
hash_value = hmac_obj.digest()
15+
16+
# 将哈希值转换为十六进制字符串
17+
hash_hex = hash_value.hex()
18+
19+
return hash_hex

0 commit comments

Comments
 (0)