Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

fix(lifecycle): harden tasks, child processes, and platform fallbacks

Samir Hossainse5111615324a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 98e0750..6e72f43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,50 @@
## [Unreleased]
+### Added
+- **VLC MovieBox DASH and Signed Cookie Streaming Compatibility**:
+ - Added a detached loopback HTTP sidecar proxy (`--proxy-for-vlc`) enabling VLC playback for MovieBox MPEG-DASH and MP4 streams protected by AWS CloudFront signed cookies (`CloudFront-Policy`, `CloudFront-Signature`, `CloudFront-Key-Pair-Id`).
+ - Implemented hierarchical path proxy routing (`/https/<host>/path` and `/http/<host>/path`) in `src/proxy.rs`; VLC's adaptive demuxer resolves relative segment URLs against the proxy path, eliminating query-string stripping that caused 400 Bad Request on DASH segment fetches.
+ - Added in-flight DASH manifest rewriter targeting origin CDN hosts to rewrite relative and absolute segment URLs to route through the local proxy.
+ - Added zero-copy chunked streaming using `reqwest::Response::bytes_stream()` for constant-memory chunk forwarding without buffering full segments in RAM.
+ - Configured platform process detachment via `process_group(0)` on Unix and `DETACHED_PROCESS` with `CREATE_NEW_PROCESS_GROUP` on Windows, ensuring streaming survives terminal window closure.
+ - Updated `supports_headers` and `header_capable_players` in `src/player.rs` to allow VLC as a supported player for all streaming sources.
+
+
+### Fixed
+- **VLC Sidecar Proxy Correctness**:
+ - Replaced `reqwest::Client::timeout(30s)` (a hard deadline over the entire response body) with `connect_timeout(15s)` only; per-chunk idle timeout (60s) now signals stalled transfers without terminating long-running video streams mid-playback.
+ - Introduced a `ConnectionGuard` RAII wrapper ensuring `active_connections` is atomically decremented even when a connection handler task panics, eliminating a counter leak that kept the sidecar alive indefinitely under 24/7 operation.
+ - Set watchdog idle threshold to 10 minutes (600s) with a 15-second polling interval; removed parent-PID liveness polling — the sidecar is fully detached and exits cleanly after 10 minutes of inactivity with no active connections.
+ - Fixed host-authority extraction to preserve explicit port numbers (e.g. `cdn.example.com:8080`) in DASH manifest segment URL rewriting; previously the port was stripped, routing manifest-relative segments to the wrong CDN endpoint and causing 400/403 errors.
+ - Capped HTTP request-line and header reads at 8 KiB per line and 64 headers per request, preventing unbounded `read_line` memory growth from malformed or adversarial clients.
+ - Added `child.wait()` after `child.kill()` on proxy spawn failure to reap the child process and avoid zombie accumulation.
+- **Search Poster Loader**: Cleared `in_flight_posters` when navigating back from the Details screen (`GoBack` → `Screen::Details` path) so that poster fetch tasks cancelled mid-flight no longer leave permanent "Loading..." placeholders on the next visit.
+- **Stream Cache TTL**: `set_provider_stream_cache_typed` now parses `DateLessThan` / `AWS:EpochTime` from the `CloudFront-Policy` Base64 payload embedded in release `Cookie` headers and caps the on-disk cache TTL to `min(2h, cf_expiry_remaining)` (floor 60s), preventing stale cached stream URLs from being served after CloudFront signed-cookie expiry.
+- **Process & Task Lifecycle Resilience**:
+ - Configured `kill_on_drop(true)` on `tokio::process::Command` when spawning `yt-dlp` in `start_resilient_download`, preventing orphaned download worker processes from continuing in the background if tasks are cancelled.
+ - Added `JoinHandle` tracking for active download workers in `RequestTaskHandles`, pairing it with an asynchronous watcher that catches background worker panics and dispatches `Action::DownloadFailed` to prevent permanent state lockup.
+ - Hardened loopback proxy sidecar accept loop to catch transient I/O and network errors (`EMFILE`, `ECONNABORTED`, `EINTR`) with a 50ms backoff sleep, preventing premature daemon exit under socket pressure.
+ - Ensured `fetch_cancel` Arc is rotated to a fresh instance and active stream/details fetch tasks are explicitly aborted upon navigating back from the Details screen (`GoBack`), preventing subsequent searches from being poisoned by aborted states.
+ - Wrapped `Action::CheckForUpdates` in a strict 15-second timeout, preventing indefinite UI loading states during transient network drops or GitHub API stalls.
+ - Threaded explicit task cancellation across `RequestTaskHandles`, download cancellation tokens, and search fetch tokens upon receiving `Action::Quit`, ensuring all background I/O operations terminate before the terminal exits.
+ - Replaced detached spawned tasks in `AddonClient::fetch_addon_streams` with direct futures via `futures::future::join_all`, ensuring that cancelled stream lookups immediately drop pending addon network requests.
+ - Added sandbox environment detection for Flatpak (`FLATPAK_ID`, `/.flatpak-info`) and Snap (`SNAP`) in `src/updater`, preventing corrupt in-app self-update writes on read-only mountpoints and guiding users to their package managers.
+ - Staged update binaries in the directory adjacent to `current_exe` rather than a temporary filesystem mount, ensuring atomic replacement across distinct storage partitions (`EXDEV`).
+ - Fixed Windows update helper double-spawn race condition by ensuring the parent process terminates immediately without invoking redundant exec/spawn wrappers.
+ - Added root uid check (`libc::getuid() == 0`) before probing `/system/bin/am` on Android outside Termux, preventing SELinux exit code 126 crashes on modern Android releases.
+ - Gated Android `/storage/downloads` subtitle path probing with `is_termux_environment()`, preventing non-Android systems with `~/storage` from misrouting subtitle files.
+ - Updated `config_dir()` and `data_dir()` to fall back to `std::env::temp_dir()` with an explicit warning when user directories cannot be resolved.
+ - Updated `install.sh` to provide clear guidance when invoked on Windows MINGW/MSYS/Cygwin environments, and hardened SHA256 checksum parsing against leading asterisk formatting.
+- **TUI & Render Hot-Path Efficiency**:
+ - Added `id_index` (`HashSet<(String, String, i64)>`) to `FavoritesManager`, eliminating $O(N)$ linear scans across visible result cards on every render frame.
+ - Bound window title recomputations in `contextual_title()` to dirty frame updates or initial launches, eliminating per-tick allocations.
+ - Added active screen and editing mode guards to search suggestion debounce in `Action::Tick`, skipping redundant string operations when not actively typing queries.
+ - Consolidated duplicate theme picker keyboard navigation actions (`Up`, `Down`, `Home`, `End`, `PageUp`, `PageDown`) into a single state change handler.
+ - Pruned unused scaffolding structs (`UiState`, `CatalogState`, `PlaybackState`, `DownloadState`) from `src/tui/state.rs`.
+ - Pruned obsolete and unused action variants (`ProbeTerminal`, `ShowSettingsPopup`, `CloseSettingsPopup`) from `src/tui/action.rs` and consolidated settings handlers.
+ - Consolidated all video playback launches through canonical `LaunchPlayback` actions, removing misleading and redundant `LaunchMpv` aliases.
+ - Prioritized `termux-am` ahead of `termux-open` in Android opener probing to preserve HTTP request headers and subtitle arguments.
### Changed
- **Symmetrical Popup and Picker Margin Alignment**:
- Eliminated lopsided right-side dead space across all floating popup pickers (Theme Picker, Streaming Sources, Media Player, Subtitles, Catalog Browse, and Provider Popup), aligning borders to provide equal horizontal padding on both sides (`│ content │`).
diff --git a/install.sh b/install.sh
index d17e915..22e051f 100755
--- a/install.sh
+++ b/install.sh
@@ -410,6 +410,11 @@ elif [ "$OS" = "Linux" ]; then
log_error "Unsupported Linux architecture ($ARCH). Only x86_64 and arm64 are supported."
exit 1
fi
+elif case "$OS" in MINGW*|MSYS*|CYGWIN*) true ;; *) false ;; esac; then
+ log_error "Windows environment detected ($OS)."
+ printf "\n %bℹ%b Please use the official Windows PowerShell installer:\n" "$C_SAPPHIRE" "$C_RESET" >&2
+ printf " %birm https://raw.githubusercontent.com/%s/main/install.ps1 | iex%b\n\n" "$C_BOLD" "$REPO" "$C_RESET" >&2
+ exit 1
else
log_error "Unsupported Operating System ($OS)."
exit 1
@@ -534,7 +539,7 @@ log_success "[2/4] Downloaded $FILE"
verify_checksum() {
local expected_sha
- expected_sha=$(awk -v file="$FILE" '$2 == file {print $1}' "$TMP_DIR/SHA256SUMS")
+ expected_sha=$(awk -v file="$FILE" '{gsub(/^\*/, "", $2); if ($2 == file) print $1}' "$TMP_DIR/SHA256SUMS")
if [ -z "$expected_sha" ]; then
return 1
fi
diff --git a/src/cache.rs b/src/cache.rs
index 2613e8a..d88c8ea 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -280,7 +280,59 @@ pub fn set_provider_stream_cache_typed(
return;
}
let path = get_provider_stream_path(provider, subject_id, season, episode);
- set_typed_cache(&path, STREAM_CACHE_EXPIRY_SECS, releases);
+ let ttl = stream_cache_ttl_secs(releases);
+ set_typed_cache(&path, ttl, releases);
+}
+
+fn stream_cache_ttl_secs(releases: &[Release]) -> u64 {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ let min_cf_expiry = releases
+ .iter()
+ .flat_map(|r| &r.mirrors)
+ .flat_map(|mirror| &mirror.headers)
+ .filter(|(name, _)| name.eq_ignore_ascii_case("cookie"))
+ .flat_map(|(_, val)| val.split(';'))
+ .filter_map(|part| {
+ let policy_raw = part.trim().strip_prefix("CloudFront-Policy=")?;
+ cf_policy_date_less_than(policy_raw)
+ })
+ .min();
+ let cf_remaining = min_cf_expiry
+ .and_then(|exp| exp.checked_sub(now))
+ .unwrap_or(STREAM_CACHE_EXPIRY_SECS);
+ cf_remaining.clamp(60, STREAM_CACHE_EXPIRY_SECS)
+}
+
+fn cf_policy_date_less_than(policy_raw: &str) -> Option<u64> {
+ use base64::Engine as _;
+ let mut normalized: String = policy_raw
+ .trim()
+ .chars()
+ .map(|c| match c {
+ '-' => '+',
+ '_' => '=',
+ '~' => '/',
+ other => other,
+ })
+ .collect();
+ let padding = (4 - normalized.len() % 4) % 4;
+ if padding > 0 {
+ normalized.push_str(&"=".repeat(padding));
+ }
+ let decoded = base64::engine::general_purpose::STANDARD
+ .decode(normalized.as_bytes())
+ .ok()?;
+ let json: serde_json::Value = serde_json::from_slice(&decoded).ok()?;
+ json.get("Statement")?
+ .as_array()?
+ .first()?
+ .get("Condition")?
+ .get("DateLessThan")?
+ .get("AWS:EpochTime")?
+ .as_u64()
}
pub fn invalidate_provider_stream_cache(
diff --git a/src/config.rs b/src/config.rs
index 1411c4f..e20aa7c 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -66,7 +66,15 @@ pub fn config_dir() -> Option<PathBuf> {
return Some(p);
}
}
- dirs::home_dir().map(|h| h.join(".config").join(APP_NAME))
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".config").join(APP_NAME)) {
+ return Some(dir);
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("config");
+ log::warn!(
+ "unable to locate user config directory, falling back to {}",
+ fallback.display()
+ );
+ Some(fallback)
}
pub fn data_dir() -> Option<PathBuf> {
@@ -88,7 +96,15 @@ pub fn data_dir() -> Option<PathBuf> {
return Some(p);
}
}
- dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME))
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME)) {
+ return Some(dir);
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("data");
+ log::warn!(
+ "unable to locate user data directory, falling back to {}",
+ fallback.display()
+ );
+ Some(fallback)
}
pub fn cache_dir() -> PathBuf {
diff --git a/src/favorites.rs b/src/favorites.rs
index 418d086..feebbf6 100644
--- a/src/favorites.rs
+++ b/src/favorites.rs
@@ -68,6 +68,8 @@ impl FavoriteItem {
pub struct FavoritesManager {
#[serde(default)]
pub items: Vec<FavoriteItem>,
+ #[serde(skip)]
+ id_index: std::collections::HashSet<(String, String, i64)>,
}
impl FavoritesManager {
@@ -86,7 +88,10 @@ impl FavoritesManager {
if path.exists() {
match fs::read_to_string(path) {
Ok(content) => match serde_json::from_str::<Self>(&content) {
- Ok(manager) => return manager,
+ Ok(mut manager) => {
+ manager.rebuild_index();
+ return manager;
+ }
Err(e) => {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -126,12 +131,34 @@ impl FavoritesManager {
}
}
+ pub fn rebuild_index(&mut self) {
+ self.id_index.clear();
+ for item in &self.items {
+ let prov_canonical = crate::providers::models::ProviderKind::parse(&item.provider)
+ .map(|p| p.cache_key().to_string())
+ .unwrap_or_else(|| item.provider.trim().to_ascii_lowercase());
+ self.id_index
+ .insert((prov_canonical, item.subject_id.clone(), item.stype));
+ }
+ }
+
pub fn is_favorite(&self, identity: &crate::models::SubjectIdentity<'_>) -> bool {
+ if !identity.subject_id.is_empty() {
+ let prov_canonical = crate::providers::models::ProviderKind::parse(identity.provider)
+ .map(|p| p.cache_key().to_string())
+ .unwrap_or_else(|| identity.provider.trim().to_ascii_lowercase());
+ if self.id_index.contains(&(
+ prov_canonical,
+ identity.subject_id.to_string(),
+ identity.stype,
+ )) {
+ return true;
+ }
+ }
self.items
.iter()
.any(|item| item.identity().matches(identity))
}
-
pub fn toggle(&mut self, item: FavoriteItem) -> bool {
let now_favorited = if let Some(pos) = self
.items
@@ -144,17 +171,20 @@ impl FavoritesManager {
self.items.push(item);
true
};
+ self.rebuild_index();
self.save();
now_favorited
}
pub fn remove(&mut self, identity: &crate::models::SubjectIdentity<'_>) {
self.items.retain(|item| !item.identity().matches(identity));
+ self.rebuild_index();
self.save();
}
pub fn clear(&mut self) {
self.items.clear();
+ self.rebuild_index();
self.save();
}
}
@@ -162,7 +192,6 @@ impl FavoritesManager {
#[cfg(test)]
mod tests {
use super::*;
-
fn dummy_item(
provider: &str,
subject_id: &str,
diff --git a/src/providers/addons/aggregator.rs b/src/providers/addons/aggregator.rs
index a1e1400..fa13113 100644
--- a/src/providers/addons/aggregator.rs
+++ b/src/providers/addons/aggregator.rs
@@ -35,7 +35,7 @@ pub async fn aggregate_streams(
let id_clone = stream_id.clone();
let m_type = media_type.to_string();
- tasks.push(tokio::spawn(async move {
+ tasks.push(async move {
let streams_res = client_clone
.fetch_streams(&base_url, &m_type, &id_clone)
.await;
@@ -57,14 +57,14 @@ pub async fn aggregate_streams(
}
Err(_) => (Vec::new(), None),
}
- }));
+ });
}
let results = futures::future::join_all(tasks).await;
let mut all_releases = Vec::new();
let mut blocked_addons = Vec::new();
- for res in results.into_iter().flatten() {
+ for res in results {
all_releases.extend(res.0);
if let Some(blocked) = res.1 {
blocked_addons.push(blocked);
diff --git a/src/service.rs b/src/service.rs
index 2b11bee..dcccbd6 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -420,11 +420,13 @@ pub fn extract_browse_metrics(item: &serde_json::Value) -> BrowseMetrics {
}
pub fn resolve_subtitle_dir() -> PathBuf {
- if let Some(home) = dirs::home_dir() {
- let storage = home.join("storage/downloads/moviebox_subs");
- if home.join("storage/downloads").exists() {
- let _ = std::fs::create_dir_all(&storage);
- return storage;
+ if crate::updater::artifact::is_termux_environment() {
+ if let Some(home) = dirs::home_dir() {
+ let storage = home.join("storage/downloads/moviebox_subs");
+ if home.join("storage/downloads").exists() {
+ let _ = std::fs::create_dir_all(&storage);
+ return storage;
+ }
}
}
crate::config::cache_dir().join("subs")
diff --git a/src/tui/action.rs b/src/tui/action.rs
index 4ba9a62..f5d6b04 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -60,7 +60,6 @@ pub enum Action {
WheelScroll {
up: bool,
},
- ProbeTerminal,
Submit,
TabPane,
BackTabPane,
@@ -73,8 +72,6 @@ pub enum Action {
ToggleThemePopup,
SelectTheme(String),
ToggleSettingsPopup,
- ShowSettingsPopup,
- CloseSettingsPopup,
SelectSettingsCategory(crate::tui::state::SettingsCategory),
SettingsAdjustValue(bool),
SettingsActivateRow,
@@ -82,7 +79,6 @@ pub enum Action {
ShowBrowseMenu,
SelectBrowse(crate::tui::state::BrowsePreset),
SelectAddonCatalog(crate::providers::addons::models::AddonCatalogTarget),
- LaunchMpv(String, Option<String>),
DownloadStream(Option<String>),
StartDownload(Option<String>, Option<String>, Vec<(String, String)>),
UpdateDownload(Option<f64>, Option<String>),
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index ffcab2a..1c352fa 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -143,7 +143,8 @@ impl App {
let is_dash = link.ends_with(".mpd") || link.contains("/dash/");
- tokio::spawn(async move {
+ self.request_tasks.cancel_download();
+ let handle = tokio::spawn(async move {
if let Err(error) = tokio::fs::create_dir_all(&target_dir).await {
sender
.send(Action::DownloadFailed(format!(
@@ -253,10 +254,9 @@ impl App {
{
cmd.creation_flags(crate::player::CREATE_NO_WINDOW);
}
-
+ cmd.kill_on_drop(true);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
-
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(err) => {
@@ -447,6 +447,18 @@ impl App {
}
}
});
+ let fail_sender = self.action_sender.clone();
+ let watcher = tokio::spawn(async move {
+ if let Err(e) = handle.await
+ && e.is_panic()
+ {
+ log::error!("download task panicked: {e}");
+ let _ = fail_sender.send(Action::DownloadFailed(
+ "Download task failed unexpectedly".to_string(),
+ ));
+ }
+ });
+ self.request_tasks.download = Some(watcher);
}
}
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 4637622..b729ee2 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -302,6 +302,8 @@ impl App {
}
if self.state.show_theme_popup {
+ let total = crate::tui::theme::AVAILABLE_THEMES.len();
+ let mut changed = false;
match key.code {
KeyCode::Esc => {
self.state.show_theme_popup = false;
@@ -312,77 +314,46 @@ impl App {
KeyCode::Up | KeyCode::Char('k') => {
crate::tui::state::cycle_list_selection(
&mut self.state.theme_list_state,
- crate::tui::theme::AVAILABLE_THEMES.len(),
+ total,
false,
);
- if let Some(i) = self.state.theme_list_state.selected() {
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[i].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
- }
+ changed = true;
}
KeyCode::Down | KeyCode::Char('j') => {
crate::tui::state::cycle_list_selection(
&mut self.state.theme_list_state,
- crate::tui::theme::AVAILABLE_THEMES.len(),
+ total,
true,
);
- if let Some(i) = self.state.theme_list_state.selected() {
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[i].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
- }
+ changed = true;
}
KeyCode::Home => {
- let total = crate::tui::theme::AVAILABLE_THEMES.len();
if total > 0 {
self.state.theme_list_state.select(Some(0));
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[0].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
+ changed = true;
}
}
KeyCode::End => {
- let total = crate::tui::theme::AVAILABLE_THEMES.len();
if total > 0 {
- let last = total - 1;
- self.state.theme_list_state.select(Some(last));
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[last].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
+ self.state.theme_list_state.select(Some(total - 1));
+ changed = true;
}
}
KeyCode::PageUp => {
- let total = crate::tui::theme::AVAILABLE_THEMES.len();
crate::tui::state::step_list_selection(
&mut self.state.theme_list_state,
total,
-5,
);
- if let Some(next) = self.state.theme_list_state.selected() {
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[next].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
- }
+ changed = true;
}
KeyCode::PageDown => {
- let total = crate::tui::theme::AVAILABLE_THEMES.len();
crate::tui::state::step_list_selection(
&mut self.state.theme_list_state,
total,
5,
);
- if let Some(next) = self.state.theme_list_state.selected() {
- let selected_theme = crate::tui::theme::AVAILABLE_THEMES[next].to_string();
- self.action_sender
- .send(Action::SelectTheme(selected_theme))
- .ok();
- }
+ changed = true;
}
KeyCode::Enter => {
self.state.show_theme_popup = false;
@@ -391,6 +362,14 @@ impl App {
}
_ => {}
}
+ if changed {
+ if let Some(i) = self.state.theme_list_state.selected() {
+ let selected_theme = crate::tui::theme::AVAILABLE_THEMES[i].to_string();
+ self.action_sender
+ .send(Action::SelectTheme(selected_theme))
+ .ok();
+ }
+ }
return None;
}
if self.state.show_settings_popup {
@@ -1383,7 +1362,7 @@ mod tests {
app.state.active_screen = crate::tui::state::Screen::Home;
app.state.input_mode = InputMode::Normal;
app.state.search_query.set_content("/history");
-
+ app.state.history.recent.clear();
let item = crate::history::WatchHistoryItem {
provider: "moviebox".to_string(),
subject_id: "hist-1".to_string(),
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 39c9063..910a237 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -24,6 +24,7 @@ pub struct RequestTaskHandles {
pub streams: Option<tokio::task::JoinHandle<()>>,
pub suggest: Option<tokio::task::JoinHandle<()>>,
pub homepage: Option<tokio::task::JoinHandle<()>>,
+ pub download: Option<tokio::task::JoinHandle<()>>,
}
impl RequestTaskHandles {
@@ -56,6 +57,11 @@ impl RequestTaskHandles {
h.abort();
}
}
+ pub fn cancel_download(&mut self) {
+ if let Some(h) = self.download.take() {
+ h.abort();
+ }
+ }
pub fn cancel_all(&mut self) {
self.cancel_search();
@@ -63,6 +69,7 @@ impl RequestTaskHandles {
self.cancel_streams();
self.cancel_suggest();
self.cancel_homepage();
+ self.cancel_download();
}
}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index a4da87a..2256dc4 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -418,7 +418,12 @@ impl App {
Screen::Details => {
self.state
.fetch_cancel
- .store(true, std::sync::atomic::Ordering::Relaxed);
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ self.state.fetch_cancel =
+ std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ self.request_tasks.cancel_details();
+ self.request_tasks.cancel_streams();
+ self.state.in_flight_posters.clear();
self.state.active_preview_request =
self.state.active_preview_request.wrapping_add(1);
self.state.active_details_request =
@@ -738,9 +743,17 @@ impl App {
source.subtitle = sub_url;
self.dispatch_playback_or_notify(source);
} else if let Some(link) = self.state.pending_play_link.take() {
- self.action_sender
- .send(Action::LaunchMpv(link, sub_url))
- .ok();
+ let source = crate::providers::models::PlaybackSource {
+ provider: self.state.active_provider,
+ url: link,
+ headers: vec![(
+ "User-Agent".to_string(),
+ self.service.client.user_agent().to_string(),
+ )],
+ subtitle: sub_url,
+ source_label: "Direct".to_string(),
+ };
+ self.dispatch_playback_or_notify(source);
}
return None;
} else if self.state.is_download_subtitle_popup {
@@ -783,9 +796,14 @@ impl App {
idx_opt.and_then(|idx| self.state.search_results.get(idx).cloned());
if let Some(item) = item_opt {
if self.state.is_tv_mode || item.stype == 3 {
- self.action_sender
- .send(Action::LaunchMpv(item.id.clone(), None))
- .ok();
+ let source = crate::providers::models::PlaybackSource {
+ provider: item.provider,
+ url: item.id.clone(),
+ headers: Vec::new(),
+ subtitle: None,
+ source_label: "Live TV".to_string(),
+ };
+ self.dispatch_playback_or_notify(source);
return None;
}
self.state.active_screen = Screen::Details;
@@ -863,9 +881,14 @@ impl App {
let item_opt = idx_opt.and_then(|idx| self.state.search_results.get(idx).cloned());
if let Some(item) = item_opt {
if self.state.is_tv_mode || item.stype == 3 {
- self.action_sender
- .send(Action::LaunchMpv(item.id.clone(), None))
- .ok();
+ let source = crate::providers::models::PlaybackSource {
+ provider: item.provider,
+ url: item.id.clone(),
+ headers: Vec::new(),
+ subtitle: None,
+ source_label: "Live TV".to_string(),
+ };
+ self.dispatch_playback_or_notify(source);
return;
}
self.state.active_screen = Screen::Details;
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index ecf25c1..81f1f22 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -255,8 +255,8 @@ impl App {
let manifest_url = target.manifest_url.clone();
let r_type = target.r#type.clone();
let cat_id = target.catalog_id.clone();
-
- tokio::spawn(async move {
+ self.request_tasks.cancel_search();
+ self.request_tasks.search = Some(tokio::spawn(async move {
let result = service
.fetch_addon_catalog(&manifest_url, &r_type, &cat_id)
.await;
@@ -278,7 +278,7 @@ impl App {
.ok();
}
}
- });
+ }));
}
Action::SearchSuccess {
@@ -1329,7 +1329,8 @@ impl App {
.unwrap_or(season > 0);
let has_stream_addons = addons.iter().any(|a| a.enabled && a.provides_stream);
- tokio::spawn(async move {
+ self.request_tasks.cancel_streams();
+ self.request_tasks.streams = Some(tokio::spawn(async move {
if !has_stream_addons {
sender
.send(Action::EpisodeStreamsFailed(
@@ -1388,7 +1389,7 @@ impl App {
))
.ok();
}
- });
+ }));
return None;
}
@@ -1398,7 +1399,8 @@ impl App {
let circleftp_client = self.service.circleftp_client.clone();
let dhakaflix_client = self.service.dhakaflix_client.clone();
let id = subject_id.clone();
- tokio::spawn(async move {
+ self.request_tasks.cancel_streams();
+ self.request_tasks.streams = Some(tokio::spawn(async move {
let result = match context.provider {
ProviderKind::FourKHdHub => {
if let Some(client) = fourk_client.as_ref() {
@@ -1477,7 +1479,7 @@ impl App {
.ok();
}
}
- });
+ }));
return None;
}
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 07a3796..f51628c 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -91,10 +91,12 @@ impl App {
let _ = crossterm::execute!(std::io::stdout(), style);
self.state.cursor_beam = want_beam;
}
- let title = self.contextual_title();
- if title != last_window_title {
- let _ = crate::tui::terminal::set_window_title(&title);
- last_window_title = title;
+ if self.state.dirty || last_window_title.is_empty() {
+ let title = self.contextual_title();
+ if title != last_window_title {
+ let _ = crate::tui::terminal::set_window_title(&title);
+ last_window_title = title;
+ }
}
self.state.normalize_result_view();
if self.state.clear_terminal_before_draw {
@@ -321,6 +323,13 @@ impl App {
}
match action {
Action::Quit => {
+ self.request_tasks.cancel_all();
+ self.state
+ .cancel_download
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ self.state
+ .fetch_cancel
+ .store(true, std::sync::atomic::Ordering::SeqCst);
return Some(());
}
@@ -332,26 +341,6 @@ impl App {
self.handle_mouse(col, row);
}
- Action::ProbeTerminal => {
- self.probe_terminal().await;
- let outcome = if self.state.image_supported {
- let protocol = self
- .state
- .image_picker
- .as_ref()
- .map(|picker| format!("{:?}", picker.protocol_type()))
- .unwrap_or_default();
- format!("Graphics protocol: {protocol}")
- } else {
- "No graphics protocol detected; using text placeholders".to_string()
- };
- self.state.notify(
- crate::tui::overlay::NotificationKind::Info,
- "Terminal probe",
- outcome,
- );
- }
-
Action::WheelScroll { up } => {
if self.state.show_help {
let delta = 3 * if up { -1i32 } else { 1 };
@@ -395,8 +384,6 @@ impl App {
| Action::SelfUpdateProgress(..)
| Action::SelfUpdateComplete(..)
| Action::ToggleSettingsPopup
- | Action::ShowSettingsPopup
- | Action::CloseSettingsPopup
| Action::SelectSettingsCategory(..)
| Action::SettingsAdjustValue(..)
| Action::SettingsActivateRow
@@ -468,7 +455,6 @@ impl App {
Action::PlayStream
| Action::ShowSubtitlePopup(..)
| Action::ShowDownloadSubtitlePopup(..)
- | Action::LaunchMpv(..)
| Action::LaunchPlayback(..)
| Action::DispatchPlayback(..)
| Action::LaunchPlayer(..)
@@ -1161,6 +1147,24 @@ impl App {
.alignment(Alignment::Center),
);
}
+ crate::updater::apply::InstallationEnvironment::Flatpak => {
+ text.push(
+ Line::from(vec![Span::styled(
+ "Flatpak sandbox • Run: flatpak update",
+ self.theme.accent,
+ )])
+ .alignment(Alignment::Center),
+ );
+ }
+ crate::updater::apply::InstallationEnvironment::Snap => {
+ text.push(
+ Line::from(vec![Span::styled(
+ "Snap sandbox • Run: sudo snap refresh moviebox-tui",
+ self.theme.accent,
+ )])
+ .alignment(Alignment::Center),
+ );
+ }
crate::updater::apply::InstallationEnvironment::ReadOnly => {
text.push(
Line::from(vec![Span::styled(
@@ -1340,6 +1344,8 @@ impl App {
}
}
crate::updater::apply::InstallationEnvironment::Termux
+ | crate::updater::apply::InstallationEnvironment::Flatpak
+ | crate::updater::apply::InstallationEnvironment::Snap
| crate::updater::apply::InstallationEnvironment::ReadOnly => {
if is_compact_modal {
vec![
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 22a041e..cc17ea1 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -35,33 +35,37 @@ impl App {
self.state.dirty = true;
}
- let query_trimmed = self.state.search_query.as_str().trim();
- if query_trimmed != self.state.last_suggest_query.as_str()
- && self.state.last_search_edit.elapsed()
- >= std::time::Duration::from_millis(350)
+ if self.state.input_mode == crate::tui::state::InputMode::Editing
+ && self.state.active_screen == crate::tui::state::Screen::Home
{
- self.state.last_suggest_query.clear();
- self.state.last_suggest_query.push_str(query_trimmed);
- if !query_trimmed.is_empty() {
- if self.state.is_tv_mode && !query_trimmed.starts_with('/') {
- let q = query_trimmed.to_lowercase();
- self.state.search_suggestions = self
- .state
- .tv_channels
- .iter()
- .filter(|c| c.name.to_lowercase().contains(&q))
- .take(10)
- .map(|c| c.name.clone())
- .collect();
- self.state.dirty = true;
+ let query_trimmed = self.state.search_query.as_str().trim();
+ if query_trimmed != self.state.last_suggest_query.as_str()
+ && self.state.last_search_edit.elapsed()
+ >= std::time::Duration::from_millis(350)
+ {
+ self.state.last_suggest_query.clear();
+ self.state.last_suggest_query.push_str(query_trimmed);
+ if !query_trimmed.is_empty() {
+ if self.state.is_tv_mode && !query_trimmed.starts_with('/') {
+ let q = query_trimmed.to_lowercase();
+ self.state.search_suggestions = self
+ .state
+ .tv_channels
+ .iter()
+ .filter(|c| c.name.to_lowercase().contains(&q))
+ .take(10)
+ .map(|c| c.name.clone())
+ .collect();
+ self.state.dirty = true;
+ } else {
+ self.action_sender
+ .send(Action::Suggest(query_trimmed.to_string()))
+ .ok();
+ }
} else {
- self.action_sender
- .send(Action::Suggest(query_trimmed.to_string()))
- .ok();
+ self.state.search_suggestions.clear();
+ self.state.dirty = true;
}
- } else {
- self.state.search_suggestions.clear();
- self.state.dirty = true;
}
}
@@ -296,30 +300,6 @@ impl App {
}
}
- Action::ShowSettingsPopup => {
- for player in crate::tui::player::detect() {
- if !self.state.available_players.contains(&player) {
- self.state.available_players.push(player);
- }
- }
- self.state.ensure_default_player();
- self.state.show_settings_popup = true;
- self.state.settings_category = crate::tui::state::SettingsCategory::General;
- self.state.settings_selected_row = 0;
- self.state.settings_download_dir_input = None;
- self.state.settings_player_picker = false;
- self.state.show_sources_popup = false;
- self.state.input_mode = crate::tui::state::InputMode::Normal;
- }
-
- Action::CloseSettingsPopup => {
- self.state.show_settings_popup = false;
- self.state.settings_download_dir_input = None;
- self.state.settings_player_picker = false;
- self.state.show_sources_popup = false;
- self.persist_config();
- }
-
Action::SelectSettingsCategory(cat) => {
self.state.settings_select_category(cat);
}
@@ -692,11 +672,15 @@ impl App {
self.state.is_checking_updates = true;
let update_sender = self.action_sender.clone();
tokio::spawn(async move {
- let task =
- tokio::spawn(crate::updater::check_release(env!("CARGO_PKG_VERSION")));
- let result = match task.await {
+ let check_future = crate::updater::check_release(env!("CARGO_PKG_VERSION"));
+ let result = match tokio::time::timeout(
+ std::time::Duration::from_secs(15),
+ check_future,
+ )
+ .await
+ {
Ok(res) => res,
- Err(join_err) => Err(format!("update check task error: {join_err}")),
+ Err(_) => Err("update check timed out after 15 seconds".to_string()),
};
update_sender.send(Action::UpdateAvailable(result)).ok();
});
@@ -860,6 +844,7 @@ impl App {
)
.ok();
+ #[cfg(unix)]
if let Ok(exe_path) = std::env::current_exe() {
if let Err(e) = crate::updater::restart_process(&exe_path) {
log::error!("failed to restart process after update: {e}");
diff --git a/src/tui/event.rs b/src/tui/event.rs
index 4204d0c..5bc0c79 100644
--- a/src/tui/event.rs
+++ b/src/tui/event.rs
@@ -31,9 +31,16 @@ impl EventHandler {
loop {
tokio::select! {
_ = tick_interval.tick() => {
+ if event_sender.is_closed() {
+ break;
+ }
let _ = event_sender.try_send(Action::Tick);
}
- Some(event) = reader.next() => {
+ event_opt = reader.next() => {
+ let Some(event) = event_opt else { break; };
+ if event_sender.is_closed() {
+ break;
+ }
match event {
Ok(CrosstermEvent::Key(key)) => {
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 0cf4321..3d25c48 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -690,9 +690,7 @@ pub(crate) fn render_landing_deck(frame: &mut Frame, area: Rect, state: &AppStat
let pill_style = if state.basic_terminal {
theme.sapphire
} else {
- let bg = theme.surface1.fg.unwrap_or(theme.base);
- let fg = theme.sapphire.fg.unwrap_or(theme.base);
- Style::default().bg(bg).fg(fg)
+ theme.sapphire.add_modifier(Modifier::BOLD)
};
let pill_area = Rect {
x: inner_area.x,
@@ -958,9 +956,7 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.lavender
} else {
- let bg = theme.surface1_color();
- let fg = theme.lavender.fg.unwrap_or(theme.base);
- Style::default().bg(bg).fg(fg)
+ theme.lavender.add_modifier(Modifier::BOLD)
};
(text, style)
} else if state.active_provider == crate::providers::models::ProviderKind::Addons {
@@ -968,9 +964,7 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.teal
} else {
- let bg = theme.surface1_color();
- let fg = theme.teal.fg.unwrap_or(theme.base);
- Style::default().bg(bg).fg(fg)
+ theme.teal.add_modifier(Modifier::BOLD)
};
(text, style)
} else {
@@ -984,9 +978,7 @@ fn render_search_bar(
let style = if state.basic_terminal {
theme.sapphire
} else {
- let bg = theme.surface1_color();
- let fg = theme.sapphire.fg.unwrap_or(theme.base);
- Style::default().bg(bg).fg(fg)
+ theme.sapphire.add_modifier(Modifier::BOLD)
};
(text, style)
};
diff --git a/src/tui/state.rs b/src/tui/state.rs
index c0cf607..268f69a 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -144,72 +144,6 @@ pub fn result_columns_for(width: u16) -> u16 {
}
}
-#[derive(Debug, Default)]
-pub struct UiState {
- pub active_screen: Screen,
- pub input_mode: InputMode,
- pub dirty: bool,
- pub show_theme_popup: bool,
- pub active_theme_kind: String,
- pub theme_is_auto: bool,
- pub show_browse_popup: bool,
- pub show_settings_popup: bool,
- pub settings_category: SettingsCategory,
- pub settings_selected_row: usize,
- pub show_help: bool,
- pub help_scroll: usize,
- pub cursor_beam: bool,
- pub details_pane: DetailsPane,
- pub player_picker_popup: bool,
- pub settings_player_picker: bool,
- pub show_sources_popup: bool,
- pub subtitle_popup: bool,
- pub is_download_subtitle_popup: bool,
- pub tv_config_popup: bool,
- pub addon_manager_popup: bool,
- pub favorites_focus: bool,
- pub is_loading: bool,
- pub is_resolving_playback: bool,
- pub is_fetching_streams: bool,
-}
-
-#[derive(Debug, Default)]
-pub struct CatalogState {
- pub active_provider: ProviderKind,
- pub provider_generation: u64,
- pub current_tab_id: String,
- pub current_page: usize,
- pub is_homepage_mode: bool,
- pub active_subject_id: Option<String>,
- pub search_error: Option<String>,
- pub details_error: Option<String>,
- pub stream_error: Option<String>,
-}
-
-#[derive(Debug, Default)]
-pub struct PlaybackState {
- pub is_playing: bool,
- pub default_player: Option<String>,
- pub available_players: Vec<PlayerKind>,
- pub pending_play_link: Option<String>,
- pub pending_playback_source: Option<crate::providers::models::PlaybackSource>,
-}
-
-#[derive(Debug, Default)]
-pub struct DownloadState {
- pub download_progress: Option<f64>,
- pub download_status: Option<String>,
- pub download_title: Option<String>,
- pub download_dir: Option<std::path::PathBuf>,
- pub download_queue_total: usize,
- pub show_season_download_confirm: bool,
- pub season_download_confirm_yes_selected: bool,
- pub show_episode_download_confirm: bool,
- pub episode_download_confirm_yes_selected: bool,
- pub is_waiting_for_download_stream: bool,
- pub auto_play_on_ready: bool,
-}
-
pub struct AppState {
pub active_provider: ProviderKind,
pub provider_generation: u64,
diff --git a/src/tui/widgets/badge.rs b/src/tui/widgets/badge.rs
index 062461b..dc00be1 100644
--- a/src/tui/widgets/badge.rs
+++ b/src/tui/widgets/badge.rs
@@ -1,5 +1,5 @@
use ratatui::{
- style::{Modifier, Style},
+ style::{Color, Modifier, Style},
text::Span,
};
@@ -76,59 +76,80 @@ pub fn resolution_badge_spans<'a>(
return vec![Span::styled(format!("{:<7}", label), style), Span::raw(" ")];
}
+ let is_light = theme.is_light;
let (badge_bg, contrast_fg, label) = match resolution {
- -1 => (
+ -1 => {
+ let accent_color = theme.lavender.fg.unwrap_or(theme.base);
if is_selected {
- theme.lavender.fg.unwrap_or(theme.base)
+ (
+ accent_color,
+ if is_light {
+ Color::White
+ } else {
+ theme.crust_color()
+ },
+ " Multi ",
+ )
+ } else if is_light {
+ (theme.surface2_color(), accent_color, " Multi ")
} else {
- theme.surface1_color()
- },
- if is_selected {
- theme.crust_color()
- } else {
- theme.lavender.fg.unwrap_or(theme.base)
- },
- " Multi ",
- ),
- 2160 | 4320 => (
- if is_selected {
- theme.rating.fg.unwrap_or(theme.base)
- } else {
- theme.surface1_color()
- },
- if is_selected {
- theme.crust_color()
- } else {
- theme.rating.fg.unwrap_or(theme.base)
- },
- " 4K ",
- ),
- 1080 => (
- if is_selected {
- theme.sapphire.fg.unwrap_or(theme.base)
- } else {
- theme.surface1_color()
- },
+ (theme.surface1_color(), accent_color, " Multi ")
+ }
+ }
+ 2160 | 4320 => {
+ let accent_color = theme.rating.fg.unwrap_or(theme.base);
if is_selected {
- theme.crust_color()
+ (
+ accent_color,
+ if is_light {
+ Color::White
+ } else {
+ theme.crust_color()
+ },
+ " 4K ",
+ )
+ } else if is_light {
+ (theme.surface2_color(), accent_color, " 4K ")
} else {
- theme.sapphire.fg.unwrap_or(theme.base)
- },
- " 1080p ",
- ),
- 720 => (
+ (theme.surface1_color(), accent_color, " 4K ")
+ }
+ }
+ 1080 => {
+ let accent_color = theme.sapphire.fg.unwrap_or(theme.base);
if is_selected {
- theme.teal.fg.unwrap_or(theme.base)
+ (
+ accent_color,
+ if is_light {
+ Color::White
+ } else {
+ theme.crust_color()
+ },
+ " 1080p ",
+ )
+ } else if is_light {
+ (theme.surface2_color(), accent_color, " 1080p ")
} else {
- theme.surface1_color()
- },
+ (theme.surface1_color(), accent_color, " 1080p ")
+ }
+ }
+ 720 => {
+ let accent_color = theme.teal.fg.unwrap_or(theme.base);
if is_selected {
- theme.crust_color()
+ (
+ accent_color,
+ if is_light {
+ Color::White
+ } else {
+ theme.crust_color()
+ },
+ " 720p ",
+ )
+ } else if is_light {
+ (theme.surface2_color(), accent_color, " 720p ")
} else {
- theme.teal.fg.unwrap_or(theme.base)
- },
- " 720p ",
- ),
+ (theme.surface1_color(), accent_color, " 720p ")
+ }
+ }
480 | 540 | 576 => (
theme.surface2_color(),
theme.text.fg.unwrap_or(theme.base),
@@ -150,7 +171,6 @@ pub fn resolution_badge_spans<'a>(
" SD ",
),
};
-
vec![
Span::styled(
label,
diff --git a/src/updater/apply.rs b/src/updater/apply.rs
index 29bfe98..ae73b12 100644
--- a/src/updater/apply.rs
+++ b/src/updater/apply.rs
@@ -15,11 +15,21 @@ pub enum InstallationEnvironment {
DirectReplace,
Homebrew,
Termux,
+ Flatpak,
+ Snap,
ReadOnly,
WindowsHelper,
}
pub fn detect_environment(exe_path: &Path) -> InstallationEnvironment {
+ if std::env::var_os("FLATPAK_ID").is_some() || Path::new("/.flatpak-info").exists() {
+ return InstallationEnvironment::Flatpak;
+ }
+
+ if std::env::var_os("SNAP").is_some() {
+ return InstallationEnvironment::Snap;
+ }
+
if super::artifact::is_termux_environment() {
return InstallationEnvironment::Termux;
}
@@ -27,7 +37,6 @@ pub fn detect_environment(exe_path: &Path) -> InstallationEnvironment {
if is_homebrew_managed(exe_path) {
return InstallationEnvironment::Homebrew;
}
-
if cfg!(windows) {
return InstallationEnvironment::WindowsHelper;
}
@@ -94,6 +103,16 @@ pub fn apply_staged_binary(
"Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
))
}
+ InstallationEnvironment::Flatpak => {
+ Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Running inside Flatpak. Please update via: flatpak update".to_string(),
+ ))
+ }
+ InstallationEnvironment::Snap => {
+ Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Running inside Snap. Please update via: sudo snap refresh moviebox-tui".to_string(),
+ ))
+ }
InstallationEnvironment::ReadOnly => {
Ok(SelfUpdateOutcome::RequiresManualUpgrade(
"MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
diff --git a/src/updater/download.rs b/src/updater/download.rs
index 80e77f7..b2c5644 100644
--- a/src/updater/download.rs
+++ b/src/updater/download.rs
@@ -1,4 +1,3 @@
-use std::io::Write;
use std::path::Path;
use super::check::http_client;
@@ -32,16 +31,37 @@ pub async fn download_file(url: &str, destination: &Path) -> Result<(), String>
return Err(format!("download failed with status {status}"));
}
- let bytes = resp
- .bytes()
+ use futures::StreamExt;
+ use tokio::io::AsyncWriteExt;
+
+ let mut file = tokio::fs::File::create(destination)
.await
- .map_err(|e| format!("failed to read response bytes: {e}"))?;
- let mut file = std::fs::File::create(destination)
.map_err(|e| format!("failed to create temp download file: {e}"))?;
- file.write_all(&bytes)
- .map_err(|e| format!("failed to write download data: {e}"))?;
- file.flush()
- .map_err(|e| format!("failed to flush download file: {e}"))?;
+
+ let mut stream = resp.bytes_stream();
+ let mut write_err = None;
+ while let Some(chunk_res) = stream.next().await {
+ match chunk_res {
+ Ok(chunk) => {
+ if let Err(e) = file.write_all(&chunk).await {
+ write_err = Some(format!("failed to write download data: {e}"));
+ break;
+ }
+ }
+ Err(e) => {
+ write_err = Some(format!("download chunk stream error: {e}"));
+ break;
+ }
+ }
+ }
+ if let Some(err) = write_err {
+ let _ = tokio::fs::remove_file(destination).await;
+ return Err(err);
+ }
+ if let Err(e) = file.flush().await {
+ let _ = tokio::fs::remove_file(destination).await;
+ return Err(format!("failed to flush download file: {e}"));
+ }
return Ok(());
}
Err(e) => {
diff --git a/src/updater/mod.rs b/src/updater/mod.rs
index ecc2020..ddaeeee 100644
--- a/src/updater/mod.rs
+++ b/src/updater/mod.rs
@@ -32,6 +32,17 @@ pub async fn perform_self_update(
"Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
));
}
+ InstallationEnvironment::Flatpak => {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Running inside Flatpak. Please update via: flatpak update".to_string(),
+ ));
+ }
+ InstallationEnvironment::Snap => {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Running inside Snap. Please update via: sudo snap refresh moviebox-tui"
+ .to_string(),
+ ));
+ }
InstallationEnvironment::ReadOnly => {
return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
"MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
@@ -61,11 +72,7 @@ pub async fn perform_self_update(
.map_err(|e| format!("failed to create temporary update directory: {e}"))?;
let archive_path = temp_dir.path().join(&asset.name);
- let staged_binary_path = if env == InstallationEnvironment::WindowsHelper {
- apply::persistent_staging_path(&current_exe)
- } else {
- temp_dir.path().join(platform.expected_binary_name())
- };
+ let staged_binary_path = apply::persistent_staging_path(&current_exe);
if let Some(tx) = progress_sender {
let _ = tx.send(format!("Downloading {}...", asset.name));
diff --git a/tests/settings_hub.rs b/tests/settings_hub.rs
index 99ce275..df368c3 100644
--- a/tests/settings_hub.rs
+++ b/tests/settings_hub.rs
@@ -142,7 +142,7 @@ fn test_settings_player_and_theme_cycling() {
async fn test_settings_keyboard_navigation_and_actions() {
let mut app = App::new();
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
assert_eq!(app.state().settings_category, SettingsCategory::General);
assert_eq!(app.state().settings_selected_row, 0);
@@ -205,7 +205,7 @@ async fn test_settings_modes_toggle_keeps_popup_open() {
app.state_mut()
.set_mode(moviebox_tui::tui::state::AppMode::Streaming);
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
app.handle_action(Action::SelectSettingsCategory(
@@ -244,14 +244,14 @@ async fn test_settings_modes_toggle_keeps_popup_open() {
app.state_mut().streaming_enabled = true;
app.state_mut().tv_enabled = true;
app.state_mut().addons_enabled = true;
- app.handle_action(Action::CloseSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(!app.state().show_settings_popup);
}
#[tokio::test]
async fn test_settings_appearance_theme_cycle_and_popup() {
let mut app = App::new();
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
app.handle_action(Action::SelectSettingsCategory(SettingsCategory::Appearance))
@@ -276,14 +276,14 @@ async fn test_settings_appearance_theme_cycle_and_popup() {
.await;
assert!(app.state().show_settings_popup);
assert!(!app.state().show_theme_popup);
- app.handle_action(Action::CloseSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(!app.state().show_settings_popup);
}
#[tokio::test]
async fn test_settings_mouse_interaction() {
let mut app = App::new();
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
app.handle_action(Action::MouseClick(0, 0)).await;
@@ -293,7 +293,7 @@ async fn test_settings_mouse_interaction() {
#[tokio::test]
async fn test_settings_mouse_tab_and_row_clicks() {
let mut app = App::new();
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
assert_eq!(app.state().settings_category, SettingsCategory::General);
@@ -371,7 +371,7 @@ fn test_expand_download_path() {
#[tokio::test]
async fn test_settings_hub_clear_cache_activation_and_notification() {
let mut app = App::new();
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
assert!(app.state().show_settings_popup);
app.handle_action(Action::SelectSettingsCategory(
@@ -407,7 +407,7 @@ async fn test_settings_hub_clear_cache_activation_and_notification() {
#[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::ToggleSettingsPopup).await;
app.handle_action(Action::SelectSettingsCategory(
SettingsCategory::StorageInfo,
))
@@ -440,7 +440,7 @@ async fn test_settings_hub_clear_watch_history_activation() {
app.state_mut().history.record_start(&item, 120);
assert!(!app.state().history.recent.is_empty());
- app.handle_action(Action::ShowSettingsPopup).await;
+ app.handle_action(Action::ToggleSettingsPopup).await;
app.handle_action(Action::SelectSettingsCategory(
SettingsCategory::StorageInfo,
))