diff --git a/src/downloader/downloader.rs b/src/downloader/downloader.rs index a3f3302..31d1734 100644 --- a/src/downloader/downloader.rs +++ b/src/downloader/downloader.rs @@ -245,6 +245,17 @@ impl DownloaderIn self.progress_bar.qload() } + /// Fallback to simple thread mode. + pub fn fallback_to_simp(&self) { + self.multi.qstore(false); + match self.pd.disable_multi() { + Ok(_) => {} + Err(e) => { + println!("{}", e); + } + }; + } + #[inline] /// Finishes the progress bar and sets a message pub fn finish_progress_bar_with_message(&self, msg: impl Into>) { diff --git a/src/downloader/pd_file/file.rs b/src/downloader/pd_file/file.rs index c4e3e95..9c8f53a 100644 --- a/src/downloader/pd_file/file.rs +++ b/src/downloader/pd_file/file.rs @@ -1,3 +1,4 @@ +use crate::concat_error; use crate::downloader::pd_file::enums::PdFileResult; use crate::downloader::pd_file::enums::PdFileStatus; use crate::downloader::pd_file::enums::PdFileType; @@ -137,6 +138,26 @@ impl PdFile { Ok(()) } + /// Disable multiple thread support + pub fn disable_multi(&self) -> Result<(), PdFileError> { + if !self.is_downloading() { + self.ftype.replace_with2(PdFileType::SingleThread); + if !self.is_mem_only() { + self.need_saved.qstore(true); + let mut f = self.file.get_mut(); + let f = f.as_mut().unwrap(); + f.seek(TYPE_OFFSET)?; + f.write_le_u8(self.ftype.get_ref().int_value())?; + self.need_saved.qstore(false); + } + } else { + let mut err = self.clear(); + concat_error!(err, self.disable_multi(), PdFileError); + return err; + } + Ok(()) + } + /// Enable multiple thread support pub fn enable_multi(&self) -> Result<(), PdFileError> { if !self.is_downloading() { diff --git a/src/downloader/tasks.rs b/src/downloader/tasks.rs index 261515e..3298633 100644 --- a/src/downloader/tasks.rs +++ b/src/downloader/tasks.rs @@ -157,7 +157,20 @@ pub async fn create_download_tasks_multi_first< if status.as_u16() >= 400 { return Err(DownloaderError::from(status)); } - // # TODO + match result.content_length() { + Some(len) => match d.pd.set_file_size(len) { + Ok(_) => {} + Err(e) => { + println!("{}", e) + } + }, + None => { + d.fallback_to_simp(); + return Err(DownloaderError::from(gettext( + "Warning: no content-length, fallback to single thread download.", + ))); + } + } Ok(()) } diff --git a/src/error.rs b/src/error.rs index 2dcf5f8..7673b3b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -36,3 +36,22 @@ macro_rules! concat_pixiv_downloader_error { } }; } + +#[macro_export] +macro_rules! concat_error { + ($exp1:expr, $exp2:expr, $typ:ty) => { + $exp1 = match $exp1 { + Ok(x) => match $exp2 { + Ok(_) => Ok(x), + Err(e) => Err(<$typ>::from(e)), + }, + Err(e) => match $exp2 { + Ok(_) => Err(e), + Err(e2) => { + println!("{}", e); + Err(<$typ>::from(e2)) + } + }, + } + }; +}