Skip to content

Commit

Permalink
chore: fix some issues from pylint, remove module Opus.
Browse files Browse the repository at this point in the history
  • Loading branch information
Nemo2011 committed Dec 16, 2024
1 parent 3cdd02d commit ffdd2a3
Show file tree
Hide file tree
Showing 15 changed files with 44 additions and 572 deletions.
2 changes: 0 additions & 2 deletions bilibili_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@
manga,
music,
note,
opus,
rank,
search,
session,
Expand Down Expand Up @@ -162,7 +161,6 @@
"manga",
"music",
"note",
"opus",
"parse_link",
"rank",
"search",
Expand Down
146 changes: 9 additions & 137 deletions bilibili_api/article.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@
from .utils.utils import get_api, raise_for_statement
from .utils.credential import Credential
from .utils.network import Api
from .utils import cache_pool
from .exceptions.NetworkException import ApiException, NetworkException
from .video import get_cid_info_sync
from . import note
from . import opus

API = get_api("article")

Expand Down Expand Up @@ -63,20 +60,6 @@
}


class ArticleType(Enum):
"""
专栏类型
- ARTICLE : 普通专栏,不与 opus 图文兼容。
- OPUS : opus。
- SPECIAL_ARTICLE: 特殊专栏,与 opus 兼容。
"""

ARTICLE = 3
OPUS = 4
SPECIAL_ARTICLE = 5


class ArticleRankingType(Enum):
"""
专栏排行榜类型枚举。
Expand Down Expand Up @@ -176,22 +159,6 @@ def __init__(self, cvid: int, credential: Union[Credential, None] = None):
self.__meta = None
self.__cvid = cvid
self.__has_parsed: bool = False
self.__is_note = False

# 设置专栏类别
if cache_pool.article_is_opus.get(self.__cvid):
self.__type = ArticleType.SPECIAL_ARTICLE
self.__is_note = cache_pool.article_is_note[self.__cvid]
else:
resp = get_initial_state_sync(
f"https://www.bilibili.com/read/cv{self.__cvid}"
)[0]
self.__dyn_id = int(resp["readInfo"]["dyn_id_str"])
self.__type = ArticleType(resp["readInfo"]["template_id"])
self.__is_note = resp["readInfo"]["type"] == 2

if cache_pool.article_dyn_id.get(self.__cvid):
self.__dyn_id = cache_pool.article_dyn_id[self.__cvid]

def get_cvid(self) -> int:
"""
Expand All @@ -202,46 +169,6 @@ def get_cvid(self) -> int:
"""
return self.__cvid

def get_type(self) -> ArticleType:
"""
获取专栏类型(专栏/笔记)
Returns:
ArticleType: 专栏类型
"""
return self.__type

def is_note(self) -> bool:
"""
检查专栏是否笔记
Returns:
bool: 是否笔记
"""
return self.__is_note

def turn_to_note(self) -> "note.Note":
"""
对于完全与 opus 兼容的部分的特殊专栏,将 Article 对象转换为 Dynamic 对象。
Returns:
Note: 笔记类
"""
raise_for_statement(self.is_note(), "仅支持公开笔记")
return note.Note(
cvid=self.__cvid, note_type=note.NoteType.PUBLIC, credential=self.credential
)

def turn_to_opus(self) -> "opus.Opus":
"""
对于 SPECIAL_ARTICLE,将其转为图文
"""
raise_for_statement(self.__type != ArticleType.ARTICLE, "仅支持图文专栏")
cache_pool.opus_type[self.__dyn_id] = 1
cache_pool.opus_is_note[self.__dyn_id] = self.is_note()
cache_pool.opus_cvid[self.__dyn_id] = self.__cvid
return opus.Opus(self.__dyn_id, credential=self.credential)

def markdown(self) -> str:
"""
转换为 Markdown
Expand Down Expand Up @@ -546,82 +473,27 @@ async def parse(el: BeautifulSoup):
elif e.name == "img":
className = e.attrs.get("class")

if not className:
if "latex" in className:
# 公式
node = LatexNode()
node.code = unquote(e["alt"]) # type: ignore
node_list.append(node)
else:
# 图片
node = ImageNode()
node.url = e.attrs.get("data-src") # type: ignore
node_list.append(node)

elif "latex" in className:
# 公式
node = LatexNode()
node_list.append(node)

node.code = unquote(e["alt"]) # type: ignore
elif e.name == "div":
node_list += (await parse(e))

return node_list

def parse_note(data: List[dict]):
for field in data:
if not isinstance(field["insert"], str):
if "tag" in field["insert"].keys():
node = VideoCardNode()
node.aid = get_cid_info_sync(field["insert"]["tag"]["cid"])[
"cid"
]
self.__children.append(node)
elif "imageUpload" in field["insert"].keys():
node = ImageNode()
node.url = field["insert"]["imageUpload"]["url"]
self.__children.append(node)
elif "cut-off" in field["insert"].keys():
node = ImageNode()
node.url = field["insert"]["cut-off"]["url"]
self.__children.append(node)
elif "native-image" in field["insert"].keys():
node = ImageNode()
node.url = field["insert"]["native-image"]["url"]
self.__children.append(node)
else:
raise Exception()
else:
node = TextNode(field["insert"])
if "attributes" in field.keys():
if field["attributes"].get("bold") == True:
bold = BoldNode()
bold.children = [node]
node = bold
if field["attributes"].get("strike") == True:
delete = DelNode()
delete.children = [node]
node = delete
if field["attributes"].get("underline") == True:
underline = UnderlineNode()
underline.children = [node]
node = underline
if field["attributes"].get("background") == True:
# FIXME: 暂不支持背景颜色
pass
if field["attributes"].get("color") != None:
color = ColorNode()
color.color = field["attributes"]["color"].replace("#", "")
color.children = [node]
node = color
if field["attributes"].get("size") != None:
size = FontSizeNode()
size.size = field["attributes"]["size"]
size.children = [node]
node = size
else:
pass
self.__children.append(node)

# 文章元数据
self.__meta = copy(resp["readInfo"])
del self.__meta["content"]

self.__children = await parse(document.find("div"))

self.__has_parsed = True

async def get_info(self) -> dict:
Expand All @@ -646,7 +518,7 @@ async def get_all(self) -> dict:
dict: 调用 API 返回的结果
"""
return (
await get_initial_state(f"https://www.bilibili.com/read/cv{self.__cvid}")
await get_initial_state(f"https://www.bilibili.com/read/cv{self.__cvid}/?jump_opus=1")
)[0]

async def set_like(self, status: bool = True) -> dict:
Expand Down
2 changes: 1 addition & 1 deletion bilibili_api/ass.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ async def make_ass_file_subtitle(
if credential.has_sessdata():
obj.credential = credential
elif not obj.credential.has_sessdata():
raise credential.raise_for_no_sessdata()
credential.raise_for_no_sessdata()

if isinstance(obj, Episode):
info = await obj.get_player_info(cid=await obj.get_cid(), epid=obj.get_epid())
Expand Down
17 changes: 8 additions & 9 deletions bilibili_api/bangumi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1537,15 +1537,14 @@ async def get_download_url(self) -> dict:
dict: 调用 API 返回的结果。
"""
api = API["info"]["playurl"]
if True:
params = {
"avid": await self.get_aid(),
"ep_id": self.get_epid(),
"qn": "127",
"otype": "json",
"fnval": 4048,
"fourk": 1,
}
params = {
"avid": await self.get_aid(),
"ep_id": self.get_epid(),
"qn": "127",
"otype": "json",
"fnval": 4048,
"fourk": 1,
}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
Expand Down
2 changes: 1 addition & 1 deletion bilibili_api/data/api/opus.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"object_id_str": "890484395664736288",
"type": { "biz": 2 }
},
"action": 4
"action": "int: 3 or 4"
},
"json_body": true,
"comment": "收藏/取消收藏"
Expand Down
57 changes: 11 additions & 46 deletions bilibili_api/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
from . import user, vote, exceptions
from .utils.credential import Credential
from .utils.network import Api
from .utils import cache_pool
from .exceptions.DynamicExceedImagesException import DynamicExceedImagesException
from . import opus

API = utils.get_api("dynamic")
raise_for_statement = utils.raise_for_statement
Expand Down Expand Up @@ -784,61 +782,23 @@ def __init__(
credential if credential is not None else Credential()
)

if cache_pool.dynamic_is_opus.get(self.__dynamic_id):
self.__opus = cache_pool.dynamic_is_opus[self.__dynamic_id]
else:
api = API["info"]["detail"]
params = {
"id": self.__dynamic_id,
"timezone_offset": -480,
"platform": "web",
"gaia_source": "main_web",
"features": "itemOpusStyle,opusBigCover,onlyfansVote,endFooterHidden,decorationCard,onlyfansAssetsV2,ugcDelete",
"web_location": "333.1368",
"x-bili-device-req-json": '{"platform":"web","device":"pc"}',
"x-bili-web-req-json": '{"spm_id":"333.1368"}',
}
data = (
Api(**api, credential=self.credential)
.update_params(**params)
.result_sync
)
self.__opus = data["item"]["basic"]["comment_type"] != 11
cache_pool.dynamic_is_opus[self.__dynamic_id] = self.__opus

def get_dynamic_id(self) -> int:
def get_dynamic_id(self) -> None:
"""
获取动态 id
获取 动态 ID。
Returns:
int: _description_
int: 动态 ID。
"""
return self.__dynamic_id

def is_opus(self) -> DynamicType:
"""
判断是否为 opus 动态
Returns:
bool: 是否为 opus 动态
"""
return self.__opus

def turn_to_opus(self) -> "opus.Opus":
"""
对 opus 动态,将其转换为图文
"""
raise_for_statement(self.__opus, "仅支持图文动态")
return opus.Opus(self.__dynamic_id, credential=self.credential)

async def get_info(self, features: str = "itemOpusStyle") -> dict:
async def get_info(self, features: str = "itemOpusStyle,opusBigCover,onlyfansVote,endFooterHidden,decorationCard,onlyfansAssetsV2,ugcDelete") -> dict:
"""
(对 Opus 动态,获取动态内容建议使用 Opus.get_detail())
获取动态信息
Args:
features (str, optional): 默认 itemOpusStyle.
features (str, optional): 默认 itemOpusStyle,opusBigCover,onlyfansVote,endFooterHidden,decorationCard,onlyfansAssetsV2,ugcDelete.
Returns:
dict: 调用 API 返回的结果
Expand All @@ -848,7 +808,12 @@ async def get_info(self, features: str = "itemOpusStyle") -> dict:
params = {
"id": self.__dynamic_id,
"timezone_offset": -480,
"platform": "web",
"gaia_source": "main_web",
"features": features,
"web_location": "333.1368",
"x-bili-device-req-json": '{"platform":"web","device":"pc"}',
"x-bili-web-req-json": '{"spm_id":"333.1368"}',
}
data = (
await Api(**api, credential=self.credential).update_params(**params).result
Expand All @@ -867,7 +832,7 @@ async def get_reaction(self, offset: str = "") -> dict:
"""

api = API["info"]["reaction"]
params = {"web_location": "333.1369", "offset": "", "id": self.get_dynamic_id()}
params = {"web_location": "333.1369", "offset": "", "id": self.__dynamic_id}
return (
await Api(**api, credential=self.credential).update_params(**params).result
)
Expand Down
Loading

0 comments on commit ffdd2a3

Please sign in to comment.