Skip to content

Commit

Permalink
写点
Browse files Browse the repository at this point in the history
  • Loading branch information
amtoaer committed Jul 10, 2024
1 parent 45e05c6 commit d7896ae
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 5 deletions.
2 changes: 1 addition & 1 deletion crates/bili_sync/src/adapter/watch_later.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use sea_orm::ActiveValue::Set;
use sea_orm::{DatabaseConnection, QuerySelect, TransactionTrait};

use super::VideoListModel;
use crate::bilibili::{BiliClient, BiliError, Collection, CollectionItem, CollectionType, Video, VideoInfo};
use crate::bilibili::{BiliClient, BiliError, Video, VideoInfo, WatchLater};
use crate::config::TEMPLATE;
use crate::utils::id_time_key;
use crate::utils::model::create_video_pages;
Expand Down
2 changes: 1 addition & 1 deletion crates/bili_sync/src/bilibili/collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ impl<'a> Collection<'a> {
break;
},
};
for video_info in videos_info.into_iter(){
for video_info in videos_info{
yield video_info;
}
let fields = match self.collection.collection_type{
Expand Down
2 changes: 1 addition & 1 deletion crates/bili_sync/src/bilibili/favorite_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl<'a> FavoriteList<'a> {
break;
},
};
for video_info in videos_info.into_iter(){
for video_info in videos_info{
yield video_info;
}
if videos["data"]["has_more"].is_boolean() && videos["data"]["has_more"].as_bool().unwrap(){
Expand Down
33 changes: 33 additions & 0 deletions crates/bili_sync/src/bilibili/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub use error::BiliError;
pub use favorite_list::FavoriteList;
use favorite_list::Upper;
pub use video::{Dimension, PageInfo, Video};
pub use watch_later::WatchLater;

mod analyzer;
mod client;
Expand Down Expand Up @@ -93,3 +94,35 @@ pub enum VideoInfo {
pubtime: DateTime<Utc>,
},
}

#[cfg(test)]
mod tests {
use futures::StreamExt;
use tokio::pin;

use super::*;

#[tokio::test]
async fn assert_video_info() {
let bili_client = BiliClient::new();
let video = Video::new(&bili_client, "BV1Z54y1C7ZB".to_string());
assert!(matches!(video.get_view_info().await, Ok(VideoInfo::View { .. })));
let collection_item = CollectionItem {
mid: "521722088".to_string(),
sid: "387214".to_string(),
collection_type: CollectionType::Series,
};
let collection = Collection::new(&bili_client, &collection_item);
let stream = collection.into_simple_video_stream();
pin!(stream);
assert!(matches!(stream.next().await, Some(VideoInfo::Simple { .. })));
let favorite = FavoriteList::new(&bili_client, "3084505258".to_string());
let stream = favorite.into_video_stream();
pin!(stream);
assert!(matches!(stream.next().await, Some(VideoInfo::Detail { .. })));
let watch_later = WatchLater::new(&bili_client);
let stream = watch_later.into_video_stream();
pin!(stream);
assert!(matches!(stream.next().await, Some(VideoInfo::Simple { .. })));
}
}
48 changes: 48 additions & 0 deletions crates/bili_sync/src/bilibili/watch_later.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use anyhow::Result;
use async_stream::stream;
use futures::Stream;
use serde_json::Value;

use crate::bilibili::{BiliClient, Validate, VideoInfo};
pub struct WatchLater<'a> {
client: &'a BiliClient,
}

impl<'a> WatchLater<'a> {
pub fn new(client: &'a BiliClient) -> Self {
Self { client }
}

async fn get_videos(&self) -> Result<Value> {
self.client
.request(reqwest::Method::GET, "https://api.bilibili.com/x/v2/history/toview")
.send()
.await?
.error_for_status()?
.json::<serde_json::Value>()
.await?
.validate()
}

pub fn into_video_stream(self) -> impl Stream<Item = VideoInfo> + 'a {
stream! {
let Ok(mut videos) = self.get_videos().await else {
error!("Failed to get watch later list");
return;
};
if !videos["data"]["list"].is_array() {
error!("Watch later list is not an array");
}
let videos_info = match serde_json::from_value::<Vec<VideoInfo>>(videos["data"]["list"].take()) {
Ok(v) => v,
Err(e) => {
error!("Failed to parse watch later list: {}", e);
return;
}
};
for video in videos_info {
yield video;
}
}
}
}
19 changes: 17 additions & 2 deletions crates/bili_sync/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ pub struct Config {
deserialize_with = "deserialize_collection_list"
)]
pub collection_list: HashMap<CollectionItem, PathBuf>,
#[serde(default)]
pub watch_later: WatchLaterConfig,
pub video_name: Cow<'static, str>,
pub page_name: Cow<'static, str>,
pub interval: u64,
Expand All @@ -76,6 +78,12 @@ pub struct Config {
pub nfo_time_type: NFOTimeType,
}

#[derive(Serialize, Deserialize, Default)]
pub struct WatchLaterConfig {
pub enabled: bool,
pub path: PathBuf,
}

#[derive(Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum NFOTimeType {
Expand All @@ -92,6 +100,7 @@ impl Default for Config {
danmaku_option: DanmakuOption::default(),
favorite_list: HashMap::new(),
collection_list: HashMap::new(),
watch_later: Default::default(),
video_name: Cow::Borrowed("{{title}}"),
page_name: Cow::Borrowed("{{bvid}}"),
interval: 1200,
Expand All @@ -105,9 +114,15 @@ impl Config {
/// 简单的预检查
pub fn check(&self) {
let mut ok = true;
if self.favorite_list.is_empty() && self.collection_list.is_empty() {
if self.favorite_list.is_empty() && self.collection_list.is_empty() && !self.watch_later.enabled {
ok = false;
error!("未设置需监听的收藏夹或视频合集,程序空转没有意义");
error!("没有配置任何需要扫描的内容,程序空转没有意义");
}
if self.watch_later.enabled && !self.watch_later.path.is_absolute() {
error!(
"稍后再看保存的路径应为绝对路径,检测到:{}",
self.watch_later.path.display()
);
}
for path in self.favorite_list.values() {
if !path.is_absolute() {
Expand Down
8 changes: 8 additions & 0 deletions crates/bili_sync/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ async fn main() {
let connection = database_connection().await.expect("获取数据库连接失败");
let mut anchor = chrono::Local::now().date_naive();
let bili_client = BiliClient::new();
let watch_later_config = &CONFIG.watch_later;
loop {
if let Err(e) = bili_client.is_login().await {
error!("检查登录状态时遇到错误:{e},等待下一轮执行");
Expand Down Expand Up @@ -57,6 +58,13 @@ async fn main() {
}
}
info!("所有合集处理完毕");
if watch_later_config.enabled {
if let Err(e) =
process_video_list(Args::WatchLater, &bili_client, &watch_later_config.path, &connection).await
{
error!("处理稍后再看时遇到非预期的错误:{e}");
}
}
info!("本轮任务执行完毕,等待下一轮执行");
tokio::time::sleep(std::time::Duration::from_secs(CONFIG.interval)).await;
}
Expand Down

0 comments on commit d7896ae

Please sign in to comment.