From 343f9c3938afb2f4c56ddefbdf12c60facb00f95 Mon Sep 17 00:00:00 2001 From: Nemo2011 Date: Sat, 14 Dec 2024 23:49:09 +0800 Subject: [PATCH] =?UTF-8?q?refactor!:=20=E9=87=8D=E6=9E=84=20bangumi?= =?UTF-8?q?=EF=BC=8C=E7=A7=BB=E9=99=A4=E6=89=80=E6=9C=89=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=EF=BC=8C=E9=83=A8=E5=88=86=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=BC=82=E6=AD=A5=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bilibili_api/bangumi.py | 274 ++++++++++++++++------------ bilibili_api/settings.py | 5 + bilibili_api/utils/initial_state.py | 18 +- bilibili_api/utils/network.py | 6 +- bilibili_api/video.py | 100 +++++----- 5 files changed, 223 insertions(+), 180 deletions(-) diff --git a/bilibili_api/bangumi.py b/bilibili_api/bangumi.py index 793e9dd6..8f9b5a73 100644 --- a/bilibili_api/bangumi.py +++ b/bilibili_api/bangumi.py @@ -14,10 +14,10 @@ from enum import Enum from typing import Any, List, Tuple, Union, Optional -from bilibili_api.utils.danmaku import Danmaku - from . import settings from .video import Video +from .utils.aid_bvid_transformer import aid2bvid, bvid2aid +from .utils.danmaku import Danmaku from .utils.utils import get_api, raise_for_statement from .utils.credential import Credential from .utils.network import Api @@ -26,11 +26,14 @@ get_initial_state_sync, InitialDataType, ) +from .exceptions import ApiException API = get_api("bangumi") episode_data_cache = {} +bangumi_ss_to_md = {} +bangumi_md_to_ss = {} class BangumiCommentOrder(Enum): @@ -1024,31 +1027,49 @@ def __init__( credential (Credential | None, optional): 凭据类. Defaults to None. """ + global bangumi_md_to_ss, bangumi_ss_to_md + if media_id == -1 and ssid == -1 and epid == -1: raise ValueError("需要 Media_id 或 Season_id 或 epid 中的一个 !") self.credential: Credential = credential if credential else Credential() + self.__media_id = media_id + self.__ssid = ssid + self.__epid = epid + self.__up_info = None + self.raw = None + self.oversea = oversea + self.ep_list = None + self.ep_item = None + + if self.__media_id != -1 and self.__ssid != -1: + bangumi_md_to_ss[self.__media_id] = self.__ssid + bangumi_ss_to_md[self.__ssid] = self.__media_id + if self.__media_id != -1 and self.__ssid == -1 and self.__media_id in bangumi_md_to_ss.keys(): + self.__ssid = bangumi_md_to_ss[self.__media_id] + if self.__media_id == -1 and self.__ssid != -1 and self.__ssid in bangumi_ss_to_md.keys(): + self.__media_id = bangumi_ss_to_md[self.__ssid] + + async def __fetch_raw(self) -> None: + global bangumi_md_to_ss, bangumi_ss_to_md # 处理极端情况 params = {} - self.__ssid = ssid - if self.__ssid == -1 and epid == -1: + if self.__ssid == -1 and self.__epid == -1: api = API["info"]["meta"] - params = {"media_id": media_id} - meta = Api(**api, credential=credential).update_params(**params).result_sync + params = {"media_id": self.__media_id} + meta = await Api(**api, credential=self.credential).update_params(**params).result self.__ssid = meta["media"]["season_id"] - params["media_id"] = media_id + params["media_id"] = self.__media_id # 处理正常情况 if self.__ssid != -1: params["season_id"] = self.__ssid - if epid != -1: - params["ep_id"] = epid - self.oversea = oversea - if oversea: + if self.__epid != -1: + params["ep_id"] = self.__epid + if self.oversea: api = API["info"]["collective_info_oversea"] else: api = API["info"]["collective_info"] - resp = Api(**api, credential=credential).update_params(**params).result_sync + resp = await Api(**api, credential=self.credential).update_params(**params).result self.__raw = resp - self.__epid = epid # 确认有结果后,取出数据 self.__ssid = resp["season_id"] self.__media_id = resp["media_id"] @@ -1056,57 +1077,54 @@ def __init__( self.__up_info = resp["up_info"] else: self.__up_info = {} - # 获取剧集相关 - self.ep_list = resp.get("episodes") - self.ep_item = [{}] - # 出海 Api 和国内的字段有些不同 - if self.ep_list: - if self.oversea: - self.ep_item = [ - item for item in self.ep_list if item["ep_id"] == self.__epid - ] - else: - self.ep_item = [ - item for item in self.ep_list if item["id"] == self.__epid - ] + bangumi_md_to_ss[self.__media_id] = self.__ssid + bangumi_ss_to_md[self.__ssid] = self.__media_id - def get_media_id(self) -> int: + async def get_media_id(self) -> int: """ 获取 media_id Returns: int: 获取 media_id """ + if self.__media_id == -1: + await self.__fetch_raw() return self.__media_id - def get_season_id(self) -> int: + async def get_season_id(self) -> int: """ 获取季度 id Returns: int: 获取季度 id """ + if self.__ssid == -1: + await self.__fetch_raw() return self.__ssid - def get_up_info(self) -> dict: + async def get_up_info(self) -> dict: """ 番剧上传者信息 出差或者原版 Returns: Api 相关字段 """ + if not self.__up_info: + await self.__fetch_raw() return self.__up_info - def get_raw(self) -> Tuple[dict, bool]: + async def get_raw(self) -> Tuple[dict, bool]: """ 原始初始化数据 Returns: Api 相关字段 """ + if not self.__raw: + await self.__fetch_raw() return self.__raw, self.oversea - def set_media_id(self, media_id: int) -> None: + async def set_media_id(self, media_id: int) -> None: """ 设置 media_id @@ -1114,8 +1132,9 @@ def set_media_id(self, media_id: int) -> None: media_id (int): 设置 media_id """ self.__init__(media_id=media_id, credential=self.credential) + await self.__fetch_raw() - def set_ssid(self, ssid: int) -> None: + async def set_ssid(self, ssid: int) -> None: """ 设置季度 id @@ -1123,6 +1142,7 @@ def set_ssid(self, ssid: int) -> None: ssid (int): 设置季度 id """ self.__init__(ssid=ssid, credential=self.credential) + await self.__fetch_raw() async def get_meta(self) -> dict: """ @@ -1134,7 +1154,7 @@ async def get_meta(self) -> dict: credential = self.credential if self.credential is not None else Credential() api = API["info"]["meta"] - params = {"media_id": self.__media_id} + params = {"media_id": await self.get_media_id()} return await Api(**api, credential=credential).update_params(**params).result async def get_short_comment_list( @@ -1156,7 +1176,7 @@ async def get_short_comment_list( credential = self.credential if self.credential is not None else Credential() api = API["info"]["short_comment"] - params = {"media_id": self.__media_id, "ps": 20, "sort": order.value} + params = {"media_id": await self.get_media_id(), "ps": 20, "sort": order.value} if next is not None: params["cursor"] = next @@ -1181,7 +1201,7 @@ async def get_long_comment_list( credential = self.credential if self.credential is not None else Credential() api = API["info"]["long_comment"] - params = {"media_id": self.__media_id, "ps": 20, "sort": order.value} + params = {"media_id": await self.get_media_id(), "ps": 20, "sort": order.value} if next is not None: params["cursor"] = next @@ -1194,6 +1214,21 @@ async def get_episode_list(self) -> dict: Returns: dict: 调用 API 返回的结果 """ + if not self.raw: + await self.__fetch_raw() + if not self.ep_list: + self.ep_list = self.__raw.get("episodes") + self.ep_item = [{}] + # 出海 Api 和国内的字段有些不同 + if self.ep_list: + if self.oversea: + self.ep_item = [ + item for item in self.ep_list if item["ep_id"] == self.__epid + ] + else: + self.ep_item = [ + item for item in self.ep_list if item["id"] == self.__epid + ] if self.oversea: # 转换 ep_id->id ,index_title->longtitle ,index->title fix_ep_list = [] @@ -1208,7 +1243,7 @@ async def get_episode_list(self) -> dict: self.credential if self.credential is not None else Credential() ) api = API["info"]["episodes_list"] - params = {"season_id": self.__ssid} + params = {"season_id": await self.get_season_id()} return ( await Api(**api, credential=credential).update_params(**params).result ) @@ -1221,20 +1256,11 @@ async def get_episodes(self) -> List["Episode"]: episode_list = await self.get_episode_list() if len(episode_list["main_section"]["episodes"]) == 0: return [] - first_epid = episode_list["main_section"]["episodes"][0]["id"] - credential = self.credential if self.credential else Credential() - content_type = None - while content_type != InitialDataType.NEXT_DATA: - bangumi_meta, content_type = await get_initial_state( - url=f"https://www.bilibili.com/bangumi/play/ep{first_epid}", - credential=credential, - ) - bangumi_meta["media_id"] = self.get_media_id() episodes = [] for ep in episode_list["main_section"]["episodes"]: episode_data_cache[ep["id"]] = { - "bangumi_meta": bangumi_meta, + "bangumi_meta": ep, "bangumi_class": self, } episodes.append(Episode(epid=ep["id"], credential=self.credential)) @@ -1250,7 +1276,7 @@ async def get_stat(self) -> dict: credential = self.credential if self.credential is not None else Credential() api = API["info"]["season_status"] - params = {"season_id": self.__ssid} + params = {"season_id": await self.get_season_id()} return await Api(**api, credential=credential).update_params(**params).result async def get_overview(self) -> dict: @@ -1265,7 +1291,7 @@ async def get_overview(self) -> dict: api = API["info"]["collective_info_oversea"] else: api = API["info"]["collective_info"] - params = {"season_id": self.__ssid} + params = {"season_id": await self.get_season_id()} return await Api(**api, credential=credential).update_params(**params).result @@ -1289,7 +1315,7 @@ async def set_follow( credential.raise_for_no_sessdata() api = API["operate"]["follow_add"] if status else API["operate"]["follow_del"] - data = {"season_id": bangumi.get_season_id()} + data = {"season_id": await bangumi.get_season_id()} return await Api(**api, credential=credential).update_data(**data).result @@ -1312,7 +1338,7 @@ async def update_follow_status( credential.raise_for_no_sessdata() api = API["operate"]["follow_status"] - data = {"season_id": bangumi.get_season_id(), "status": status} + data = {"season_id": await bangumi.get_season_id(), "status": status} return await Api(**api, credential=credential).update_data(**data).result @@ -1338,58 +1364,75 @@ def __init__(self, epid: int, credential: Union[Credential, None] = None): global episode_data_cache self.credential: Credential = credential if credential else Credential() self.__epid: int = epid + self.bangumi = None + self.__ep_aid = None + self.__ep_bvid = None + self.__ep_info_html = None - if not epid in episode_data_cache.keys(): - res, content_type = get_initial_state_sync( - url=f"https://www.bilibili.com/bangumi/play/ep{self.__epid}", - credential=self.credential, - ) # 随机 __NEXT_DATA__ 见 https://github.com/Nemo2011/bilibili-api/issues/433 - if content_type == InitialDataType.NEXT_DATA: - content = res["props"]["pageProps"]["dehydratedState"]["queries"][0][ - "state" - ]["data"]["result"]["play_view_business_info"] - self.bangumi = ( - Bangumi(ssid=content["season_info"]["season_id"]) - if not epid in episode_data_cache.keys() - else episode_data_cache[epid]["bangumi_class"] - ) - ep_info = content["episode_info"] - bvid = ep_info["bvid"] - self.__ep_info: dict = ep_info - else: # InitialDataType.INITIAL_STATE - self.__ep_info: dict = res["epInfo"] - self.bangumi = ( - Bangumi(ssid=res["mediaInfo"]["season_id"]) - if not epid in episode_data_cache.keys() - else episode_data_cache[epid]["bangumi_class"] - ) - bvid = res["epInfo"]["bvid"] - else: - content = episode_data_cache[epid]["bangumi_meta"] - bvid = None - self.__ep_info = content["props"]["pageProps"]["dehydratedState"][ - "queries" - ][0]["state"]["data"]["result"]["play_view_business_info"]["episode_info"] - bvid = self.__ep_info["bvid"] + if epid in episode_data_cache.keys(): self.bangumi = episode_data_cache[epid]["bangumi_class"] - self.__ep_info: dict = episode_data_cache[epid] + self.__ep_aid = episode_data_cache[epid]["bangumi_meta"]["aid"] + self.__ep_bvid = aid2bvid(self.__ep_aid) - self.video_class = Video(bvid=bvid, credential=self.credential) - super().__init__(bvid=bvid, credential=self.credential) + super().__init__(bvid="BV1Am411y7iK", credential=self.credential) self.set_aid = self.set_aid_e self.set_bvid = self.set_bvid_e - def get_epid(self) -> int: + async def __fetch_bangumi(self) -> None: + res, content_type = await self.get_episode_info() # 随机 __NEXT_DATA__ 见 https://github.com/Nemo2011/bilibili-api/issues/433 + if content_type == InitialDataType.NEXT_DATA: + content = res["props"]["pageProps"]["dehydratedState"]["queries"][0][ + "state" + ]["data"]["result"]["play_view_business_info"] + self.bangumi = Bangumi(ssid=content["season_info"]["season_id"], media_id=res["props"]["pageProps"]["dehydratedState"]["queries"][1][ + "state" + ]["data"]["media_id"]) + self.__ep_bvid = content["episode_info"]["bvid"] + self.__ep_aid = bvid2aid(self.__ep_bvid) + else: # InitialDataType.INITIAL_STATE + self.bangumi = Bangumi(ssid=res["mediaInfo"]["season_id"]) # 刷不出 INITIAL_STATE 了,暂时不动 + self.__ep_bvid = res["epInfo"]["bvid"] + self.__ep_aid = bvid2aid(self.__ep_bvid) + + async def get_bvid(self) -> str: + """ + 获取 BVID。 + + Returns: + str: BVID。 """ - 获取 epid + if not self.__ep_bvid: + await self.__fetch_bangumi() + return self.__ep_bvid + + async def get_aid(self) -> str: """ - return self.__epid + 获取 AID。 - def set_aid_e(self, aid: int) -> None: - raise_for_statement(0, "Set aid is not allowed in Episode") + Returns: + str: AID。 + """ + if not self.__ep_aid: + await self.__fetch_bangumi() + return self.__ep_aid + + async def set_bvid_e(self) -> None: + """ + 此方法不可用于 Episode 类。 + """ + raise ApiException("此方法不可用于 Episode 类。") + + async def set_aid_e(self) -> None: + """ + 此方法不可用于 Episode 类。 + """ + raise ApiException("此方法不可用于 Episode 类。") - def set_bvid_e(self, bvid: str) -> None: - raise_for_statement(0, "Set bvid is not allowed in Episode") + async def get_epid(self) -> int: + """ + 获取 epid + """ + return self.__epid async def get_cid(self) -> int: """ @@ -1400,16 +1443,16 @@ async def get_cid(self) -> int: """ return (await self.get_episode_info())["cid"] - def get_bangumi(self) -> "Bangumi": + async def get_bangumi(self) -> "Bangumi": """ 获取对应的番剧 Returns: Bangumi: 番剧类 """ - return self.bangumi # type: ignore + return await self.get_bangumi_from_episode() - def set_epid(self, epid: int) -> None: + async def set_epid(self, epid: int) -> None: """ 设置 epid @@ -1417,32 +1460,21 @@ def set_epid(self, epid: int) -> None: epid (int): epid """ self.__init__(epid, self.credential) + await self.__fetch_bangumi() - async def get_episode_info(self) -> dict: + async def get_episode_info(self) -> Tuple[dict, InitialDataType]: """ 获取番剧单集信息 Returns: - HTML 中的数据 + Tuple[dict, InitialDataType]: 前半部分为数据,后半部分为数据类型(__INITIAL_STATE__ 或 __NEXT_DATA) """ - if self.__ep_info is None: - res, content_type = get_initial_state( - url=f"https://www.bilibili.com/bangumi/play/ep{self.__epid}", - credential=self.credential, - ) - if content_type == InitialDataType.NEXT_DATA: - content = res["props"]["pageProps"]["dehydratedState"]["queries"][0][ - "state" - ]["data"]["mediaInfo"] - for ep_info in content["episodes"]: - if int( - ep_info["id"] if "id" in ep_info else ep_info["ep_id"] - ) == int(self.get_epid()): - return ep_info - else: - return res["epInfo"] - else: - return self.__ep_info + if self.__ep_info_html: + return self.__ep_info_html + return await get_initial_state( + url=f"https://www.bilibili.com/bangumi/play/ep{self.__epid}", + credential=self.credential, + ) async def get_bangumi_from_episode(self) -> "Bangumi": """ @@ -1451,9 +1483,9 @@ async def get_bangumi_from_episode(self) -> "Bangumi": Returns: Bangumi: 输入的集对应的番剧类 """ - info = await self.get_episode_info() - ssid = info["mediaInfo"]["season_id"] - return Bangumi(ssid=ssid) + if not self.bangumi: + await self.__fetch_bangumi() + return self.bangumi async def get_download_url(self) -> dict: """ @@ -1494,7 +1526,7 @@ async def get_danmaku_view(self) -> dict: Returns: dict: 二进制流解析结果 """ - return await self.video_class.get_danmaku_view(0) + return await super().get_danmaku_view(0) async def get_danmakus( self, @@ -1515,7 +1547,7 @@ async def get_danmakus( Returns: dict[Danmaku]: 弹幕列表 """ - return await self.video_class.get_danmakus(0, date, from_seg=from_seg, to_seg=to_seg) + return await super().get_danmakus(0, date, from_seg=from_seg, to_seg=to_seg) async def get_history_danmaku_index( self, date: Union[datetime.date, None] = None @@ -1529,4 +1561,4 @@ async def get_history_danmaku_index( Returns: None | List[str]: 调用 API 返回的结果。不存在时为 None。 """ - return await self.video_class.get_history_danmaku_index(0, date) + return await super().get_history_danmaku_index(0, date) diff --git a/bilibili_api/settings.py b/bilibili_api/settings.py index af1c4a1c..6f76894d 100644 --- a/bilibili_api/settings.py +++ b/bilibili_api/settings.py @@ -55,6 +55,11 @@ class HTTPClient(Enum): 请求 Api 时是否打印 Api 信息 """ +request_log_show_response: bool = False +""" +请求 Api 打印 Api 信息是否打印响应信息(避免信息过多) +""" + wbi_retry_times: int = 3 """ WBI请求重试次数上限设置, 默认为3次 diff --git a/bilibili_api/utils/initial_state.py b/bilibili_api/utils/initial_state.py index 3e522d92..f7fa7350 100644 --- a/bilibili_api/utils/initial_state.py +++ b/bilibili_api/utils/initial_state.py @@ -7,12 +7,12 @@ import json import httpx from enum import Enum -from typing import Union +from typing import Tuple from ..exceptions import * from .short import get_real_url from .credential import Credential -from .network import get_session +from .network import get_session, Api class InitialDataType(Enum): @@ -26,7 +26,7 @@ class InitialDataType(Enum): async def get_initial_state( url: str, credential: Credential = Credential() -) -> Union[dict, InitialDataType]: +) -> Tuple[dict, InitialDataType]: """ 异步获取初始化信息 @@ -36,17 +36,11 @@ async def get_initial_state( credential (Credential, optional): 用户凭证. Defaults to Credential(). """ try: - session = get_session() - resp = await session.get( - url, - cookies=credential.get_cookies(), - headers={"User-Agent": "Mozilla/5.0"}, - follow_redirects=True, - ) + resp = await Api(url=url, method="GET", credential=credential, comment="[获取初始化信息]").request(byte=True) except Exception as e: raise e else: - content = resp.text + content = resp.decode("utf-8") pattern = re.compile(r"window.__INITIAL_STATE__=(\{.*?\});") match = re.search(pattern, content) if match is None: @@ -69,7 +63,7 @@ async def get_initial_state( def get_initial_state_sync( url: str, credential: Credential = Credential() -) -> Union[dict, InitialDataType]: +) -> Tuple[dict, InitialDataType]: """ 同步获取初始化信息 diff --git a/bilibili_api/utils/network.py b/bilibili_api/utils/network.py index bb58c0bf..e65003e7 100644 --- a/bilibili_api/utils/network.py +++ b/bilibili_api/utils/network.py @@ -600,7 +600,7 @@ async def request(self, raw: bool = False, byte: bool = False, **kwargs) -> Unio raise NetworkException(resp.status_code, str(resp.status_code)) if byte: ret = resp.read() - if settings.request_log: + if settings.request_log and settings.request_log_show_response: settings.logger.info(f"获得字节数据\n{str(ret)}") return ret real_data = self._process_response( @@ -616,7 +616,7 @@ async def request(self, raw: bool = False, byte: bool = False, **kwargs) -> Unio raise NetworkException(e.status, e.message) if byte: ret = await resp.read() - if settings.request_log: + if settings.request_log and settings.request_log_show_response: settings.logger.info(f"获得字节数据\n{str(ret)}") return ret real_data = self._process_response( @@ -647,7 +647,7 @@ def _process_response( # JSON resp_data: dict = json.loads(resp_text) - if settings.request_log: + if settings.request_log and settings.request_log_show_response: settings.logger.info(f"获得 json 数据\n{pprint.pformat(resp_data)}") if raw: diff --git a/bilibili_api/video.py b/bilibili_api/video.py index 5b6375d9..822f26ab 100644 --- a/bilibili_api/video.py +++ b/bilibili_api/video.py @@ -14,7 +14,7 @@ import logging import datetime from enum import Enum -from inspect import isfunction +from inspect import iscoroutine, isfunction from functools import cmp_to_key from dataclasses import dataclass from typing import Any, List, Union, Optional @@ -218,6 +218,18 @@ def get_aid(self) -> int: """ return self.__aid + async def __get_bvid(self) -> str: + res = self.get_bvid() + if iscoroutine(res): + return await res + return res + + async def __get_aid(self) -> str: + res = self.get_aid() + if iscoroutine(res): + return await res + return res + async def get_info(self) -> dict: """ 获取视频信息。 @@ -226,7 +238,7 @@ async def get_info(self) -> dict: dict: 调用 API 返回的结果。 """ api = API["info"]["info"] - params = {"bvid": self.get_bvid(), "aid": self.get_aid()} + params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} resp = ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -243,8 +255,8 @@ async def get_detail(self) -> dict: """ api = API["info"]["detail"] params = { - "bvid": self.get_bvid(), - "aid": self.get_aid(), + "bvid": await self.__get_bvid(), + "aid": await self.__get_aid(), "need_operation_card": 0, "need_elec": 0, } @@ -272,7 +284,7 @@ async def __get_info_cached(self) -> dict: # dict: 调用 API 返回的结果。 # """ # api = API["info"]["stat"] - # params = {"bvid": self.get_bvid(), "aid": self.get_aid()} + # params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} # return await Api(**api, credential=self.credential).update_params(**params).result async def get_up_mid(self) -> int: @@ -305,7 +317,7 @@ async def get_tags( cid = await self.get_cid(page_index=page_index) api = API["info"]["tags"] - params = {"bvid": self.get_bvid(), "aid": self.get_aid(), "cid": cid} + params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid(), "cid": cid} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -320,7 +332,7 @@ async def get_chargers(self) -> dict: info = await self.__get_info_cached() mid = info["owner"]["mid"] api = API["info"]["chargers"] - params = {"aid": self.get_aid(), "bvid": self.get_bvid(), "mid": mid} + params = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid(), "mid": mid} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -333,7 +345,7 @@ async def get_pages(self) -> List[dict]: dict: 调用 API 返回的结果。 """ api = API["info"]["pages"] - params = {"aid": self.get_aid(), "bvid": self.get_bvid()} + params = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid()} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -380,11 +392,11 @@ async def get_video_snapshot( Returns: dict: 调用 API 返回的结果,数据中 Url 没有 http 头 """ - params: dict[str, Any] = {"aid": self.get_aid()} + params: dict[str, Any] = {"aid": await self.__get_aid()} if pvideo: api = API["info"]["video_snapshot_pvideo"] else: - params["bvid"] = self.get_bvid() + params["bvid"] = await self.__get_bvid() if json_index: params["index"] = 1 if cid: @@ -434,8 +446,8 @@ async def get_download_url( api = API["info"]["playurl"] params = { - "avid": self.get_aid(), - "bvid": self.get_bvid(), + "avid": await self.__get_aid(), + "bvid": await self.__get_bvid(), "cid": cid, "qn": "127", "fnver": 0, @@ -456,7 +468,7 @@ async def get_related(self) -> dict: dict: 调用 API 返回的结果。 """ api = API["info"]["related"] - params = {"aid": self.get_aid(), "bvid": self.get_bvid()} + params = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid()} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -470,7 +482,7 @@ async def get_relation(self) -> dict: """ self.credential.raise_for_no_sessdata() api = API["info"]["relation"] - params = {"aid": self.get_aid(), "bvid": self.get_bvid()} + params = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid()} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -485,7 +497,7 @@ async def has_liked(self) -> bool: self.credential.raise_for_no_sessdata() api = API["info"]["has_liked"] - params = {"bvid": self.get_bvid(), "aid": self.get_aid()} + params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -500,7 +512,7 @@ async def get_pay_coins(self) -> int: self.credential.raise_for_no_sessdata() api = API["info"]["get_pay_coins"] - params = {"bvid": self.get_bvid(), "aid": self.get_aid()} + params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} return ( await Api(**api, credential=self.credential).update_params(**params).result )["multiply"] @@ -515,7 +527,7 @@ async def has_favoured(self) -> bool: self.credential.raise_for_no_sessdata() api = API["info"]["has_favoured"] - params = {"bvid": self.get_bvid(), "aid": self.get_aid()} + params = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} return ( await Api(**api, credential=self.credential).update_params(**params).result )["favoured"] @@ -528,7 +540,7 @@ async def is_forbid_note(self) -> bool: bool: 是否禁止笔记。 """ api = API["info"]["is_forbid"] - params = {"aid": self.get_aid()} + params = {"aid": await self.__get_aid()} return ( await Api(**api, credential=self.credential).update_params(**params).result )["forbid_note_entrance"] @@ -543,7 +555,7 @@ async def get_private_notes_list(self) -> list: self.credential.raise_for_no_sessdata() api = API["info"]["private_notes"] - params = {"oid": self.get_aid(), "oid_type": 0} + params = {"oid": await self.__get_aid(), "oid_type": 0} return ( await Api(**api, credential=self.credential).update_params(**params).result )["noteIds"] @@ -562,7 +574,7 @@ async def get_public_notes_list(self, pn: int, ps: int) -> dict: """ api = API["info"]["public_notes"] - params = {"oid": self.get_aid(), "oid_type": 0, "pn": pn, "ps": ps} + params = {"oid": await self.__get_aid(), "oid_type": 0, "pn": pn, "ps": ps} return ( await Api(**api, credential=self.credential).update_params(**params).result ) @@ -592,8 +604,8 @@ async def get_ai_conclusion(self, cid: Optional[int] = None, page_index: Optiona api = API["info"]["ai_conclusion"] params = { - "aid": self.get_aid(), - "bvid": self.get_bvid(), + "aid": await self.__get_aid(), + "bvid": await self.__get_bvid(), "cid": cid, "up_mid": await self.get_up_mid() if up_mid is None else up_mid, "web_location": "333.788", @@ -623,7 +635,7 @@ async def get_danmaku_view( cid = await self.__get_cid_by_index(page_index) api = API["danmaku"]["view"] - params = {"type": 1, "oid": cid, "pid": self.get_aid()} + params = {"type": 1, "oid": cid, "pid": await self.__get_aid()} try: resp_data = await Api(**api, credential=self.credential).update_params(**params).request(byte=True) @@ -846,7 +858,7 @@ async def get_danmakus( cid = await self.__get_cid_by_index(page_index) - aid = self.get_aid() + aid = await self.__get_aid() params: dict[str, Any] = {"oid": cid, "type": 1, "pid": aid} if date is not None: # 获取历史弹幕 @@ -1131,8 +1143,8 @@ async def send_danmaku( "type": 1, "oid": cid, "msg": danmaku.text, - "aid": self.get_aid(), - "bvid": self.get_bvid(), + "aid": await self.__get_aid(), + "bvid": await self.__get_bvid(), "progress": int(danmaku.dm_time * 1000), "color": int(danmaku.color, 16), "fontsize": danmaku.font_size, @@ -1216,7 +1228,7 @@ async def get_online(self, cid: Optional[int] = None, page_index: Optional[int] dict: 调用 API 返回的结果。 """ api = API["info"]["online"] - params = {"aid": self.get_aid(), "bvid": self.get_bvid(), + params = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid(), "cid": cid if cid is not None else await self.get_cid(page_index=page_index)} return ( await Api(**api, credential=self.credential).update_params(**params).result @@ -1285,7 +1297,7 @@ async def like(self, status: bool = True) -> dict: self.credential.raise_for_no_bili_jct() api = API["operate"]["like"] - data = {"aid": self.get_aid(), "like": 1 if status else 2} + data = {"aid": await self.__get_aid(), "like": 1 if status else 2} return await Api(**api, credential=self.credential).update_data(**data).result async def pay_coin(self, num: int = 1, like: bool = False) -> dict: @@ -1308,8 +1320,8 @@ async def pay_coin(self, num: int = 1, like: bool = False) -> dict: api = API["operate"]["coin"] data = { - "aid": self.get_aid(), - "bvid": self.get_bvid(), + "aid": await self.__get_aid(), + "bvid": await self.__get_bvid(), "multiply": num, "like": 1 if like else 0, } @@ -1324,8 +1336,8 @@ async def share(self) -> int: """ api = API["operate"]["share"] data = { - "bvid": self.get_bvid(), - "aid": self.get_aid(), + "bvid": await self.__get_bvid(), + "aid": await self.__get_aid(), "csrf": self.credential.bili_jct, } return await Api(**api, credential=self.credential).update_data(**data).result @@ -1338,7 +1350,7 @@ async def triple(self) -> dict: dict: 调用 API 返回的结果 """ api = API["operate"]["yjsl"] - data = {"bvid": self.get_bvid(), "aid": self.get_aid()} + data = {"bvid": await self.__get_bvid(), "aid": await self.__get_aid()} return await Api(**api, credential=self.credential).update_data(**data).result async def add_tag(self, name: str) -> dict: @@ -1355,7 +1367,7 @@ async def add_tag(self, name: str) -> dict: self.credential.raise_for_no_bili_jct() api = API["operate"]["add_tag"] - data = {"aid": self.get_aid(), "bvid": self.get_bvid(), "tag_name": name} + data = {"aid": await self.__get_aid(), "bvid": await self.__get_bvid(), "tag_name": name} return await Api(**api, credential=self.credential).update_data(**data).result async def delete_tag(self, tag_id: int) -> dict: @@ -1373,7 +1385,7 @@ async def delete_tag(self, tag_id: int) -> dict: api = API["operate"]["del_tag"] - data = {"tag_id": tag_id, "aid": self.get_aid(), "bvid": self.get_bvid()} + data = {"tag_id": tag_id, "aid": await self.__get_aid(), "bvid": await self.__get_bvid()} return await Api(**api, credential=self.credential).update_data(**data).result async def appeal(self, reason: Any, detail: str): @@ -1389,7 +1401,7 @@ async def appeal(self, reason: Any, detail: str): dict: 调用 API 返回的结果 """ api = API["operate"]["appeal"] - data = {"aid": self.get_aid(), "desc": detail} + data = {"aid": await self.__get_aid(), "desc": detail} if isfunction(reason): reason = reason() if isinstance(reason, int): @@ -1420,7 +1432,7 @@ async def set_favorite( api = API["operate"]["favorite"] data = { - "rid": self.get_aid(), + "rid": await self.__get_aid(), "type": 2, "add_media_ids": ",".join(map(lambda x: str(x), add_media_ids)), "del_media_ids": ",".join(map(lambda x: str(x), del_media_ids)), @@ -1466,7 +1478,7 @@ async def get_player_info( api = API["info"]["get_player_info"] params = { - "aid": self.get_aid(), + "aid": await self.__get_aid(), "cid": cid, "isGaiaAvoided": False, "web_location": 1315873, @@ -1560,7 +1572,7 @@ async def submit_subtitle( "data": json.dumps(data), "submit": submit, "sign": sign, - "bvid": self.get_bvid(), + "bvid": await self.__get_bvid(), } return await Api(**api, credential=self.credential).update_data(**payload).result @@ -1574,7 +1586,7 @@ async def get_danmaku_snapshot(self) -> dict: """ api = API["danmaku"]["snapshot"] - params = {"aid": self.get_aid()} + params = {"aid": await self.__get_aid()} return ( await Api(**api, credential=self.credential).update_params(**params).result @@ -1647,7 +1659,7 @@ async def add_to_toview(self) -> dict: self.credential.raise_for_no_bili_jct() api = get_api("toview")["operate"]["add"] datas = { - "aid": self.get_aid(), + "aid": await self.__get_aid(), } return await Api(**api, credential=self.credential).update_data(**datas).result @@ -1661,7 +1673,7 @@ async def delete_from_toview(self) -> dict: self.credential.raise_for_no_sessdata() self.credential.raise_for_no_bili_jct() api = get_api("toview")["operate"]["del"] - datas = {"viewed": "false", "aid": self.get_aid()} + datas = {"viewed": "false", "aid": await self.__get_aid()} return await Api(**api, credential=self.credential).update_data(**datas).result @@ -1792,7 +1804,7 @@ async def __main(self): cid = pages[self.__page_index]["cid"] # 获取服务器信息 - self.logger.debug(f"准备连接:{self.__video.get_bvid()}") + self.logger.debug(f"准备连接:{self.__video.__get_bvid()}") self.logger.debug(f"获取服务器信息中...") api = API["info"]["video_online_broadcast_servers"] @@ -1811,7 +1823,7 @@ async def __main(self): # 发送认证信息 self.logger.debug("服务器连接成功,准备发送认证信息...") verify_info = { - "room_id": f"video://{self.__video.get_aid()}/{cid}", + "room_id": f"video://{self.__video.__get_aid()}/{cid}", "platform": "web", "accepts": [1000, 1015], }