Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(download): resolve season batch timing and segmented fallbacks
Samir Hossainseb5cac75c40f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c98d534..bf91c7b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,12 @@## [Unreleased]+### Fixed+- **Download Engine & Batch Queue**:+ - Fixed season batch downloads by arming `is_waiting_for_download_stream` during queue steps, eliminating immediate empty-list download calls that aborted multi-episode queues.+ - Reset the download resolution state lock on 4KHDHub resolver timeouts and errors so failed mirror resolutions do not block subsequent download attempts.+ - Added sequential single-connection fallback to the internal HTTP downloader when multi-worker segmented range requests receive HTTP 403, 429, or network disconnects.+### Added- **In-App Updater Lifecycle**:- Tracked target executable path before staging updates and resolved deleted inode suffixes (` (deleted)`) on Linux to restart the new binary automatically after popup self-update.diff --git a/docs/downloads.md b/docs/downloads.mdindex 0deb137..fbe012d 100644--- a/docs/downloads.md+++ b/docs/downloads.md@@ -6,8 +6,7 @@ MovieBox-TUI includes a multi-segment HTTP chunked downloader supporting pause,- **Storage Location**: Defaults to `~/Downloads/MovieBox-TUI/`. Configurable via `/settings` (General → Download Folder).- **Multi-Segment Engine**: Files are partitioned into concurrent byte ranges using HTTP RFC 7233 `Range: bytes=X-Y` requests.-- **Single-Stream Fallback**: If an upstream server or CDN does not support range requests (returns HTTP `200 OK` instead of `206 Partial Content`), the engine falls back to single-stream downloading without failing.-+- **Single-Stream Fallback**: If an upstream server or CDN does not support range requests (returns HTTP `200 OK` instead of `206 Partial Content`) or terminates concurrent connections with HTTP 403 or 429, the engine falls back to single-stream sequential downloading.## File Lifecycle & State FilesDuring download, files are saved with temporary extensions:diff --git a/src/download.rs b/src/download.rsindex a052e00..8d1fb72 100644--- a/src/download.rs+++ b/src/download.rs@@ -277,7 +277,9 @@ where).await{- Err(DownloadError::InvalidRange(_)) => {+ Err(DownloadError::InvalidRange(_))+ | Err(DownloadError::Http(_))+ | Err(DownloadError::Network(_)) => {let _ = tokio::fs::remove_file(&partial).await;metadata = ResumeMetadata::default();write_metadata(&metadata_path, &metadata).await?;@@ -1209,4 +1211,65 @@ mod tests {let _ = tokio::fs::remove_dir_all(&temp_dir).await;}++ #[tokio::test]+ async fn test_download_segmented_drops_fallback_to_sequential_download() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ use tokio::net::TcpListener;++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let url = format!("http://127.0.0.1:{port}/stream.mp4");++ let server = tokio::spawn(async move {+ let total_size = 5 * 1024 * 1024;+ let mut request_num = 0;+ while request_num < 10 {+ let (mut socket, _) = match listener.accept().await {+ Ok(s) => s,+ Err(_) => break,+ };+ request_num += 1;+ let mut buf = [0u8; 1024];+ let n = socket.read(&mut buf).await.unwrap_or(0);+ let req = String::from_utf8_lossy(&buf[..n]);++ if req.contains("Range: bytes=0-0") {+ let resp = format!(+ "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-0/{total_size}\r\nContent-Length: 1\r\nAccept-Ranges: bytes\r\n\r\n0"+ );+ let _ = socket.write_all(resp.as_bytes()).await;+ } else if req.contains("Range: bytes=") && request_num <= 4 {+ let resp = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n";+ let _ = socket.write_all(resp.as_bytes()).await;+ } else {+ let chunk = vec![b'X'; total_size];+ let resp = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {total_size}\r\nAccept-Ranges: none\r\nConnection: close\r\n\r\n"+ );+ let _ = socket.write_all(resp.as_bytes()).await;+ let _ = socket.write_all(&chunk).await;+ break;+ }+ }+ });++ let temp_dir =+ std::env::temp_dir().join(format!("mbx_fallback_test_{}", std::process::id()));+ tokio::fs::create_dir_all(&temp_dir).await.unwrap();+ let dest_file = temp_dir.join("fallback_stream.mp4");++ let client = reqwest::Client::new();+ let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));++ let res = download(&client, &url, &dest_file, cancel, |_| {}).await;+ let _ = server.await;++ assert!(matches!(res, Ok(DownloadOutcome::Completed { .. })));+ assert!(dest_file.exists());+ let meta = tokio::fs::metadata(&dest_file).await.unwrap();+ assert_eq!(meta.len(), 5 * 1024 * 1024);++ let _ = tokio::fs::remove_dir_all(&temp_dir).await;+ }}diff --git a/src/tui/app/download.rs b/src/tui/app/download.rsindex 4ac85ce..2fcb1f6 100644--- a/src/tui/app/download.rs+++ b/src/tui/app/download.rs@@ -631,18 +631,20 @@ impl App {}Ok(Err(error)) => {log::error!("4KHDHub download resolve failed: {error}");+ sender.send(Action::PlayerExited).ok();sender- .send(Action::SetStatus(format!(- "Error: 4KHDHub: {}",+ .send(Action::DownloadFailed(format!(+ "4KHDHub: {}",error.user_message()))).ok();}Err(_) => {log::error!("4KHDHub download resolve timed out");+ sender.send(Action::PlayerExited).ok();sender- .send(Action::SetStatus(- "Error: 4KHDHub: Timed out.".to_string(),+ .send(Action::DownloadFailed(+ "4KHDHub: Timed out.".to_string(),)).ok();}@@ -792,6 +794,7 @@ impl App {self.state.selected_resources.clear();self.state.is_fetching_streams = true;+ self.state.is_waiting_for_download_stream = true;self.action_sender.send(Action::FetchEpisodeStreams {@@ -801,8 +804,6 @@ impl App {force_refresh: false,}).ok();-- self.action_sender.send(Action::DownloadStream(None)).ok();} else if self.state.download_queue_total > 0 {self.state.notify(NotificationKind::Success,@@ -1506,4 +1507,37 @@ mod tests {assert_eq!(series_file, expected_series_file);assert_eq!(series_sub, expected_series_sub);}+ #[tokio::test]+ async fn test_process_download_queue_sets_waiting_flag_without_immediate_download() {+ let mut app = App::new();+ app.state.active_screen = Screen::Details;+ app.state.active_subject_id = Some("test_subject".to_string());+ app.state.download_queue.push_back((2, 1));+ app.state.download_queue_total = 1;++ app.handle_download(Action::ProcessDownloadQueue).await;++ assert!(app.state.is_waiting_for_download_stream);+ assert!(app.state.is_fetching_streams);++ let mut fetched = false;+ let mut downloaded = false;+ while let Ok(action) = app.action_receiver.try_recv() {+ match action {+ Action::FetchEpisodeStreams {+ season, episode, ..+ } => {+ assert_eq!(season, 2);+ assert_eq!(episode, 1);+ fetched = true;+ }+ Action::DownloadStream(_) => {+ downloaded = true;+ }+ _ => {}+ }+ }+ assert!(fetched);+ assert!(!downloaded);+ }}