Skip to content

Commit

Permalink
fix: video.get_danmakus ([漏洞] {获取弹幕时,部分视频获取失败} #799)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nemo2011 committed Aug 25, 2024
1 parent 17cc249 commit ca727cd
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 58 deletions.
62 changes: 33 additions & 29 deletions bilibili_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,46 +41,47 @@
)
from . import (
app,
article_category,
article,
ass,
hot,
game,
live,
note,
rank,
show,
user,
vote,
audio_uploader,
audio,
emoji,
login,
manga,
music,
topic,
video,
bangumi,
black_room,
channel_series,
cheese,
client,
search,
article,
bangumi,
comment,
creative_center,
dynamic,
session,
emoji,
favorite_list,
festival,
game,
homepage,
settings,
watchroom,
hot,
interactive_video,
live_area,
video_tag,
black_room,
live,
login_func,
video_zone,
favorite_list,
channel_series,
login,
manga,
music,
note,
opus,
rank,
search,
session,
settings,
show,
topic,
user,
video_tag,
video_uploader,
creative_center,
article_category,
interactive_video,
audio_uploader,
video_zone,
video,
vote,
watchroom
)

BILIBILI_API_VERSION = "16.2.0"
Expand Down Expand Up @@ -134,6 +135,7 @@
"festival",
"game",
"get_aiohttp_session",
"get_httpx_sync_session",
"get_real_url",
"get_session",
"homepage",
Expand All @@ -146,11 +148,13 @@
"manga",
"music",
"note",
"opus",
"parse_link",
"rank",
"search",
"session",
"set_aiohttp_session",
"set_httpx_sync_session",
"set_session",
"settings",
"show",
Expand Down
3 changes: 2 additions & 1 deletion bilibili_api/data/api/video.json
Original file line number Diff line number Diff line change
Expand Up @@ -389,9 +389,10 @@
},
"danmaku": {
"get_danmaku": {
"url": "https://api.bilibili.com/x/v2/dm/web/seg.so",
"url": "https://api.bilibili.com/x/v2/dm/wbi/web/seg.so",
"method": "GET",
"verify": false,
"wbi": true,
"params": {
"oid": "int: video_info 中的 cid,即分 P 的编号",
"type": "const int: 1",
Expand Down
12 changes: 8 additions & 4 deletions bilibili_api/utils/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ async def _prepare_request(self, **kwargs) -> dict:
if self.wbi:
global wbi_mixin_key
if wbi_mixin_key == "":
wbi_mixin_key = await get_mixin_key()
wbi_mixin_key = await get_mixin_key(credential=self.credential)
enc_wbi(self.params, wbi_mixin_key)

# 自动添加 csrf
Expand Down Expand Up @@ -532,7 +532,7 @@ def request_sync(self, raw: bool = False, **kwargs) -> Union[int, str, dict]:
return real_data

@retry(times=settings.wbi_retry_times)
async def request(self, raw: bool = False, **kwargs) -> Union[int, str, dict]:
async def request(self, raw: bool = False, byte: bool = False, **kwargs) -> Union[int, str, dict]:
"""
向接口发送请求。
Expand All @@ -551,6 +551,8 @@ async def request(self, raw: bool = False, **kwargs) -> Union[int, str, dict]:
resp.raise_for_status()
except httpx.HTTPStatusError as e:
raise NetworkException(resp.status_code, str(resp.status_code))
if byte:
return resp.read()
real_data = self._process_response(
resp, await self._get_resp_text(resp), raw=raw
)
Expand All @@ -562,6 +564,8 @@ async def request(self, raw: bool = False, **kwargs) -> Union[int, str, dict]:
resp.raise_for_status()
except aiohttp.ClientResponseError as e:
raise NetworkException(e.status, e.message)
if byte:
return await resp.read()
real_data = self._process_response(
resp, await self._get_resp_text(resp), raw=raw
)
Expand Down Expand Up @@ -753,14 +757,14 @@ def split(key):
return le[:32]


async def get_mixin_key() -> str:
async def get_mixin_key(credential: Credential = Credential()) -> str:
"""
获取混合密钥
Returns:
str: 新获取的密钥
"""
data = await get_nav()
data = await get_nav(credential=credential)
wbi_img: Dict[str, str] = data["wbi_img"]

# 为什么要把里的 lambda 表达式换成函数 这不是一样的吗
Expand Down
32 changes: 8 additions & 24 deletions bilibili_api/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from .utils.credential import Credential
from .utils.BytesReader import BytesReader
from .utils.danmaku import Danmaku, SpecialDanmaku
from .utils.network import get_aiohttp_session, Api, get_session
from .utils.network import get_aiohttp_session, Api, get_session, get_mixin_key, enc_wbi
from .exceptions import (
ArgsException,
NetworkException,
Expand Down Expand Up @@ -638,7 +638,7 @@ async def get_danmaku_view(

config = {}
config["url"] = api["url"]
config["params"] = {"type": 1, "oid": cid, "pid": self.get_aid()}
config["params"] = {"type": 1, "oid": cid, "pid": self.get_aid(), "duration": (await self.__get_info_cached())["duration"]}
config["cookies"] = self.credential.get_cookies()
config["headers"] = {
"Referer": "https://www.bilibili.com",
Expand Down Expand Up @@ -867,7 +867,6 @@ async def get_danmakus(

cid = await self.__get_cid_by_index(page_index)

session = get_session()
aid = self.get_aid()
params: dict[str, Any] = {"oid": cid, "type": 1, "pid": aid}
if date is not None:
Expand All @@ -882,38 +881,23 @@ async def get_danmakus(
from_seg = 0
if to_seg == None:
view = await self.get_danmaku_view(cid=cid)
to_seg = view["dm_seg"]["total"] - 1
if view["dm_seg"].get("total"):
to_seg = view["dm_seg"]["total"] - 1
else:
to_seg = (await self.__get_info_cached())["duration"] // 360 + 1

danmakus = []

for seg in range(from_seg, to_seg + 1):
if date is None:
# 仅当获取当前弹幕时需要该参数
params["segment_index"] = seg + 1

config = {}
config["url"] = api["url"]
config["params"] = params
config["headers"] = {
"Referer": "https://www.bilibili.com",
"User-Agent": "Mozilla/5.0",
}
config["cookies"] = self.credential.get_cookies()

try:
req = await session.get(**config)
data = await Api(**api, credential=self.credential).update_params(**params).request(byte=True)
except Exception as e:
raise e
raise NetworkException(-1, str(e))

if "content-type" not in req.headers.keys():
break
else:
content_type = req.headers["content-type"]
if content_type != "application/octet-stream":
raise ResponseException("返回数据类型错误:")

# 解析二进制流数据
data = req.read()
if data == b"\x10\x01":
# 视频弹幕被关闭
raise DanmakuClosedException()
Expand Down

0 comments on commit ca727cd

Please sign in to comment.