fix: remove empty tempfile after unsuccessful download

This commit is contained in:
ThetaDev 2024-12-12 23:47:03 +01:00
parent 8a2dee19f7
commit 54f104d6a2

View file

@ -10,6 +10,7 @@ use std::{
cmp::Ordering, cmp::Ordering,
ffi::OsString, ffi::OsString,
ops::Range, ops::Range,
os::unix::fs::MetadataExt,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
time::Duration, time::Duration,
@ -1214,7 +1215,7 @@ async fn download_single_file(
.open(&output_path_tmp) .open(&output_path_tmp)
.await?; .await?;
if is_gvideo && size.is_some() { let res = if is_gvideo && size.is_some() {
download_chunks_by_param( download_chunks_by_param(
http, http,
&mut file, &mut file,
@ -1226,7 +1227,7 @@ async fn download_single_file(
#[cfg(feature = "indicatif")] #[cfg(feature = "indicatif")]
pb, pb,
) )
.await?; .await
} else { } else {
download_chunks_by_header( download_chunks_by_header(
http, http,
@ -1238,7 +1239,19 @@ async fn download_single_file(
#[cfg(feature = "indicatif")] #[cfg(feature = "indicatif")]
pb, 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?; fs::rename(&output_path_tmp, &output_path).await?;