Skip to content

Commit

Permalink
Merge pull request #615 from iconFehu/dev
Browse files Browse the repository at this point in the history
feat: 新增同步请求, 替换部分httpx代码处
  • Loading branch information
z0z0r4 authored Dec 30, 2023
2 parents 16abaf7 + f1376f6 commit 65c0d79
Show file tree
Hide file tree
Showing 14 changed files with 345 additions and 100 deletions.
9 changes: 2 additions & 7 deletions bilibili_api/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@
from .utils.credential import Credential
from .utils.network import Api, get_session
from .exceptions.NetworkException import ApiException, NetworkException
from .video import get_cid_info_sync

API = get_api("article")


# 文章颜色表
ARTICLE_COLOR_MAP = {
"default": "222222",
Expand Down Expand Up @@ -526,12 +526,7 @@ def parse_note(data: List[dict]):
if not isinstance(field["insert"], str):
if "tag" in field["insert"].keys():
node = VideoCardNode()
node.aid = json.loads(
httpx.get(
"https://hd.biliplus.com/api/cidinfo?cid="
+ str(field["insert"]["tag"]["cid"])
).text
)["data"]["cid"]
node.aid = get_cid_info_sync(field["insert"]["tag"]["cid"])["cid"]
self.__children.append(node)
elif "imageUpload" in field["insert"].keys():
node = ImageNode()
Expand Down
26 changes: 6 additions & 20 deletions bilibili_api/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import httpx

from .user import name2uid_sync
from .utils import utils
from .utils.sync import sync
from .utils.picture import Picture
Expand Down Expand Up @@ -303,14 +304,7 @@ def add_at(self, uid: Union[int, user.User]) -> "BuildDynmaic":
"""
if isinstance(uid, user.User):
uid = uid.__uid
name = httpx.get(
"https://api.bilibili.com/x/space/acc/info",
params={"mid": uid},
headers={
"User-Agent": "Mozilla/5.0",
"Referer": "https://www.bilibili.com",
},
).json()["data"]["name"]
name = user.User(uid).get_user_info_sync().get("name")
self.contents.append(
{"biz_id": uid, "type": DynmaicContentType.AT.value, "raw_text": f"@{name}"}
)
Expand Down Expand Up @@ -339,17 +333,12 @@ def add_emoji(self, emoji_id: int) -> "BuildDynmaic":
return self

def add_vote(self, vote: vote.Vote) -> "BuildDynmaic":
vote_info = httpx.get(
"https://api.vc.bilibili.com/vote_svr/v1/vote_svr/vote_info?vote_id={}".format(
vote.get_vote_id()
)
).json()
title = vote_info["data"]["info"]["title"]
vote.get_info_sync()
self.contents.append(
{
"biz_id": str(vote.get_vote_id()),
"type": DynmaicContentType.VOTE.value,
"raw_text": title,
"raw_text": vote.title,
}
)
return self
Expand Down Expand Up @@ -383,11 +372,8 @@ def _get_ats(text: str) -> List:
for match in match_result:
uname = match.group()
try:
name_to_uid_resp = httpx.get(
"https://api.vc.bilibili.com/dynamic_mix/v1/dynamic_mix/name_to_uid?",
params={"names": uname},
)
uid = name_to_uid_resp.json()["data"]["uid_list"][0]["uid"]
name_to_uid_resp = name2uid_sync(uname)
uid = name_to_uid_resp["uid_list"][0]["uid"]
except KeyError:
# 没有此用户
continue
Expand Down
13 changes: 4 additions & 9 deletions bilibili_api/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from .utils.utils import get_api
from .utils.credential import Credential
from .exceptions.LoginError import LoginError
from .utils.network import to_form_urlencoded
from .utils.network import to_form_urlencoded, Api
from .utils.network import HEADERS, get_session, get_spi_buvid_sync
from .utils.captcha import get_result, close_server, start_server
from .utils.safecenter_captcha import get_result as safecenter_get_result
Expand Down Expand Up @@ -86,7 +86,7 @@ def make_qrcode(url) -> str:

def update_qrcode_data() -> dict:
api = API["qrcode"]["get_qrcode_and_token"]
qrcode_data = httpx.get(api["url"], follow_redirects=True, headers=HEADERS).json()["data"]
qrcode_data = Api(credential=credential, **api).result_sync
return qrcode_data


Expand Down Expand Up @@ -203,12 +203,7 @@ def login_with_qrcode_term() -> Credential:
def login_with_key(key: str) -> dict:
params = {"qrcode_key": key, "source": "main-fe-header"}
events_api = API["qrcode"]["get_events"]
events = httpx.get(
events_api["url"],
params=params,
cookies={"buvid3": str(uuid.uuid1()), "Domain": ".bilibili.com"},
headers=HEADERS
).json()
events = Api(credential=credential, **events_api, params=params).result_sync
return events


Expand Down Expand Up @@ -602,4 +597,4 @@ def fetch_info(self) -> dict:
api = API["safecenter"]["check_info"]
self.tmp_token = self.check_url.split("?")[1].split("&")[0][10:]
params = {"tmp_code": self.tmp_token}
return json.loads(httpx.get(api["url"], params=params).text)["data"]
return Api(credential=credential, **api, params=params).result_sync
8 changes: 2 additions & 6 deletions bilibili_api/note.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from .utils.credential import Credential
from .exceptions import ApiException, ArgsException
from .utils.network import Api, get_session
from .video import get_cid_info_sync

API = get_api("note")
API_ARTICLE = get_api("article")
Expand Down Expand Up @@ -276,12 +277,7 @@ def parse_note(data: List[dict]):
if not isinstance(field["insert"], str):
if "tag" in field["insert"].keys():
node = VideoCardNode()
node.aid = json.loads(
httpx.get(
"https://hd.biliplus.com/api/cidinfo?cid="
+ str(field["insert"]["tag"]["cid"])
).text
)["data"]["cid"]
node.aid = get_cid_info_sync(field["insert"]["tag"]["cid"])["cid"]
self.__children.append(node)
elif "imageUpload" in field["insert"].keys():
node = ImageNode()
Expand Down
20 changes: 20 additions & 0 deletions bilibili_api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,26 @@
"""

import logging
from enum import Enum

class HTTPClient(Enum):
"""
- AioHttp: aiohttp
- Httpx: httpx
"""

AIOHTTP = "aiohttp"
HTTPX = "httpx"

http_client: HTTPClient = HTTPClient.AIOHTTP
"""
用于设置使用的 HTTP 客户端,默认为 Httpx
e.x.:
``` python
from bilibili_api import settings
settings.http_client = settings.HTTPClient.AIOHTTP
"""

proxy: str = ""
"""
Expand Down
41 changes: 37 additions & 4 deletions bilibili_api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,24 @@ class OrderType(Enum):
asc = "asc"


async def name2uid_sync(names: Union[str, List[str]]):
"""
将用户名转为 uid
Args:
names (str/List[str]): 用户名
Returns:
dict: 调用 API 返回的结果
"""
if isinstance(names, str):
n = names
else:
n = ",".join(names)
params = {"names": n}
return Api(**API["info"]["name_to_uid"]).update_params(**params).result_sync


async def name2uid(names: Union[str, List[str]]):
"""
将用户名转为 uid
Expand Down Expand Up @@ -234,6 +252,21 @@ def __init__(self, uid: int, credential: Union[Credential, None] = None):
self.credential = credential
self.__self_info = None

def get_user_info_sync(self) -> dict:
"""
获取用户信息(昵称,性别,生日,签名,头像 URL,空间横幅 URL 等)
Returns:
dict: 调用接口返回的内容。
[用户空间详细信息](https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/docs/user/info.md#%E7%94%A8%E6%88%B7%E7%A9%BA%E9%97%B4%E8%AF%A6%E7%BB%86%E4%BF%A1%E6%81%AF)
"""
params = {
"mid": self.__uid,
}
result = Api(**API["info"]["info"], credential=self.credential, params=params).result_sync
return result

async def get_user_info(self) -> dict:
"""
获取用户信息(昵称,性别,生日,签名,头像 URL,空间横幅 URL 等)
Expand Down Expand Up @@ -438,7 +471,7 @@ async def get_videos(
"keyword": keyword,
"order": order.value,
# -352 https://github.com/Nemo2011/bilibili-api/issues/595
"dm_img_list": "[]", # 鼠标/键盘操作记录
"dm_img_list": "[]", # 鼠标/键盘操作记录
# WebGL 1.0 (OpenGL ES 2.0 Chromium)
"dm_img_str": "V2ViR0wgMS4wIChPcGVuR0wgRVMgMi4wIENocm9taXVtKQ",
# ANGLE (Intel, Intel(R) UHD Graphics 630 (0x00003E9B) Direct3D11 vs_5_0 ps_5_0, D3D11)Google Inc. (Intel
Expand All @@ -450,7 +483,7 @@ async def get_videos(

async def get_media_list(
self,
oid: int|None = None,
oid: int | None = None,
ps: int = 20,
direction: bool = False,
desc: bool = True,
Expand Down Expand Up @@ -961,7 +994,7 @@ async def get_channels(self) -> List["ChannelSeries"]:
meta = item["meta"]
channel_series.channel_meta_cache[
str(ChannelSeriesType.SEASON.value) + "-" + str(id_)
] = meta
] = meta
channels.append(
ChannelSeries(
self.__uid, ChannelSeriesType.SEASON, id_, self.credential
Expand All @@ -972,7 +1005,7 @@ async def get_channels(self) -> List["ChannelSeries"]:
meta = item["meta"]
channel_series.channel_meta_cache[
str(ChannelSeriesType.SERIES.value) + "-" + str(id_)
] = meta
] = meta
channels.append(
ChannelSeries(
self.__uid, ChannelSeriesType.SERIES, id_, self.credential
Expand Down
Loading

0 comments on commit 65c0d79

Please sign in to comment.