From 5262becca1e9e3e8262833764ef18c23bc401172 Mon Sep 17 00:00:00 2001 From: ThetaDev Date: Thu, 12 Dec 2024 23:47:03 +0100 Subject: [PATCH] fix: remove empty tempfile after unsuccessful download --- downloader/src/lib.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/downloader/src/lib.rs b/downloader/src/lib.rs index f30af85..6107235 100644 --- a/downloader/src/lib.rs +++ b/downloader/src/lib.rs @@ -10,6 +10,7 @@ use std::{ cmp::Ordering, ffi::OsString, ops::Range, + os::unix::fs::MetadataExt, path::{Path, PathBuf}, sync::Arc, time::Duration, @@ -1214,7 +1215,7 @@ async fn download_single_file( .open(&output_path_tmp) .await?; - if is_gvideo && size.is_some() { + let res = if is_gvideo && size.is_some() { download_chunks_by_param( http, &mut file, @@ -1226,7 +1227,7 @@ async fn download_single_file( #[cfg(feature = "indicatif")] pb, ) - .await?; + .await } else { download_chunks_by_header( http, @@ -1238,7 +1239,19 @@ async fn download_single_file( #[cfg(feature = "indicatif")] pb, ) - .await?; + .await + }; + + drop(file); + if let Err(e) = res { + // Remove temporary file if nothing was downloaded (e.g. 403 error) + if std::fs::metadata(&output_path_tmp) + .map(|md| md.size() == 0) + .unwrap_or_default() + { + _ = std::fs::remove_file(&output_path_tmp); + } + return Err(e); } fs::rename(&output_path_tmp, &output_path).await?;