From b441f04cdf8e00660b3d363459f74ede389244db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=80=E1=B4=8D=E1=B4=9B=E1=B4=8F=E1=B4=80=E1=B4=87?= =?UTF-8?q?=CA=80?= Date: Wed, 24 Sep 2025 17:36:20 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E4=BF=AE=E5=A4=8D=E6=96=B0=E7=9A=84?= =?UTF-8?q?=20clippy=20warnings=20(#467)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/bili_sync/src/adapter/collection.rs | 9 ++-- .../bili_sync/src/api/routes/dashboard/mod.rs | 4 +- crates/bili_sync/src/api/routes/mod.rs | 13 +++-- crates/bili_sync/src/api/routes/ws/mod.rs | 16 +++--- crates/bili_sync/src/bilibili/analyzer.rs | 54 +++++++++---------- crates/bili_sync/src/downloader.rs | 2 +- crates/bili_sync/src/error.rs | 8 +-- crates/bili_sync/src/task/http_server.rs | 40 +++++++------- crates/bili_sync/src/utils/rule.rs | 6 +-- crates/bili_sync/src/utils/task_notifier.rs | 15 +----- crates/bili_sync/src/workflow.rs | 16 +++--- .../bili_sync_entity/src/custom_type/rule.rs | 4 +- 12 files changed, 87 insertions(+), 100 deletions(-) diff --git a/crates/bili_sync/src/adapter/collection.rs b/crates/bili_sync/src/adapter/collection.rs index b320f15..d7027b3 100644 --- a/crates/bili_sync/src/adapter/collection.rs +++ b/crates/bili_sync/src/adapter/collection.rs @@ -56,11 +56,12 @@ impl VideoSource for collection::Model { latest_row_at: &chrono::DateTime, ) -> Option { // 由于 collection 的视频无固定时间顺序,should_take 无法提前中断拉取,因此 should_filter 环节需要进行额外过滤 - if let Ok(video_info) = video_info { - if video_info.release_datetime() > latest_row_at { - return Some(video_info); - } + if let Ok(video_info) = video_info + && video_info.release_datetime() > latest_row_at + { + return Some(video_info); } + None } diff --git a/crates/bili_sync/src/api/routes/dashboard/mod.rs b/crates/bili_sync/src/api/routes/dashboard/mod.rs index 747d32f..fac4f23 100644 --- a/crates/bili_sync/src/api/routes/dashboard/mod.rs +++ b/crates/bili_sync/src/api/routes/dashboard/mod.rs @@ -55,11 +55,11 @@ ORDER BY )) .all(&db), )?; - return Ok(ApiResponse::ok(DashBoardResponse { + Ok(ApiResponse::ok(DashBoardResponse { enabled_favorites, enabled_collections, enabled_submissions, enable_watch_later: enabled_watch_later > 0, videos_by_day, - })); + })) } diff --git a/crates/bili_sync/src/api/routes/mod.rs b/crates/bili_sync/src/api/routes/mod.rs index 4706aff..d79afdc 100644 --- a/crates/bili_sync/src/api/routes/mod.rs +++ b/crates/bili_sync/src/api/routes/mod.rs @@ -43,17 +43,16 @@ pub async fn auth(mut headers: HeaderMap, request: Request, next: Next) -> Resul { return Ok(next.run(request).await); } - if let Some(protocol) = headers.remove("Sec-WebSocket-Protocol") { - if protocol + if let Some(protocol) = headers.remove("Sec-WebSocket-Protocol") + && protocol .to_str() .ok() .and_then(|s| BASE64_URL_SAFE_NO_PAD.decode(s).ok()) .is_some_and(|s| s == token.as_bytes()) - { - let mut resp = next.run(request).await; - resp.headers_mut().insert("Sec-WebSocket-Protocol", protocol); - return Ok(resp); - } + { + let mut resp = next.run(request).await; + resp.headers_mut().insert("Sec-WebSocket-Protocol", protocol); + return Ok(resp); } Ok(ApiResponse::<()>::unauthorized("auth token does not match").into_response()) } diff --git a/crates/bili_sync/src/api/routes/ws/mod.rs b/crates/bili_sync/src/api/routes/ws/mod.rs index 5a62836..c81c49d 100644 --- a/crates/bili_sync/src/api/routes/ws/mod.rs +++ b/crates/bili_sync/src/api/routes/ws/mod.rs @@ -118,7 +118,7 @@ impl WebSocketHandler { let rx = log_writer_clone.sender.subscribe(); let log_stream = futures::stream::iter(history_logs.into_iter()) .chain(BroadcastStream::new(rx).filter_map(async |msg| msg.ok())) - .map(|msg| ServerEvent::Logs(msg)); + .map(ServerEvent::Logs); pin!(log_stream); while let Some(event) = log_stream.next().await { if let Err(e) = tx_clone.send(event).await { @@ -133,8 +133,8 @@ impl WebSocketHandler { if task_handle.as_ref().is_none_or(|h: &JoinHandle<()>| h.is_finished()) { let tx_clone = tx.clone(); task_handle = Some(tokio::spawn(async move { - let mut stream = WatchStream::new(TASK_STATUS_NOTIFIER.subscribe()) - .map(|status| ServerEvent::Tasks(status)); + let mut stream = + WatchStream::new(TASK_STATUS_NOTIFIER.subscribe()).map(ServerEvent::Tasks); while let Some(event) = stream.next().await { if let Err(e) = tx_clone.send(event).await { error!("Failed to send task status: {:?}", e); @@ -179,7 +179,7 @@ impl WebSocketHandler { // 添加订阅者 async fn add_sysinfo_subscriber(&self, uuid: Uuid, sender: tokio::sync::mpsc::Sender) { self.sysinfo_subscribers.insert(uuid, sender); - if self.sysinfo_subscribers.len() > 0 + if !self.sysinfo_subscribers.is_empty() && self .sysinfo_handles .read() @@ -235,10 +235,10 @@ impl WebSocketHandler { async fn remove_sysinfo_subscriber(&self, uuid: Uuid) { self.sysinfo_subscribers.remove(&uuid); - if self.sysinfo_subscribers.is_empty() { - if let Some(handle) = self.sysinfo_handles.write().take() { - handle.abort(); - } + if self.sysinfo_subscribers.is_empty() + && let Some(handle) = self.sysinfo_handles.write().take() + { + handle.abort(); } } } diff --git a/crates/bili_sync/src/bilibili/analyzer.rs b/crates/bili_sync/src/bilibili/analyzer.rs index 4bb3515..fd3b664 100644 --- a/crates/bili_sync/src/bilibili/analyzer.rs +++ b/crates/bili_sync/src/bilibili/analyzer.rs @@ -263,39 +263,37 @@ impl PageAnalyzer { }); } } - if !filter_option.no_hires { - if let Some(flac) = self.info.pointer_mut("/dash/flac/audio") { - let (Some(url), Some(quality)) = (flac["baseUrl"].as_str(), flac["id"].as_u64()) else { - bail!("invalid flac stream"); - }; - let quality = AudioQuality::from_repr(quality as usize).context("invalid flac stream quality")?; - if quality >= filter_option.audio_min_quality && quality <= filter_option.audio_max_quality { - streams.push(Stream::DashAudio { - url: url.to_string(), - backup_url: serde_json::from_value(flac["backupUrl"].take()).unwrap_or_default(), - quality, - }); - } + if !filter_option.no_hires + && let Some(flac) = self.info.pointer_mut("/dash/flac/audio") + { + let (Some(url), Some(quality)) = (flac["baseUrl"].as_str(), flac["id"].as_u64()) else { + bail!("invalid flac stream"); + }; + let quality = AudioQuality::from_repr(quality as usize).context("invalid flac stream quality")?; + if quality >= filter_option.audio_min_quality && quality <= filter_option.audio_max_quality { + streams.push(Stream::DashAudio { + url: url.to_string(), + backup_url: serde_json::from_value(flac["backupUrl"].take()).unwrap_or_default(), + quality, + }); } } - if !filter_option.no_dolby_audio { - if let Some(dolby_audio) = self + if !filter_option.no_dolby_audio + && let Some(dolby_audio) = self .info .pointer_mut("/dash/dolby/audio/0") .and_then(|a| a.as_object_mut()) - { - let (Some(url), Some(quality)) = (dolby_audio["baseUrl"].as_str(), dolby_audio["id"].as_u64()) else { - bail!("invalid dolby audio stream"); - }; - let quality = - AudioQuality::from_repr(quality as usize).context("invalid dolby audio stream quality")?; - if quality >= filter_option.audio_min_quality && quality <= filter_option.audio_max_quality { - streams.push(Stream::DashAudio { - url: url.to_string(), - backup_url: serde_json::from_value(dolby_audio["backupUrl"].take()).unwrap_or_default(), - quality, - }); - } + { + let (Some(url), Some(quality)) = (dolby_audio["baseUrl"].as_str(), dolby_audio["id"].as_u64()) else { + bail!("invalid dolby audio stream"); + }; + let quality = AudioQuality::from_repr(quality as usize).context("invalid dolby audio stream quality")?; + if quality >= filter_option.audio_min_quality && quality <= filter_option.audio_max_quality { + streams.push(Stream::DashAudio { + url: url.to_string(), + backup_url: serde_json::from_value(dolby_audio["backupUrl"].take()).unwrap_or_default(), + quality, + }); } } Ok(streams) diff --git a/crates/bili_sync/src/downloader.rs b/crates/bili_sync/src/downloader.rs index 8bd8860..7976cbe 100644 --- a/crates/bili_sync/src/downloader.rs +++ b/crates/bili_sync/src/downloader.rs @@ -149,7 +149,7 @@ impl Downloader { } } } - res.with_context(|| format!("failed to download file")) + res.context("failed to download file") } pub async fn merge(&self, video_path: &Path, audio_path: &Path, output_path: &Path) -> Result<()> { diff --git a/crates/bili_sync/src/error.rs b/crates/bili_sync/src/error.rs index 8218dad..e7807fc 100644 --- a/crates/bili_sync/src/error.rs +++ b/crates/bili_sync/src/error.rs @@ -42,10 +42,10 @@ impl From> for ExecutionStatus { } } // 未包裹的 reqwest::Error - if let Some(error) = cause.downcast_ref::() { - if is_ignored_reqwest_error(error) { - return ExecutionStatus::Ignored(err); - } + if let Some(error) = cause.downcast_ref::() + && is_ignored_reqwest_error(error) + { + return ExecutionStatus::Ignored(err); } } ExecutionStatus::Failed(err) diff --git a/crates/bili_sync/src/task/http_server.rs b/crates/bili_sync/src/task/http_server.rs index dc72f22..f624598 100644 --- a/crates/bili_sync/src/task/http_server.rs +++ b/crates/bili_sync/src/task/http_server.rs @@ -53,13 +53,13 @@ async fn frontend_files(request: Request) -> impl IntoResponse { (header::CACHE_CONTROL, "no-cache"), (header::ETAG, &content.hash()), ]; - if let Some(if_none_match) = request.headers().get(header::IF_NONE_MATCH) { - if let Ok(client_etag) = if_none_match.to_str() { - if client_etag == content.hash() { - return (StatusCode::NOT_MODIFIED, default_headers).into_response(); - } - } + if let Some(if_none_match) = request.headers().get(header::IF_NONE_MATCH) + && let Ok(client_etag) = if_none_match.to_str() + && client_etag == content.hash() + { + return (StatusCode::NOT_MODIFIED, default_headers).into_response(); } + if request.method() == axum::http::Method::HEAD { return (StatusCode::OK, default_headers).into_response(); } @@ -74,20 +74,20 @@ async fn frontend_files(request: Request) -> impl IntoResponse { .map(|s| s.split(',').map(str::trim).collect::>()) .unwrap_or_default(); for (encoding, data) in [("br", content.data_br()), ("gzip", content.data_gzip())] { - if accepted_encodings.contains(encoding) { - if let Some(data) = data { - return ( - StatusCode::OK, - [ - (header::CONTENT_TYPE, content_type), - (header::CACHE_CONTROL, "no-cache"), - (header::ETAG, &content.hash()), - (header::CONTENT_ENCODING, encoding), - ], - data, - ) - .into_response(); - } + if accepted_encodings.contains(encoding) + && let Some(data) = data + { + return ( + StatusCode::OK, + [ + (header::CONTENT_TYPE, content_type), + (header::CACHE_CONTROL, "no-cache"), + (header::ETAG, &content.hash()), + (header::CONTENT_ENCODING, encoding), + ], + data, + ) + .into_response(); } } ( diff --git a/crates/bili_sync/src/utils/rule.rs b/crates/bili_sync/src/utils/rule.rs index 0e770c9..6b85f3d 100644 --- a/crates/bili_sync/src/utils/rule.rs +++ b/crates/bili_sync/src/utils/rule.rs @@ -52,14 +52,14 @@ impl FieldEvaluatable for RuleTarget { /// 修改模型后进行评估,此时能访问的是未保存的 activeModel,就地使用 activeModel 评估 fn evaluate(&self, video: &video::ActiveModel, pages: &[page::ActiveModel]) -> bool { match self { - RuleTarget::Title(cond) => video.name.try_as_ref().is_some_and(|title| cond.evaluate(&title)), + RuleTarget::Title(cond) => video.name.try_as_ref().is_some_and(|title| cond.evaluate(title)), // 目前的所有条件都是分别针对全体标签进行 any 评估的,例如 Prefix("a") && Suffix("b") 意味着 any(tag.Prefix("a")) && any(tag.Suffix("b")) 而非 any(tag.Prefix("a") && tag.Suffix("b")) // 这可能不满足用户预期,但应该问题不大,如果真有很多人用复杂标签筛选再单独改 RuleTarget::Tags(cond) => video .tags .try_as_ref() .and_then(|t| t.as_ref()) - .is_some_and(|tags| tags.0.iter().any(|tag| cond.evaluate(&tag))), + .is_some_and(|tags| tags.0.iter().any(|tag| cond.evaluate(tag))), RuleTarget::FavTime(cond) => video .favtime .try_as_ref() @@ -84,7 +84,7 @@ impl FieldEvaluatable for RuleTarget { RuleTarget::Tags(cond) => video .tags .as_ref() - .is_some_and(|tags| tags.0.iter().any(|tag| cond.evaluate(&tag))), + .is_some_and(|tags| tags.0.iter().any(|tag| cond.evaluate(tag))), RuleTarget::FavTime(cond) => cond.evaluate(&video.favtime.and_utc().with_timezone(&Local).naive_local()), RuleTarget::PubTime(cond) => cond.evaluate(&video.pubtime.and_utc().with_timezone(&Local).naive_local()), RuleTarget::PageCount(cond) => cond.evaluate(pages.len()), diff --git a/crates/bili_sync/src/utils/task_notifier.rs b/crates/bili_sync/src/utils/task_notifier.rs index 4da2788..21b0809 100644 --- a/crates/bili_sync/src/utils/task_notifier.rs +++ b/crates/bili_sync/src/utils/task_notifier.rs @@ -7,7 +7,7 @@ use crate::config::VersionedConfig; pub static TASK_STATUS_NOTIFIER: LazyLock = LazyLock::new(TaskStatusNotifier::new); -#[derive(Serialize)] +#[derive(Serialize, Default)] pub struct TaskStatus { is_running: bool, last_run: Option>, @@ -21,17 +21,6 @@ pub struct TaskStatusNotifier { rx: tokio::sync::watch::Receiver>, } -impl Default for TaskStatus { - fn default() -> Self { - Self { - is_running: false, - last_run: None, - last_finish: None, - next_run: None, - } - } -} - impl TaskStatusNotifier { pub fn new() -> Self { let (tx, rx) = tokio::sync::watch::channel(Arc::new(TaskStatus::default())); @@ -55,7 +44,7 @@ impl TaskStatusNotifier { pub fn finish_running(&self, _lock: MutexGuard<()>) { let last_status = self.tx.borrow(); - let last_run = last_status.last_run.clone(); + let last_run = last_status.last_run; drop(last_status); let config = VersionedConfig::get().load(); let now = chrono::Local::now(); diff --git a/crates/bili_sync/src/workflow.rs b/crates/bili_sync/src/workflow.rs index b9c1370..4b6f12e 100644 --- a/crates/bili_sync/src/workflow.rs +++ b/crates/bili_sync/src/workflow.rs @@ -296,10 +296,10 @@ pub async fn download_video_pages( error!("处理视频「{}」{}失败: {:#}", &video_model.name, task_name, e) } }); - if let ExecutionStatus::Failed(e) = results.into_iter().nth(4).context("page download result not found")? { - if e.downcast_ref::().is_some() { - return Err(e); - } + if let ExecutionStatus::Failed(e) = results.into_iter().nth(4).context("page download result not found")? + && e.downcast_ref::().is_some() + { + return Err(e); } let mut video_active_model: video::ActiveModel = video_model.into(); video_active_model.download_status = Set(status.into()); @@ -488,10 +488,10 @@ pub async fn download_page( ), }); // 如果下载视频时触发风控,直接返回 DownloadAbortError - if let ExecutionStatus::Failed(e) = results.into_iter().nth(1).context("video download result not found")? { - if let Ok(BiliError::RiskControlOccurred) = e.downcast::() { - bail!(DownloadAbortError()); - } + if let ExecutionStatus::Failed(e) = results.into_iter().nth(1).context("video download result not found")? + && let Ok(BiliError::RiskControlOccurred) = e.downcast::() + { + bail!(DownloadAbortError()); } let mut page_active_model: page::ActiveModel = page_model.into(); page_active_model.download_status = Set(status.into()); diff --git a/crates/bili_sync_entity/src/custom_type/rule.rs b/crates/bili_sync_entity/src/custom_type/rule.rs index e38f406..231ce26 100644 --- a/crates/bili_sync_entity/src/custom_type/rule.rs +++ b/crates/bili_sync_entity/src/custom_type/rule.rs @@ -108,11 +108,11 @@ where { let pattern = String::deserialize(deserializer)?; // 反序列化时预编译 regex,优化性能 - let regex = regex::Regex::new(&pattern).map_err(|e| serde::de::Error::custom(e))?; + let regex = regex::Regex::new(&pattern).map_err(serde::de::Error::custom)?; Ok((pattern, regex)) } -fn serialize_regex(pattern: &String, _regex: ®ex::Regex, serializer: S) -> Result +fn serialize_regex(pattern: &str, _regex: ®ex::Regex, serializer: S) -> Result where S: Serializer, {