Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix: harden proxy security, cross-platform playback, and dub metadata
Samir Hossainseaa463f08b67
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d31599c..f18ef7f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,6 +40,23 @@- Added direct links to GitHub Discussions and Termux setup documentation in `.github/ISSUE_TEMPLATE/config.yml`.- Added automated `incomplete-issue.yml` workflow to flag and comment on vague issue reports lacking diagnostic context.- Added automated `stale.yml` workflow to close unresponsive `needs-info` issues after 7 days.+- **Security & Terminal Signal Hardening**:+ - Enforced host authority whitelist validation against `target_host` in local proxy sidecar `handle_connection` (`src/proxy.rs`), returning HTTP 403 Forbidden on host mismatch to prevent Server-Side Request Forgery and unauthorized auth header leakage.+ - Enforced HTTP and HTTPS scheme validation on percent-decoded subtitle URLs in proxy `extract_target_url` (`src/proxy.rs`), preventing arbitrary URL scheme forwarding.+ - Registered Unix `SIGTERM` and `SIGHUP` signal handlers in `EventHandler::new` (`src/tui/event.rs`) routing to `Action::Quit`, ensuring proper terminal de-initialization and alternate screen restoration via `TerminalGuard` on process termination.+ - Replaced silent `reqwest::Client::new` fallbacks with explicit builder `expect` assertions in `MovieBoxClient`, `DhakaFlixClient`, and `CircleFtpClient`, preventing silent networking degradation without shared DNS and connection pooling configurations.+ - Added canonical path containment checks in `start_resilient_download` (`src/tui/app/download.rs`) ensuring download target paths resolve within the configured download directory tree.+- **Cross-Platform Compatibility & Player Integration**:+ - Stripped Windows extended-length verbatim prefix (`\\?\`) in `start_resilient_download` (`src/tui/app/download.rs`), preventing false-positive download containment failures when comparing canonicalized base directories with un-canonicalized target paths.+ - Added environment variable expansion for `REG_EXPAND_SZ` values in Windows registry queries (`src/player.rs`), allowing automatic discovery of player binaries configured with `%USERPROFILE%`, `%SystemRoot%`, or `%LOCALAPPDATA%` paths.+ - Retained downloaded local subtitle files for Android intent launches in `src/tui/app/playback.rs` without premature process-exit deletion, avoiding loopback proxy URLs (`http://127.0.0.1:<port>/sub/...`) and allowing external players (VLC, MX Player) to load subtitles from shared storage before background cleanup.+ - Gated Kitty keyboard enhancement protocol flags (`PushKeyboardEnhancementFlags`) behind `!is_termux_environment()` in `src/main.rs`, preventing unsupported escape sequence noise on mobile touch terminals.+ - Restricted Termux shared storage subtitle directory probing (`~/storage/downloads/moviebox_subs`) to verified Termux environments in `src/main.rs` and `src/cache.rs`.+ - Added Flatpak `@@` file forwarding markers for local file and `file://` URLs in `mpv_command` and `vlc_command` (`src/player.rs`), ensuring Flatpak Document portal exports media and subtitle files into sandboxed player containers.+- **Audio Track Switch Metadata & Synopsis Preservation**:+ - Preserved rich metadata (duration, synopsis, genres, cast, crew, and clean title) when switching audio dubs on the Details screen in `src/tui/app/requests.rs`.+ - Resolved an issue where selecting an audio track (e.g. Hindi dub) caused duration (`2h 20m`) to disappear and replaced the multi-line synopsis with a title placeholder (`Ek Deewane Ki Deewaniyat`), breaking visual balance against the poster.+ - Sanitized window title in `contextual_title` (`src/tui/app/run.rs`) using `clean_moviebox_title` to prevent raw dub tags (`[Hindi]`) from leaking into the terminal window title.- **MovieBox Edge-Cache CDN Stream Manifest Resolution**:- Added `Edge-Cache-Cookie` `urlprefix` Base64 decoding in `resolve_dash_manifest_from_policy` (`src/providers/moviebox/adapt.rs`).- Resolves active multi-quality MPEG-DASH manifests (`https://sbcdn*.hakunaymatata.com/dash/.../index.mpd`) generated under MovieBox's updated CDN token structure.diff --git a/docs/cross-platform.md b/docs/cross-platform.mdindex 4924932..d01db08 100644--- a/docs/cross-platform.md+++ b/docs/cross-platform.md@@ -11,9 +11,9 @@ 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%` (filtering out 0-byte Windows Store `WindowsApps` execution alias stubs); 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 process spawning (registry queries and yt-dlp downloader) hardened with `CREATE_NO_WINDOW` (`0x08000000`) and isolated with `CREATE_NEW_PROCESS_GROUP` (`0x00000200`) so terminal interrupts do not kill active downloads; updater helper process spawned with `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` so console exit does not abort in-flight binary replacement; full legacy Windows console (`conhost.exe` on Windows 8.1 and earlier) compatibility via crossterm WinAPI fallback by eliminating unsupported underline color sequences. |-| Linux | Flatpak mpv/VLC supported (`flatpak run …`); xdg data/cache dirs. Linux ARM64 binaries (`MovieBox_Linux_arm64.tar.gz`) are fully static musl executables linked with 64KB ELF segment alignment (`-Wl,-z,max-page-size=65536`) for compatibility across 4KB, 16KB, and 64KB page kernels. |-| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools`. Detection prioritizes the native Android player bridge ahead of headless CLI players, automatically falls back from `termux-am` to `termux-open` if `am.sock` is unavailable, and strictly gates system `am` probes behind `target_os = "android"`. Download storage directory prefers `~/storage/downloads` when running inside verified Termux environments. |+| Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%` (filtering out 0-byte Windows Store `WindowsApps` execution alias stubs); path-safe file stems; environment variable expansion (`%USERPROFILE%`, `%SystemRoot%`, `%LOCALAPPDATA%`) for `REG_EXPAND_SZ` registry queries; verbatim `\\?\` UNC prefix normalization during download directory containment checks; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries; handle-safe atomic download replacement (dropping file handles before renames); background process spawning (registry queries and yt-dlp downloader) hardened with `CREATE_NO_WINDOW` (`0x08000000`) and isolated with `CREATE_NEW_PROCESS_GROUP` (`0x00000200`) so terminal interrupts do not kill active downloads; updater helper process spawned with `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` so console exit does not abort in-flight binary replacement; full legacy Windows console (`conhost.exe` on Windows 8.1 and earlier) compatibility via crossterm WinAPI fallback by eliminating unsupported underline color sequences. |+| Linux | Flatpak mpv/VLC supported (`flatpak run …`) with `@@` file forwarding markers for local files; xdg data/cache dirs. Linux ARM64 binaries (`MovieBox_Linux_arm64.tar.gz`) are fully static musl executables linked with 64KB ELF segment alignment (`-Wl,-z,max-page-size=65536`) for compatibility across 4KB, 16KB, and 64KB page kernels. |+| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools`. Detection prioritizes the native Android player bridge ahead of headless CLI players, automatically falls back from `termux-am` to `termux-open` if `am.sock` is unavailable, and strictly gates system `am` probes behind `target_os = "android"`. Subtitles are retained in `~/storage/downloads/moviebox_subs` during playback and cleaned up on a 24-hour retention schedule rather than immediate process exit. Download storage directory prefers `~/storage/downloads` when running inside verified Termux environments. |## Terminal capabilities@@ -45,7 +45,8 @@ prevent escape sequence probe leakage (`Gi=31...`):selection suppression to isolate dialog focus. An explicit `MOVIEBOX_THEME` or saved themealways wins over autodetection.- **Keyboard & Cursor**: The kitty keyboard protocol (disambiguated escapes, event- types) is requested at start and popped on exit; unsupported terminals+ types) is requested at start and popped on exit (gated behind `!is_termux_environment()`+ to prevent escape sequence noise on mobile touch keyboards); unsupported terminalsignore it. Real input cursor styling (`SetCursorStyle::SteadyBar`) activatesduring text editing modes on supported terminals.- **Loading & Progress Indicators**: Unicode Braille loading spinners (`⠋ ⠙ ⠹ ...`)diff --git a/docs/downloads.md b/docs/downloads.mdindex 8682f9c..7afc5a2 100644--- a/docs/downloads.md+++ b/docs/downloads.md@@ -41,7 +41,7 @@ and length is capped.- **Movie downloads:** Saved under `<base_dir>/Movies/<Title>/<Title>.<ext>` (and subtitle `<Title>.<lang>.<sub_ext>`).- **Default path:** Files go to the user's OS download directory (`~/Downloads/MovieBox-TUI`). On Android (Termux), the engine prefers shared `~/storage/downloads` when present, scoped strictly to verified Termux environments.- **Custom path:** Users can set a custom download directory in `/settings` → General → Download Folder or reset to default. Target directories are validated with a write probe before saving, and the code creates the `MovieBox-TUI` subfolder hierarchy (`Movies/` and `Series/`). If custom storage becomes unavailable at runtime, the engine falls back to the default download location.-+- **Path Containment:** Destination paths are validated against the canonical download base directory before file creation, with Windows verbatim `\\?\` prefix normalization, preventing directory escape.## Contextual triggers & Seasons- **Contextual trigger**: Pressing `d` (or clicking `[Download]`) while focused on the **Seasons** pane prompts to download all episodes of the selected season. Triggering download while on the **Episodes** or **Streams** pane prompts to download only that single episode.diff --git a/docs/players.md b/docs/players.mdindex faab7fe..98d57ef 100644--- a/docs/players.md+++ b/docs/players.md@@ -18,8 +18,8 @@ Resolution caches detected paths across runs while allowing newly installed play| Player | Invocation | Notes || :--- | :--- | :--- |-| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no --ytdl-format=bestvideo+bestaudio/best --hls-bitrate=max [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Sets maximum adaptive stream bitrate and best video/audio format selection. Each non-UA, non-Referer header is passed as a separate `--http-header-fields` argument. Flatpak mpv is launched via `flatpak run`. |-| VLC | `vlc --width=W --height=H --play-and-exit --adaptive-logic=highest [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Sets adaptive logic to highest representation. Supports start time resume via `--start-time`. For CloudFront cookie-gated streams (MovieBox DASH), the URL is replaced by a loopback sidecar proxy address (`http://127.0.0.1:<port>/https/<host>/path`) that injects all auth headers server-side before forwarding chunks to VLC. |+| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no --ytdl-format=bestvideo+bestaudio/best --hls-bitrate=max [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Sets maximum adaptive stream bitrate and best video/audio format selection. Each non-UA, non-Referer header is passed as a separate `--http-header-fields` argument. Flatpak mpv is launched via `flatpak run` with `@@` file forwarding markers for local files. |+| VLC | `vlc --width=W --height=H --play-and-exit --adaptive-logic=highest [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Sets adaptive logic to highest representation. Supports start time resume via `--start-time`. For CloudFront cookie-gated streams (MovieBox DASH), the URL is replaced by a loopback sidecar proxy address (`http://127.0.0.1:<port>/https/<host>/path`) that injects all auth headers server-side before forwarding chunks to VLC. Flatpak VLC wraps local files with `@@` markers. || IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. [--mpv-start=..] [--mpv-http-header-fields=..] [--mpv-sub-files=..] <url>` | Uses the installed IINA `iina-cli`; falls back to `open -a IINA <url>` with an informational status warning if the CLI is absent. || Android / Termux | `termux-open --chooser --content-type video/* <url>` (or `termux-open-url` / `termux-am`) | Opens an app chooser on the device, delegating playback to external apps (VLC, MX Player, Just Player, MPV Android). Requires `pkg install -y termux-tools termux-am`. Forwards `User-Agent`, `Referer`, and subtitles when using `termux-am`. |@@ -40,8 +40,8 @@ The `supports_headers` gate in `app/playback.rs` validates whether a player can- VLC and IINA download the subtitle to a temp file first, preserving the URL'sextension (srt/vtt/ass/…), and pass the local path. The download applies the sourceheaders. On failure a status is shown and playback continues without subtitles.-- Android intent playback passes subtitle paths to `am`/`termux-am` via `subtitles_location` and `subs` intent extras.-- Temp files are cleaned up after the player exits and purged at startup if stale.+- Android intent playback downloads subtitles to shared storage (`~/storage/downloads/moviebox_subs`) and passes local file paths to `am`/`termux-am` via `subtitles_location` and `subs` intent extras. Subtitles are retained during playback without premature deletion on intent command exit, and purged on a 24-hour retention cycle.+- Desktop temp files are cleaned up after the player process exits and purged at startup if stale.## Playback Tracking & Resumediff --git a/src/cache.rs b/src/cache.rsindex 21e906a..91bb4ee 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -678,7 +678,9 @@ pub fn clear_all_cache() -> Result<(), String> {let _ = fs::remove_dir(&legacy);}}- if let Some(home) = dirs::home_dir() {+ if crate::updater::artifact::is_termux_environment()+ && let Some(home) = dirs::home_dir()+ {let storage = home.join("storage/downloads/moviebox_subs");if storage.exists() {purge_subtitle_cache_files(&storage, &mut errors);diff --git a/src/main.rs b/src/main.rsindex 692bc69..08180c6 100644--- a/src/main.rs+++ b/src/main.rs@@ -26,7 +26,9 @@ fn purge_stale_subtitles() {moviebox_tui::service::resolve_subtitle_dir(),std::env::temp_dir().join("moviebox-tui/subs"),];- if let Some(home) = dirs::home_dir() {+ if moviebox_tui::updater::artifact::is_termux_environment()+ && let Some(home) = dirs::home_dir()+ {let android_storage = home.join("storage/downloads/moviebox_subs");if home.join("storage/downloads").exists() {dirs.push(android_storage);@@ -133,13 +135,15 @@ async fn main() -> std::io::Result<()> {crossterm::event::EnableMouseCapture,crossterm::event::EnableFocusChange)?;- let _ = crossterm::execute!(- std::io::stdout(),- crossterm::event::PushKeyboardEnhancementFlags(- crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES- | crossterm::event::KeyboardEnhancementFlags::REPORT_EVENT_TYPES- )- );+ if !moviebox_tui::updater::artifact::is_termux_environment() {+ let _ = crossterm::execute!(+ std::io::stdout(),+ crossterm::event::PushKeyboardEnhancementFlags(+ crossterm::event::KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES+ | crossterm::event::KeyboardEnhancementFlags::REPORT_EVENT_TYPES+ )+ );+ }moviebox_tui::cache::clean_old_cache_background();purge_stale_subtitles();diff --git a/src/player.rs b/src/player.rsindex a419ca6..094fad3 100644--- a/src/player.rs+++ b/src/player.rs@@ -463,8 +463,13 @@ fn mpv_command(command.arg(format!("{opt}={sub_path}"));}- command.arg(url);-+ if executable.starts_with("flatpak run ")+ && (url.starts_with('/') || url.starts_with("file://"))+ {+ command.arg("@@").arg(url).arg("@@");+ } else {+ command.arg(url);+ }command}@@ -647,7 +652,13 @@ fn vlc_command(command.arg(format!("--sub-file={sub_path}"));}- command.arg(url);+ if executable.starts_with("flatpak run ")+ && (url.starts_with('/') || url.starts_with("file://"))+ {+ command.arg("@@").arg(url).arg("@@");+ } else {+ command.arg(url);+ }command}@@ -709,11 +720,17 @@ fn query_windows_registry_value(key: &str, value_name: Option<&str>) -> Option<S.iter().position(|&p| p == "REG_SZ" || p == "REG_EXPAND_SZ"){+ let is_expand = parts[pos] == "REG_EXPAND_SZ";if pos + 1 < parts.len() {let val = parts[pos + 1..].join(" ");let clean = val.trim_matches('"').trim();if !clean.is_empty() {- return Some(clean.to_string());+ let expanded = if is_expand {+ expand_env_vars(clean)+ } else {+ clean.to_string()+ };+ return Some(expanded);}}}@@ -722,6 +739,40 @@ fn query_windows_registry_value(key: &str, value_name: Option<&str>) -> Option<SNone}+#[cfg(target_os = "windows")]+fn expand_env_vars(raw: &str) -> String {+ let mut result = String::with_capacity(raw.len());+ let mut chars = raw.chars().peekable();+ while let Some(ch) = chars.next() {+ if ch == '%' {+ let mut var_name = String::new();+ let mut found_end = false;+ for next_ch in chars.by_ref() {+ if next_ch == '%' {+ found_end = true;+ break;+ }+ var_name.push(next_ch);+ }+ if found_end && !var_name.is_empty() {+ if let Ok(val) = std::env::var(&var_name) {+ result.push_str(&val);+ } else {+ result.push('%');+ result.push_str(&var_name);+ result.push('%');+ }+ } else {+ result.push('%');+ result.push_str(&var_name);+ }+ } else {+ result.push(ch);+ }+ }+ result+}+pub fn windows_mpv_candidate_paths(localappdata: Option<&str>,appdata: Option<&str>,diff --git a/src/providers/bdix/circleftp/client.rs b/src/providers/bdix/circleftp/client.rsindex bda9181..466850f 100644--- a/src/providers/bdix/circleftp/client.rs+++ b/src/providers/bdix/circleftp/client.rs@@ -308,5 +308,5 @@ fn build_client() -> reqwest::Client {crate::net::http_client_builder().timeout(Duration::from_secs(5)).build()- .unwrap_or_else(|_| reqwest::Client::new())+ .expect("circleftp http client")}diff --git a/src/providers/bdix/dhakaflix/client.rs b/src/providers/bdix/dhakaflix/client.rsindex fd70e94..b1a9251 100644--- a/src/providers/bdix/dhakaflix/client.rs+++ b/src/providers/bdix/dhakaflix/client.rs@@ -96,7 +96,7 @@ impl DhakaFlixClient {.timeout(Duration::from_secs(5)).user_agent(crate::net::DEFAULT_BROWSER_USER_AGENT).build()- .unwrap_or_else(|_| reqwest::Client::new()),+ .expect("dhakaflix http client"),recent_fails: Arc::new(RwLock::new(HashMap::new())),}}diff --git a/src/providers/moviebox/client.rs b/src/providers/moviebox/client.rsindex af8638e..1db6811 100644--- a/src/providers/moviebox/client.rs+++ b/src/providers/moviebox/client.rs@@ -59,7 +59,7 @@ impl MovieBoxClient {.pool_idle_timeout(std::time::Duration::from_secs(90)).pool_max_idle_per_host(4).build()- .unwrap_or_else(|_| reqwest::Client::new());+ .expect("moviebox http client");let (user_agent, client_info) =crate::providers::moviebox::crypto::generate_client_info_and_ua();diff --git a/src/proxy.rs b/src/proxy.rsindex fc549cb..478771a 100644--- a/src/proxy.rs+++ b/src/proxy.rs@@ -264,6 +264,15 @@ async fn handle_connection(return Ok(());}};+ if let Some(allowed_host) = target_host {+ let extracted_host = extract_host_authority(&target_url);+ if extracted_host.as_deref() != Some(allowed_host) {+ let response =+ "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";+ writer.write_all(response.as_bytes()).await?;+ return Ok(());+ }+ }let mut req = match method {"HEAD" => client.head(&target_url),@@ -407,7 +416,10 @@ fn extract_target_url(path_and_query: &str) -> Option<String> {let raw = path_and_query.strip_prefix('/')?;if let Some(rest) = raw.strip_prefix("sub/") {if let Ok(decoded) = percent_encoding::percent_decode_str(rest).decode_utf8() {- return Some(decoded.into_owned());+ let s = decoded.into_owned();+ if s.starts_with("http://") || s.starts_with("https://") {+ return Some(s);+ }}}if let Some(rest) = raw.strip_prefix("https/") {@@ -500,6 +512,20 @@ mod tests {);assert_eq!(extract_target_url("/invalid/path"), None);}+ #[test]+ fn test_extract_target_url_sub_rejects_non_http() {+ assert_eq!(+ extract_target_url("/sub/file%3A%2F%2F%2Fetc%2Fpasswd"),+ None+ );+ assert_eq!(extract_target_url("/sub/data%3Atext%2Fhtml%2Chello"), None);+ assert!(+ extract_target_url("/sub/https%3A%2F%2Fcdn.example.com%2Fsub.vtt")+ .as_deref()+ .unwrap_or("")+ .starts_with("https://")+ );+ }#[test]fn test_extract_host_authority_strips_path_preserves_port() {diff --git a/src/tui/app/download.rs b/src/tui/app/download.rsindex 9bba89e..1544c9a 100644--- a/src/tui/app/download.rs+++ b/src/tui/app/download.rs@@ -78,6 +78,32 @@ impl App {)};let destination = target_dir.join(format!("{base_name}.{extension}"));+ {+ let normalize_unc = |p: std::path::PathBuf| -> std::path::PathBuf {+ #[cfg(windows)]+ {+ let s = p.to_string_lossy();+ if let Some(stripped) = s.strip_prefix(r"\\?\") {+ return std::path::PathBuf::from(stripped);+ }+ }+ p+ };+ let resolved_base =+ normalize_unc(std::fs::canonicalize(&base_dir).unwrap_or(base_dir.clone()));+ let resolved_dest = normalize_unc(+ std::fs::canonicalize(target_dir.parent().unwrap_or(&target_dir))+ .unwrap_or(target_dir.clone()),+ );+ if !resolved_dest.starts_with(&resolved_base) {+ self.state.notify(+ NotificationKind::Warning,+ "Download blocked",+ "Destination path is outside the download directory.",+ );+ return;+ }+ }if is_media_already_downloaded(&target_dir, &base_name) {self.state.is_waiting_for_download_stream = false;self.state.notify(diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex cd5453f..6ed2354 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -314,7 +314,9 @@ impl App {match download_res {Ok(path) => {local_subtitle = Some(path.to_string_lossy().into_owned());- temporary_subtitle = Some(path);+ if !matches!(kind, crate::tui::state::PlayerKind::AndroidIntent) {+ temporary_subtitle = Some(path);+ }}Err(_) => {local_subtitle = None;@@ -346,7 +348,9 @@ impl App {Ok(local_url) => {let sub_url =if matches!(kind, crate::tui::state::PlayerKind::AndroidIntent) {- if let Some(remote_sub) = &subtitle {+ if local_subtitle.is_some() {+ local_subtitle.clone()+ } else if let Some(remote_sub) = &subtitle {if let Some(authority) = local_url.strip_prefix("http://").and_then(|s| s.split('/').next())@@ -357,10 +361,10 @@ impl App {);Some(format!("http://{authority}/sub/{encoded}"))} else {- local_subtitle.clone()+ None}} else {- local_subtitle.clone()+ None}} else {local_subtitle.clone()diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rsindex cb835a7..2d3fd09 100644--- a/src/tui/app/requests.rs+++ b/src/tui/app/requests.rs@@ -868,32 +868,66 @@ impl App {self.state.details_error = None;if let Some(existing) = &self.state.selected_details {- if existing.id.value == id && existing.id.provider == details.id.provider {- if details.title.trim().is_empty() {+ let is_same_subject = existing.id.value == id+ || existing.dubs.iter().any(|d| d.subject_id == id)+ || details+ .dubs+ .iter()+ .any(|d| d.subject_id == existing.id.value)+ || crate::providers::moviebox::clean_moviebox_title(&existing.title)+ == crate::providers::moviebox::clean_moviebox_title(&details.title);++ if is_same_subject && existing.id.provider == details.id.provider {+ if details.title.trim().is_empty()+ || (!existing.title.trim().is_empty()+ && crate::providers::moviebox::clean_moviebox_title(&details.title)+ == crate::providers::moviebox::clean_moviebox_title(+ &existing.title,+ ))+ {details.title = existing.title.clone();}- if details.description.is_none() {+ let is_placeholder_desc = |desc: &Option<String>| {+ desc.as_ref().is_none_or(|d| {+ let trimmed = d.trim();+ trimmed.is_empty()+ || trimmed == "N/A"+ || crate::providers::moviebox::clean_moviebox_title(trimmed)+ == crate::providers::moviebox::clean_moviebox_title(+ &details.title,+ )+ })+ };+ if is_placeholder_desc(&details.description)+ && !is_placeholder_desc(&existing.description)+ {details.description = existing.description.clone();}if details.poster_url.is_none() {details.poster_url = existing.poster_url.clone();}- if details.year.is_none() {+ if details.year.is_none() || details.year.as_deref() == Some("N/A") {details.year = existing.year.clone();}- if details.duration.is_none() {+ if details.duration.is_none()+ || details.duration.as_deref() == Some("N/A")+ || details.duration.as_deref() == Some("")+ {details.duration = existing.duration.clone();}if details.genres.is_empty() {details.genres = existing.genres.clone();}- if details.imdb_rating.is_none() {+ if details.imdb_rating.is_none()+ || details.imdb_rating.as_deref() == Some("N/A")+ {details.imdb_rating = existing.imdb_rating.clone();}- if details.director.is_none() {+ if details.director.is_none() || details.director.as_deref() == Some("N/A")+ {details.director = existing.director.clone();}- if details.stars.is_none() {+ if details.stars.is_none() || details.stars.as_deref() == Some("N/A") {details.stars = existing.stars.clone();}if details.dubs.is_empty() {@@ -902,11 +936,16 @@ impl App {}}- if let Some(res) = self.state.search_results.iter().find(|r| r.id == id) {+ if let Some(res) = self.state.search_results.iter().find(|r| {+ r.id == id+ || details.dubs.iter().any(|d| d.subject_id == r.id)+ || crate::providers::moviebox::clean_moviebox_title(&r.title)+ == crate::providers::moviebox::clean_moviebox_title(&details.title)+ }) {if details.title.trim().is_empty() {details.title = res.title.clone();}- if details.year.is_none() {+ if details.year.is_none() || details.year.as_deref() == Some("N/A") {details.year = Some(res.release_year.clone());}if details.poster_url.is_none() {@@ -1945,4 +1984,95 @@ mod tests {assert_eq!(app.state.selected_resources.len(), 2);}++ #[tokio::test]+ async fn test_details_success_preserves_rich_metadata_across_dub_switch() {+ use crate::providers::models::{+ AudioTrackOption, MediaDetails, MediaType, ProviderMediaId,+ };++ let mut app = App::new();+ app.state.active_screen = crate::tui::state::Screen::Details;+ let original_id = "100".to_string();+ let dub_id = "200".to_string();++ app.state.selected_details = Some(MediaDetails {+ id: ProviderMediaId {+ provider: ProviderKind::MovieBox,+ value: original_id.clone(),+ },+ title: "Ek Deewane Ki Deewaniyat".to_string(),+ media_type: MediaType::Movie,+ year: Some("2025".to_string()),+ description: Some(+ "When a powerful politician falls for a strong-willed superstar...".to_string(),+ ),+ tagline: None,+ imdb_rating: Some("4.7".to_string()),+ director: Some("Director Name".to_string()),+ stars: Some("Actor One, Actor Two".to_string()),+ prints: None,+ audios: None,+ poster_url: Some("https://example.com/poster.jpg".to_string()),+ duration: Some("2h 20m".to_string()),+ genres: vec!["Romance".to_string(), "Drama".to_string()],+ seasons: vec![],+ dubs: vec![+ AudioTrackOption {+ subject_id: original_id.clone(),+ language: "Original".to_string(),+ label: "Original".to_string(),+ },+ AudioTrackOption {+ subject_id: dub_id.clone(),+ language: "Hindi".to_string(),+ label: "Hindi".to_string(),+ },+ ],+ });++ let dub_details = Box::new(MediaDetails {+ id: ProviderMediaId {+ provider: ProviderKind::MovieBox,+ value: dub_id.clone(),+ },+ title: "Ek Deewane Ki Deewaniyat [Hindi]".to_string(),+ media_type: MediaType::Movie,+ year: Some("2025".to_string()),+ description: Some("Ek Deewane Ki Deewaniyat".to_string()),+ tagline: None,+ imdb_rating: Some("4.7".to_string()),+ director: None,+ stars: None,+ prints: None,+ audios: None,+ poster_url: None,+ duration: None,+ genres: vec![],+ seasons: vec![],+ dubs: vec![],+ });++ let context = app.request_context();+ let request_id = app.state.active_details_request;+ app.handle_requests(Action::DetailsSuccess(+ context,+ request_id,+ dub_id,+ dub_details,+ ))+ .await;++ let details = app.state.selected_details.as_ref().unwrap();+ assert_eq!(details.duration.as_deref(), Some("2h 20m"));+ assert_eq!(+ details.description.as_deref(),+ Some("When a powerful politician falls for a strong-willed superstar...")+ );+ assert_eq!(details.title, "Ek Deewane Ki Deewaniyat");+ assert_eq!(details.genres, vec!["Romance", "Drama"]);+ assert_eq!(details.director.as_deref(), Some("Director Name"));+ assert_eq!(details.stars.as_deref(), Some("Actor One, Actor Two"));+ assert_eq!(details.dubs.len(), 2);+ }}diff --git a/src/tui/app/run.rs b/src/tui/app/run.rsindex 41eb91d..3d95857 100644--- a/src/tui/app/run.rs+++ b/src/tui/app/run.rs@@ -306,8 +306,9 @@ impl App {},Screen::Details => {if let Some(details) = &self.state.selected_details {- if !details.title.is_empty() {- return format!("MovieBox-Tui — {}", details.title);+ let clean = crate::providers::moviebox::clean_moviebox_title(&details.title);+ if !clean.is_empty() {+ return format!("MovieBox-Tui — {clean}");}}"MovieBox-Tui — Details".to_string()diff --git a/src/tui/event.rs b/src/tui/event.rsindex 5bc0c79..c484841 100644--- a/src/tui/event.rs+++ b/src/tui/event.rs@@ -22,6 +22,26 @@ impl EventHandler {}}});+ #[cfg(unix)]+ tokio::spawn({+ let signal_sender = sender.clone();+ async move {+ use tokio::signal::unix::{SignalKind, signal};+ let mut sigterm = match signal(SignalKind::terminate()) {+ Ok(s) => s,+ Err(_) => return,+ };+ let mut sighup = match signal(SignalKind::hangup()) {+ Ok(s) => s,+ Err(_) => return,+ };+ tokio::select! {+ _ = sigterm.recv() => {}+ _ = sighup.recv() => {}+ }+ let _ = signal_sender.send(Action::Quit).await;+ }+ });tokio::spawn(async move {let mut tick_interval = tokio::time::interval(tick_rate);