Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(system): eliminate silent errors across downloads, favorites, and process launching
Samir Hossains389a72780276
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b1d0cd3..718ccf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,13 @@- Removed redundant `Poster Graphics` toggle from Settings Hub (`/settings` $\to$ Appearance) and `config.json`, delegating terminal graphics strictly to automatic native GPU protocol detection (Kitty, Sixel, iTerm2).### Fixed+- **Cross-Platform Handle Safety & Silent Failure Elimination**:+ - Fixed Windows file sharing violation (`ERROR_SHARING_VIOLATION`) in multi-segment download assembly by explicitly flushing, syncing, and dropping the file write handle before executing destination renames.+ - Added overwrite handling on destination collisions during download finalization on Windows, preventing failed renames on re-downloaded media.+ - Guarded `FavoritesManager::load_from_path` against premature corrupt file rotation on transient read errors, matching history and configuration persistence invariants.+ - Hardened Lua tracker script and state file directory initialization to return `None` on directory creation or write failures rather than passing non-existent paths to media players.+ - Handled web browser launch failures in Settings Hub (`open::that`), logging warnings and displaying the repository URL on headless or restricted environments.+ - Added `CREATE_NO_WINDOW` flag (`0x08000000`) to the Windows update helper process spawn to eliminate console window flashes during in-app updates.- **Resilient Cross-Platform Cache Clearing & In-Flight Task Isolation**:- Hardened `clear_all_cache` with recursive directory contents deletion, leaving the root directory node intact to prevent `ERROR_ACCESS_DENIED` and `ERROR_SHARING_VIOLATION` failures when Windows processes or shells hold folder handles.- Added Windows read-only attribute clearing before unlinking locked files.diff --git a/docs/cross-platform.md b/docs/cross-platform.mdindex e73e6e5..14f4a5f 100644--- a/docs/cross-platform.md+++ b/docs/cross-platform.md@@ -13,7 +13,7 @@ the release checks in [`release-checklist.md`](release-checklist.md).| Platform | Notes || ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || macOS | IINA preferred player (via the installed IINA `iina-cli`); VLC/mpv `.app` paths detected. `process_group(0)` on spawn. |-| Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%`; path-safe file stems; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries. |+| Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%`; path-safe file stems; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries; handle-safe atomic download replacement (dropping file handles before renames); background update helper spawned with `CREATE_NO_WINDOW` (`0x08000000`). || Linux | Flatpak mpv/VLC supported (`flatpak run …`); xdg data/cache dirs. || Android (Termux) | Uses the Linux ARM64 binary compiled as static-PIE (`ET_DYN`) with 64-byte `PT_TLS` alignment to satisfy Android Bionic (`/system/bin/linker64`) and kernel W^X execution rules without `unexpected e_type: 2` errors. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution, and dynamically checks for `termux-open`, `termux-open-url`, `termux-am`, or in-terminal `mpv`; playback strips `LD_LIBRARY_PATH` and `LD_PRELOAD` before launching the chooser. Android intent playback cannot forward stream headers or attach subtitles. Real-device chooser behavior is a release prerequisite; Proot/Termux X11 behavior is unsupported unless separately tested. |diff --git a/src/download.rs b/src/download.rsindex cfa7492..6fe6437 100644--- a/src/download.rs+++ b/src/download.rs@@ -449,13 +449,26 @@ where}output.flush().await?;output.sync_data().await?;+ drop(output);if file_len(&assembly).await != total {return Err(DownloadError::Incomplete {downloaded: file_len(&assembly).await,expected: total,});}- tokio::fs::rename(&assembly, destination).await?;+ if destination.exists() {+ let _ = tokio::fs::remove_file(destination).await;+ }+ if let Err(e) = tokio::fs::rename(&assembly, destination).await {+ let _ = tokio::fs::remove_file(destination).await;+ tokio::fs::rename(&assembly, destination)+ .await+ .map_err(|e2| {+ DownloadError::File(std::io::Error::other(format!(+ "failed to move assembled file to destination: {e} ({e2})"+ )))+ })?;+ }for index in 0..segments {let _ = tokio::fs::remove_file(segment_path(destination, index)).await;}@@ -715,7 +728,10 @@ async fn finalize(metadata: &Path,destination: &Path,) -> Result<(), std::io::Error> {- tokio::fs::rename(partial, destination).await?;+ if tokio::fs::rename(partial, destination).await.is_err() {+ let _ = tokio::fs::remove_file(destination).await;+ tokio::fs::rename(partial, destination).await?;+ }let _ = tokio::fs::remove_file(metadata).await;Ok(())}@@ -812,4 +828,37 @@ mod tests {"Movie_ The _Ultimate_ Edition");}++ #[tokio::test]+ async fn test_finalize_replaces_existing_destination_cleanly() {+ let dir = std::env::temp_dir().join(format!(+ "mbx_test_finalize_{}_{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos()+ ));+ tokio::fs::create_dir_all(&dir).await.unwrap();+ let partial = dir.join("video.mp4.part");+ let metadata = dir.join("video.mp4.metadata");+ let destination = dir.join("video.mp4");++ tokio::fs::write(&destination, b"old version")+ .await+ .unwrap();+ tokio::fs::write(&partial, b"new version").await.unwrap();+ tokio::fs::write(&metadata, b"{}").await.unwrap();++ let res = finalize(&partial, &metadata, &destination).await;+ assert!(res.is_ok());+ assert!(!partial.exists());+ assert!(!metadata.exists());+ assert!(destination.exists());+ assert_eq!(+ tokio::fs::read_to_string(&destination).await.unwrap(),+ "new version"+ );+ let _ = tokio::fs::remove_dir_all(&dir).await;+ }}diff --git a/src/favorites.rs b/src/favorites.rsindex 05cd7df..418d086 100644--- a/src/favorites.rs+++ b/src/favorites.rs@@ -84,22 +84,30 @@ impl FavoritesManager {pub fn load_from_path(path: &Path) -> Self {if path.exists() {- if let Ok(content) = fs::read_to_string(path) {- if let Ok(manager) = serde_json::from_str::<Self>(&content) {- return manager;+ match fs::read_to_string(path) {+ Ok(content) => match serde_json::from_str::<Self>(&content) {+ Ok(manager) => return manager,+ Err(e) => {+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs();+ let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));+ log::error!(+ "failed to parse favorites from {} ({e}), rotating to {}",+ crate::logging::sanitize_path(path),+ crate::logging::sanitize_path(&corrupt_path)+ );+ let _ = fs::rename(path, corrupt_path);+ }+ },+ Err(e) => {+ log::warn!(+ "failed to read favorites from {}: {e}",+ crate::logging::sanitize_path(path)+ );}}- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_secs();- let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));- log::error!(- "failed to parse favorites from {}, rotating to {}",- crate::logging::sanitize_path(path),- crate::logging::sanitize_path(&corrupt_path)- );- let _ = fs::rename(path, corrupt_path);}Self::default()}diff --git a/src/player/tracker.rs b/src/player/tracker.rsindex c602ffa..30f456b 100644--- a/src/player/tracker.rs+++ b/src/player/tracker.rs@@ -120,7 +120,10 @@ end)pub fn ensure_tracker_script() -> Option<PathBuf> {let dir = crate::config::scripts_dir()?;if !dir.exists() {- let _ = fs::create_dir_all(&dir);+ if let Err(e) = fs::create_dir_all(&dir) {+ log::warn!("failed to create scripts dir {}: {e}", dir.display());+ return None;+ }}let path = dir.join("moviebox_tracker.lua");if !path.exists()@@ -128,7 +131,10 @@ pub fn ensure_tracker_script() -> Option<PathBuf> {.map(|c| c != TRACKER_LUA_CONTENT).unwrap_or(true){- let _ = fs::write(&path, TRACKER_LUA_CONTENT.as_bytes());+ if let Err(e) = fs::write(&path, TRACKER_LUA_CONTENT.as_bytes()) {+ log::warn!("failed to write tracker script {}: {e}", path.display());+ return None;+ }}Some(path)}@@ -141,7 +147,10 @@ pub fn state_file_path() -> Option<PathBuf> {let dir = crate::config::playback_state_dir()?;if !dir.exists() {- let _ = fs::create_dir_all(&dir);+ if let Err(e) = fs::create_dir_all(&dir) {+ log::warn!("failed to create playback state dir {}: {e}", dir.display());+ return None;+ }}let sanitized_provider = sanitize_component(provider);let sanitized_id = sanitize_component(subject_id);diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex 7d25efb..7091eb5 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -271,7 +271,12 @@ impl App {false,);if let Ok(serialized) = serde_json::to_string(&initial_state) {- let _ = std::fs::write(&state_path, serialized);+ if let Err(e) = std::fs::write(&state_path, serialized) {+ log::warn!(+ "failed to write initial playback state to {}: {e}",+ crate::logging::sanitize_path(&state_path)+ );+ }}}}diff --git a/src/tui/app/system.rs b/src/tui/app/system.rsindex 2663c2e..a96e26b 100644--- a/src/tui/app/system.rs+++ b/src/tui/app/system.rs@@ -609,12 +609,24 @@ impl App {self.action_sender.send(Action::CheckForUpdates).ok();}2 => {- let _ = open::that("https://github.com/mesamirh/MovieBox-Tui");- self.state.notify(- NotificationKind::Info,- "GitHub",- "Opening repository in default web browser...",- );+ const REPO_URL: &str = "https://github.com/mesamirh/MovieBox-Tui";+ match open::that(REPO_URL) {+ Ok(()) => {+ self.state.notify(+ NotificationKind::Info,+ "GitHub",+ "Opening repository in default web browser...",+ );+ }+ Err(error) => {+ log::warn!("failed to open web browser: {error}");+ self.state.notify(+ NotificationKind::Warning,+ "Browser Launch Failed",+ format!("Could not open browser: {error}\n{REPO_URL}"),+ );+ }+ }}_ => {}}@@ -872,7 +884,9 @@ impl App {.ok();if let Ok(exe_path) = std::env::current_exe() {- let _ = crate::updater::restart_process(&exe_path);+ if let Err(e) = crate::updater::restart_process(&exe_path) {+ log::error!("failed to restart process after update: {e}");+ }}std::process::exit(0);}diff --git a/src/updater/apply.rs b/src/updater/apply.rsindex 388d5b3..158cf94 100644--- a/src/updater/apply.rs+++ b/src/updater/apply.rs@@ -227,9 +227,14 @@ fn spawn_windows_helper(staged_path: &Path, current_exe: &Path) -> Result<(), Ststd::fs::write(&helper_path, script_content).map_err(|e| format!("failed to write Windows update helper: {e}"))?;- Command::new("cmd.exe")- .args(["/C", &helper_path.to_string_lossy()])- .spawn()+ let mut cmd = Command::new("cmd.exe");+ cmd.args(["/C", &helper_path.to_string_lossy()]);+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x08000000);+ }+ cmd.spawn().map_err(|e| format!("failed to spawn Windows update helper: {e}"))?;Ok(())diff --git a/tests/settings_hub.rs b/tests/settings_hub.rsindex 36bfdad..ef3ce5d 100644--- a/tests/settings_hub.rs+++ b/tests/settings_hub.rs@@ -414,3 +414,19 @@ async fn test_settings_hub_clear_cache_activation_and_notification() {assert!(err_notification.is_some());assert_eq!(err_notification.unwrap().title, "Cache Clear Failed");}++#[tokio::test]+async fn test_settings_hub_browser_open_row_activation() {+ let mut app = App::new();+ app.handle_action(Action::ShowSettingsPopup).await;+ app.handle_action(Action::SelectSettingsCategory(+ SettingsCategory::StorageInfo,+ ))+ .await;+ app.state_mut().settings_selected_row = 2;+ app.handle_action(Action::SettingsActivateRow).await;+ let notification = app.state().notifications.back();+ assert!(notification.is_some());+ let title = ¬ification.unwrap().title;+ assert!(title == "GitHub" || title == "Browser Launch Failed");+}