mirror of
https://github.com/amtoaer/bili-sync.git
synced 2026-09-05 07:28:04 +08:00
feat: 支持下载 cc 字幕 (#234)
This commit is contained in:
@@ -25,6 +25,7 @@ mod danmaku;
|
||||
mod error;
|
||||
mod favorite_list;
|
||||
mod submission;
|
||||
mod subtitle;
|
||||
mod video;
|
||||
mod watch_later;
|
||||
|
||||
@@ -197,4 +198,26 @@ mod tests {
|
||||
assert!(videos.iter().all(|v| matches!(v, VideoInfo::Submission { .. })));
|
||||
assert!(videos.iter().rev().is_sorted_by_key(|v| v.release_datetime()));
|
||||
}
|
||||
|
||||
#[ignore = "only for manual test"]
|
||||
#[tokio::test]
|
||||
async fn test_subtitle_parse() -> Result<()> {
|
||||
let bili_client = BiliClient::new();
|
||||
let Ok(Some(mixin_key)) = bili_client.wbi_img().await.map(|wbi_img| wbi_img.into()) else {
|
||||
panic!("获取 mixin key 失败");
|
||||
};
|
||||
set_global_mixin_key(mixin_key);
|
||||
let video = Video::new(&bili_client, "BV1gLfnY8E6D".to_string());
|
||||
let pages = video.get_pages().await?;
|
||||
println!("pages: {:?}", pages);
|
||||
let subtitles = video.get_subtitles(&pages[0]).await?;
|
||||
for subtitle in subtitles {
|
||||
println!(
|
||||
"{}: {}",
|
||||
subtitle.lan,
|
||||
subtitle.body.to_string().chars().take(200).collect::<String>()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SubTitlesInfo {
|
||||
pub subtitles: Vec<SubTitleInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SubTitleInfo {
|
||||
pub lan: String,
|
||||
pub subtitle_url: String,
|
||||
}
|
||||
|
||||
pub struct SubTitle {
|
||||
pub lan: String,
|
||||
pub body: SubTitleBody,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SubTitleBody(pub Vec<SubTitleItem>);
|
||||
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SubTitleItem {
|
||||
from: f64,
|
||||
to: f64,
|
||||
content: String,
|
||||
}
|
||||
|
||||
impl SubTitleInfo {
|
||||
pub fn is_ai_sub(&self) -> bool {
|
||||
// ai: aisubtitle.hdslb.com/bfs/ai_subtitle/xxxx
|
||||
// 非 ai: aisubtitle.hdslb.com/bfs/subtitle/xxxx
|
||||
self.subtitle_url.contains("ai_subtitle")
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for SubTitleBody {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for (idx, item) in self.0.iter().enumerate() {
|
||||
writeln!(f, "{}", idx)?;
|
||||
writeln!(f, "{} --> {}", format_time(item.from), format_time(item.to))?;
|
||||
writeln!(f, "{}", item.content)?;
|
||||
writeln!(f)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn format_time(time: f64) -> String {
|
||||
let (second, millisecond) = (time.trunc(), (time.fract() * 1e3) as u32);
|
||||
let (hour, minute, second) = (
|
||||
(second / 3600.0) as u32,
|
||||
((second % 3600.0) / 60.0) as u32,
|
||||
(second % 60.0) as u32,
|
||||
);
|
||||
format!("{:02}:{:02}:{:02},{:03}", hour, minute, second, millisecond)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn test_format_time() {
|
||||
// float 解析会有精度问题,但误差几毫秒应该不太关键
|
||||
// 想再健壮一点就得手写 serde_json 解析拆分秒和毫秒,然后分别处理了
|
||||
let testcases = [
|
||||
(0.0, "00:00:00,000"),
|
||||
(1.5, "00:00:01,500"),
|
||||
(206.45, "00:03:26,449"),
|
||||
(360001.23, "100:00:01,229"),
|
||||
];
|
||||
for (time, expect) in testcases.iter() {
|
||||
assert_eq!(super::format_time(*time), *expect);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use crate::bilibili::analyzer::PageAnalyzer;
|
||||
use crate::bilibili::client::BiliClient;
|
||||
use crate::bilibili::credential::encoded_query;
|
||||
use crate::bilibili::danmaku::{DanmakuElem, DanmakuWriter, DmSegMobileReply};
|
||||
use crate::bilibili::subtitle::{SubTitle, SubTitleBody, SubTitleInfo, SubTitlesInfo};
|
||||
use crate::bilibili::{Validate, VideoInfo, MIXIN_KEY};
|
||||
|
||||
static MASK_CODE: u64 = 2251799813685247;
|
||||
@@ -164,6 +165,44 @@ impl<'a> Video<'a> {
|
||||
.validate()?;
|
||||
Ok(PageAnalyzer::new(res["data"].take()))
|
||||
}
|
||||
|
||||
pub async fn get_subtitles(&self, page: &PageInfo) -> Result<Vec<SubTitle>> {
|
||||
let mut res = self
|
||||
.client
|
||||
.request(Method::GET, "https://api.bilibili.com/x/player/wbi/v2")
|
||||
.await
|
||||
.query(&encoded_query(
|
||||
vec![("cid", &page.cid.to_string()), ("bvid", &self.bvid), ("aid", &self.aid)],
|
||||
MIXIN_KEY.load().as_deref(),
|
||||
))
|
||||
.send()
|
||||
.await?
|
||||
.json::<serde_json::Value>()
|
||||
.await?
|
||||
.validate()?;
|
||||
// 接口返回的信息,包含了一系列的字幕,每个字幕包含了字幕的语言和 json 下载地址
|
||||
let subtitles_info: SubTitlesInfo = serde_json::from_value(res["data"]["subtitle"].take())?;
|
||||
let tasks = subtitles_info
|
||||
.subtitles
|
||||
.into_iter()
|
||||
.filter(|v| !v.is_ai_sub())
|
||||
.map(|v| self.get_subtitle(v))
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
tasks.try_collect().await
|
||||
}
|
||||
|
||||
async fn get_subtitle(&self, info: SubTitleInfo) -> Result<SubTitle> {
|
||||
let mut res = self
|
||||
.client
|
||||
.client // 这里可以直接使用 inner_client,因为该请求不需要鉴权
|
||||
.request(Method::GET, format!("https:{}", &info.subtitle_url).as_str(), None)
|
||||
.send()
|
||||
.await?
|
||||
.json::<serde_json::Value>()
|
||||
.await?;
|
||||
let body: SubTitleBody = serde_json::from_value(res["body"].take())?;
|
||||
Ok(SubTitle { lan: info.lan, body })
|
||||
}
|
||||
}
|
||||
|
||||
fn bvid_to_aid(bvid: &str) -> u64 {
|
||||
|
||||
Reference in New Issue
Block a user