Skip to content

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

feat(updater): harden cross-platform self-update, rate-limit fallback, and input isolation

Samir Hossains98e8d0ef290d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca69482..b7e5322 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,14 @@
## [Unreleased]
+### Added
+- **In-App Self-Update Engine Hardening**:
+ - Added deterministic fallback download URL generation for GitHub release assets and `SHA256SUMS` when unauthenticated API requests encounter HTTP 403 rate limits.
+ - Added active in-flight self-update progress modal (`draw_updating_modal`) featuring animated Braille spinners, version upgrade indicators (`v{old} → v{new}`), and real-time status steps.
+ - Added environment-aware update modal actions: displays Homebrew upgrade instructions (`brew upgrade moviebox-tui`) with `[b]` shortcut on Homebrew installations, Termux installer guidance on Android, and package manager notifications on read-only installations.
+ - Added 5-iteration retry loop with bounded 1-second backoff in the Windows update helper script (`moviebox_update_helper.bat`) to tolerate transient file locks from antivirus or Windows search indexers during binary replacement.
+ - Cached full `Release` metadata in `AppState` and action pipeline, eliminating duplicate network queries between release checking and self-update invocation.
+
### Changed
- **Provider Switching Shortcut**:
- Scoped `Ctrl+P` strictly to Streaming Mode for provider cycling, eliminating redundant `Ctrl+P` handling in TV and Addon modes.
@@ -18,6 +26,9 @@
- Updated macOS Homebrew installation with explicit `brew trust` step required by Homebrew 6.0+ for third-party taps.
- Streamlined quickstart section to reference in-app interactive help (`?`) and `docs/controls.md`, preventing documentation drift.
### Fixed
+- **Update Modal Input Isolation & Event Guards**:
+ - Prevented keystroke hijacking: deferred blocking update modal presentation while the user is actively typing in the search bar (`InputMode::Editing`), ensuring keys (`u`, `o`, `Esc`) never trigger unintended update actions.
+ - Added input lock during in-flight updates (`is_updating`), consuming all keyboard and mouse events to prevent mid-upgrade process termination or disk corruption.
- **Direct Playback & Header Compatibility**:
- Eliminated vestigial in-stream "Open with" popup that blocked playback when only VLC was installed, routing playback directly to the preferred compatible player.
- Prevented silent player overrides: when a user explicitly selects a default player (e.g. VLC) that cannot satisfy stream authentication headers (e.g. MovieBox signed DASH manifests), the app now halts playback and warns the user with actionable detected alternatives instead of silently launching an unselected player.
diff --git a/docs/controls.md b/docs/controls.md
index 291a312..529ab9e 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -119,6 +119,16 @@ Type these commands directly into the search bar:
- `↑`/`↓`, `PageUp`/`PageDown`, and the mouse wheel scroll long content.
- Other keys are ignored while help is open.
+## Update Notification Modal
+
+When a new release is detected:
+
+- `u` / `U`: Download and install update immediately (direct binary replacement platforms).
+- `b` / `B`: View Homebrew upgrade command (`brew upgrade moviebox-tui`) on Homebrew-managed installations.
+- `o` / `O`: Open GitHub release notes in the system browser.
+- `Esc`: Dismiss modal and return to previous screen.
+- Modal presentation is deferred while actively typing in the search bar (`InputMode::Editing`) to prevent input hijacking. During update installation, keyboard and mouse inputs are locked while an in-flight Braille progress modal displays download, verification, and replacement status.
+
## Wide-Terminal Grid
On terminals at least 110 columns wide, search results render in two
diff --git a/docs/cross-platform.md b/docs/cross-platform.md
index 5e88aa3..8c1109b 100644
--- a/docs/cross-platform.md
+++ b/docs/cross-platform.md
@@ -62,6 +62,16 @@ prevent escape sequence probe leakage (`Gi=31...`):
embedded public resolvers (Cloudflare `1.1.1.1`, Google `8.8.8.8`, Quad9 `9.9.9.9`)
when no system configuration exists — as on Android/Termux or minimal containers.
No JNI or `ndk-context` required.
+## In-App Self-Update Engine
+
+MovieBox-TUI embeds an in-app binary upgrade engine (`src/updater/`) with cross-platform environment detection and deterministic fallback:
+
+- **Direct Replacement**: Supported on Linux (`x86_64`, `aarch64`), macOS (Universal binary), and Windows (`x64`, `arm64`). Downloaded release archives are validated against SHA-256 checksums, unpacked to temporary staging files, and swapped atomically with rollback on failure.
+- **Windows Helper Script**: On Windows, because running executables are locked by the OS, an external transient batch helper (`moviebox_update_helper.bat`) waits for the parent process PID to terminate, attempts atomic binary replacement with a 5-iteration retry loop (to tolerate antivirus/SmartScreen file locks), restarts the application, and self-deletes.
+- **Homebrew Managed Environments**: Automatically detected via path markers (`/Cellar/`, `/opt/homebrew/`, `/usr/local/Cellar/`, `/home/linuxbrew/`). In-app binary overwrites are disabled to protect package manager integrity; the update modal displays Homebrew instructions (`brew upgrade moviebox-tui`) with a dedicated `[b]` shortcut.
+- **Android / Termux**: Protects Termux environments from overwriting bionic libc binaries with incompatible Linux glibc binaries. Instructs users to re-run the universal installer script (`curl -fsSL ... | bash`).
+- **Deterministic GitHub Asset Fallback**: When GitHub API requests are unauthenticated or rate-limited (status 403), tag resolution falls back to HTTP redirects, and asset download URLs are computed deterministically from release tags rather than failing update operations.
+- **Input Isolation & Event Locking**: Update notifications defer blocking modal presentation while typing in search mode (`InputMode::Editing`) to prevent keystroke hijacking. During in-flight update execution (`is_updating`), all keyboard and mouse events are locked while displaying an active Braille progress spinner.
## Things to verify per release
diff --git a/src/tui/action.rs b/src/tui/action.rs
index f65d9b3..2a04be5 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -131,7 +131,7 @@ pub enum Action {
),
PosterSuccess(String, std::sync::Arc<image::DynamicImage>),
SearchPosterLoaded(String, Option<std::sync::Arc<image::DynamicImage>>),
- UpdateAvailable(Result<Option<(String, String)>, String>),
+ UpdateAvailable(Result<Option<crate::updater::Release>, String>),
CheckForUpdates,
StartSelfUpdate,
SelfUpdateProgress(String),
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 13d7c7a..3422031 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -9,6 +9,9 @@ impl App {
pub(super) async fn handle_key(&mut self, key: KeyEvent) -> Option<()> {
use crossterm::event::{KeyCode, KeyModifiers};
+ if self.state.is_updating {
+ return None;
+ }
if self.state.show_help {
match key.code {
KeyCode::Up | KeyCode::PageUp => {
@@ -85,26 +88,44 @@ impl App {
return None;
}
- if let Some((version, _)) = &self.state.update_available {
- match key.code {
- KeyCode::Char('u') | KeyCode::Char('U') => {
- self.action_sender.send(Action::StartSelfUpdate).ok();
- return None;
- }
- KeyCode::Char('o') | KeyCode::Char('O') => {
- let url = format!(
- "https://github.com/mesamirh/MovieBox-Tui/releases/tag/v{}",
- version
- );
- let _ = open::that(&url);
- self.state.update_available = None;
- return None;
- }
- KeyCode::Esc => {
- self.state.update_available = None;
- return None;
+ if self.state.input_mode != InputMode::Editing {
+ if let Some((version, _)) = &self.state.update_available {
+ let is_homebrew = std::env::current_exe()
+ .map(|p| crate::updater::apply::is_homebrew_managed(&p))
+ .unwrap_or(false);
+
+ match key.code {
+ KeyCode::Char('u') | KeyCode::Char('U') if !is_homebrew => {
+ self.action_sender.send(Action::StartSelfUpdate).ok();
+ return None;
+ }
+ KeyCode::Char('b') | KeyCode::Char('B') if is_homebrew => {
+ self.state
+ .set_status_short("Run: brew upgrade moviebox-tui");
+ self.state.notify(
+ crate::tui::overlay::NotificationKind::Info,
+ "Homebrew Upgrade",
+ "Run 'brew upgrade moviebox-tui' in your terminal to update.",
+ );
+ self.state.update_available = None;
+ return None;
+ }
+ KeyCode::Char('o') | KeyCode::Char('O') => {
+ let url = format!(
+ "https://github.com/mesamirh/MovieBox-Tui/releases/tag/v{}",
+ version
+ );
+ let _ = open::that(&url);
+ self.state.update_available = None;
+ return None;
+ }
+ KeyCode::Esc => {
+ self.state.update_available = None;
+ return None;
+ }
+ _ => {}
}
- _ => {}
+ return None;
}
}
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 8d6ad5f..cd5e468 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -24,6 +24,10 @@ impl App {
}
fn handle_overlay_mouse(&mut self, col: u16, row: u16, area: Rect) -> bool {
+ if self.state.is_updating {
+ return true;
+ }
+
if !self.state.notifications.is_empty() {
let rects = crate::tui::overlay::notification_rects(
area,
@@ -234,9 +238,23 @@ impl App {
.popup_area
.contains(ratatui::layout::Position::new(col, row))
{
+ let is_homebrew = std::env::current_exe()
+ .map(|p| crate::updater::apply::is_homebrew_managed(&p))
+ .unwrap_or(false);
+
if row == layout.button_row_y {
if col < layout.update_btn_end_x {
- self.action_sender.send(Action::StartSelfUpdate).ok();
+ if is_homebrew {
+ self.state
+ .set_status_short("Run: brew upgrade moviebox-tui");
+ self.state.notify(
+ NotificationKind::Info,
+ "Homebrew Upgrade",
+ "Run 'brew upgrade moviebox-tui' in your terminal to update.",
+ );
+ } else {
+ self.action_sender.send(Action::StartSelfUpdate).ok();
+ }
} else if col < layout.open_btn_end_x {
let url =
format!("https://github.com/mesamirh/MovieBox-Tui/releases/tag/v{ver}");
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index e0916c1..81ef3bc 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -531,7 +531,7 @@ impl App {
self.draw_theme_picker(frame, area);
self.draw_player_picker(frame, area);
self.draw_update_modal(frame, area);
-
+ self.draw_updating_modal(frame, area);
crate::tui::overlay::notifications(
frame,
area,
@@ -745,11 +745,20 @@ impl App {
}
fn draw_update_modal(&self, frame: &mut Frame, area: Rect) {
+ if self.state.input_mode == crate::tui::state::InputMode::Editing {
+ return;
+ }
+
if let Some((version, notes)) = &self.state.update_available {
use ratatui::layout::Alignment;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
+ let env = std::env::current_exe()
+ .ok()
+ .map(|p| crate::updater::apply::detect_environment(&p))
+ .unwrap_or(crate::updater::apply::InstallationEnvironment::DirectReplace);
+
let layout = crate::tui::overlay::update_modal_layout(area, notes);
let popup_area = layout.popup_area;
let display_count = layout.display_count;
@@ -789,15 +798,53 @@ impl App {
),
])
.alignment(Alignment::Center),
- Line::from(""),
- Line::from(vec![Span::styled(
- "Release Notes:",
- self.theme
- .subtext1
- .add_modifier(ratatui::style::Modifier::BOLD),
- )]),
];
+ match env {
+ crate::updater::apply::InstallationEnvironment::Homebrew => {
+ text.push(
+ Line::from(vec![
+ Span::styled("Homebrew Managed • Run: ", self.theme.text_dim),
+ Span::styled(
+ "brew upgrade moviebox-tui",
+ self.theme
+ .accent
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ ),
+ ])
+ .alignment(Alignment::Center),
+ );
+ }
+ crate::updater::apply::InstallationEnvironment::Termux => {
+ text.push(
+ Line::from(vec![Span::styled(
+ "Termux / Android • Re-run installer script to update",
+ self.theme.accent,
+ )])
+ .alignment(Alignment::Center),
+ );
+ }
+ crate::updater::apply::InstallationEnvironment::ReadOnly => {
+ text.push(
+ Line::from(vec![Span::styled(
+ "Binary is not user-writable • Update via your package manager",
+ self.theme.accent,
+ )])
+ .alignment(Alignment::Center),
+ );
+ }
+ crate::updater::apply::InstallationEnvironment::DirectReplace
+ | crate::updater::apply::InstallationEnvironment::WindowsHelper => {}
+ }
+
+ text.push(Line::from(""));
+ text.push(Line::from(vec![Span::styled(
+ "Release Notes:",
+ self.theme
+ .subtext1
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ )]));
+
let line_width = popup_area.width.saturating_sub(6) as usize;
for line in note_lines.iter().take(display_count) {
let trimmed = line.trim();
@@ -857,20 +904,117 @@ impl App {
}
text.push(Line::from(""));
- text.push(
- Line::from(vec![
+
+ let buttons = match env {
+ crate::updater::apply::InstallationEnvironment::Homebrew => vec![
+ Span::styled("[b]", self.theme.shortcut),
+ Span::styled(" Copy 'brew upgrade' ", self.theme.text),
+ Span::styled("[o]", self.theme.shortcut),
+ Span::styled(" Open Release Page ", self.theme.text),
+ Span::styled("[Esc]", self.theme.shortcut),
+ Span::styled(" Dismiss", self.theme.text),
+ ],
+ crate::updater::apply::InstallationEnvironment::Termux
+ | crate::updater::apply::InstallationEnvironment::ReadOnly => vec![
+ Span::styled("[o]", self.theme.shortcut),
+ Span::styled(" Open Release Page ", self.theme.text),
+ Span::styled("[Esc]", self.theme.shortcut),
+ Span::styled(" Dismiss", self.theme.text),
+ ],
+ crate::updater::apply::InstallationEnvironment::DirectReplace
+ | crate::updater::apply::InstallationEnvironment::WindowsHelper => vec![
Span::styled("[u]", self.theme.shortcut),
Span::styled(" Update Now ", self.theme.text),
Span::styled("[o]", self.theme.shortcut),
Span::styled(" Open Release Page ", self.theme.text),
Span::styled("[Esc]", self.theme.shortcut),
Span::styled(" Dismiss", self.theme.text),
- ])
- .alignment(Alignment::Center),
- );
+ ],
+ };
+
+ text.push(Line::from(buttons).alignment(Alignment::Center));
let popup = Paragraph::new(text);
frame.render_widget(popup, inner_area);
}
}
+
+ fn draw_updating_modal(&self, frame: &mut Frame, area: Rect) {
+ if !self.state.is_updating {
+ return;
+ }
+
+ use ratatui::layout::Alignment;
+ use ratatui::text::{Line, Span};
+ use ratatui::widgets::Paragraph;
+
+ let width = 56.min(area.width.saturating_sub(4)).max(36);
+ let height = 8.min(area.height.saturating_sub(2)).max(6);
+ let popup_area = crate::tui::overlay::centered(area, width, height, 36, 56);
+
+ let inner_area = crate::tui::widgets::ModalFrame::new(
+ "Self-Update in Progress",
+ &self.theme,
+ self.state.basic_terminal,
+ )
+ .render(frame, popup_area, area);
+
+ let spinner = crate::tui::screens::details::stream_loading_spinner(
+ self.state.tick_count,
+ self.state.basic_terminal,
+ );
+
+ let target_version = self
+ .state
+ .update_release
+ .as_ref()
+ .map(|r| r.version.as_str())
+ .unwrap_or("latest");
+
+ let progress_msg = self
+ .state
+ .update_progress_msg
+ .as_deref()
+ .unwrap_or("Applying update...");
+
+ let text = vec![
+ Line::from(vec![
+ Span::styled(
+ format!("{spinner} "),
+ self.theme
+ .accent
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ ),
+ Span::styled(
+ "Upgrading MovieBox-Tui ",
+ self.theme
+ .header
+ .add_modifier(ratatui::style::Modifier::BOLD),
+ ),
+ Span::styled(
+ format!("v{} → v{}", env!("CARGO_PKG_VERSION"), target_version),
+ self.theme.highlight,
+ ),
+ ])
+ .alignment(Alignment::Center),
+ Line::from(""),
+ Line::from(vec![Span::styled(
+ crate::tui::text::truncate_width(
+ progress_msg,
+ inner_area.width.saturating_sub(2) as usize,
+ ),
+ self.theme.text,
+ )])
+ .alignment(Alignment::Center),
+ Line::from(""),
+ Line::from(vec![Span::styled(
+ "Please wait, do not close the terminal...",
+ self.theme.text_dim,
+ )])
+ .alignment(Alignment::Center),
+ ];
+
+ let popup = Paragraph::new(text);
+ frame.render_widget(popup, inner_area);
+ }
}
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 0fba097..8968e25 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -691,7 +691,8 @@ 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(env!("CARGO_PKG_VERSION")));
+ let task =
+ tokio::spawn(crate::updater::check_release(env!("CARGO_PKG_VERSION")));
let result = match task.await {
Ok(res) => res,
Err(join_err) => Err(format!("update check task error: {join_err}")),
@@ -735,10 +736,28 @@ impl App {
}
self.state.manual_update_check = false;
}
- Ok(Some((version, notes))) => {
+ Ok(Some(release)) => {
self.state.manual_update_check = false;
- self.reset_transient_overlays();
- self.state.update_available = Some((version, notes));
+ let version = release.version.clone();
+ let notes = release.notes.clone();
+ self.state.update_release = Some(release);
+ if self.state.input_mode == crate::tui::state::InputMode::Editing {
+ self.state.update_available = Some((version.clone(), notes));
+ self.state.notify(
+ NotificationKind::Info,
+ "Update Available",
+ format!(
+ "MovieBox-Tui v{version} is available. Exit search to view."
+ ),
+ );
+ } else if self.state.is_playing || self.state.download_progress.is_some() {
+ self.state.update_available = Some((version.clone(), notes));
+ self.state
+ .set_status_short(format!("Update v{version} available."));
+ } else {
+ self.reset_transient_overlays();
+ self.state.update_available = Some((version, notes));
+ }
}
}
}
@@ -766,6 +785,7 @@ impl App {
self.state.is_updating = true;
self.state.update_available = None;
+ self.state.update_progress_msg = Some("Starting self-update...".to_string());
self.state.set_status_long("Starting self-update...");
self.state.notify(
NotificationKind::Info,
@@ -773,24 +793,29 @@ impl App {
"Downloading release artifact and verifying checksum...",
);
+ let cached_release = self.state.update_release.clone();
let update_sender = self.action_sender.clone();
tokio::spawn(async move {
- let release =
- match crate::updater::check_release(env!("CARGO_PKG_VERSION")).await {
- Ok(Some(r)) => r,
- Ok(None) => {
- update_sender
- .send(Action::SelfUpdateComplete(Err(
- "Already on the latest version.".to_string(),
- )))
- .ok();
- return;
- }
- Err(e) => {
- update_sender.send(Action::SelfUpdateComplete(Err(e))).ok();
- return;
+ let release = match cached_release {
+ Some(r) => r,
+ None => {
+ match crate::updater::check_release(env!("CARGO_PKG_VERSION")).await {
+ Ok(Some(r)) => r,
+ Ok(None) => {
+ update_sender
+ .send(Action::SelfUpdateComplete(Err(
+ "Already on the latest version.".to_string(),
+ )))
+ .ok();
+ return;
+ }
+ Err(e) => {
+ update_sender.send(Action::SelfUpdateComplete(Err(e))).ok();
+ return;
+ }
}
- };
+ }
+ };
let (progress_tx, mut progress_rx) =
tokio::sync::mpsc::unbounded_channel::<String>();
@@ -808,11 +833,13 @@ impl App {
}
Action::SelfUpdateProgress(msg) => {
+ self.state.update_progress_msg = Some(msg.clone());
self.state.set_status_long(msg);
}
Action::SelfUpdateComplete(result) => {
self.state.is_updating = false;
+ self.state.update_progress_msg = None;
match result {
Ok(crate::updater::SelfUpdateOutcome::Success) => {
self.state
diff --git a/src/tui/state.rs b/src/tui/state.rs
index d261049..55dc8ac 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -318,7 +318,7 @@ pub struct AppState {
pub is_checking_updates: bool,
pub is_updating: bool,
pub update_release: Option<crate::updater::Release>,
-
+ pub update_progress_msg: Option<String>,
pub download_progress: Option<f64>,
pub download_status: Option<String>,
pub cancel_download: std::sync::Arc<std::sync::atomic::AtomicBool>,
@@ -478,7 +478,7 @@ impl Default for AppState {
is_checking_updates: false,
is_updating: false,
update_release: None,
-
+ update_progress_msg: None,
download_progress: None,
download_status: None,
cancel_download: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
@@ -728,7 +728,8 @@ impl AppState {
|| self.is_download_subtitle_popup
|| self.show_season_download_confirm
|| self.show_episode_download_confirm
- || self.update_available.is_some()
+ || (self.update_available.is_some() && self.input_mode != InputMode::Editing)
+ || self.is_updating
|| (self.input_mode == InputMode::Editing && !self.search_suggestions.is_empty())
}
@@ -1250,6 +1251,9 @@ mod tests {
state.update_available = Some(("v2.0.0".to_string(), "Notes".to_string()));
assert!(state.has_active_modal());
+ state.input_mode = InputMode::Editing;
+ assert!(!state.has_active_modal());
+ state.input_mode = InputMode::Normal;
state.update_available = None;
state.input_mode = InputMode::Editing;
diff --git a/src/updater/apply.rs b/src/updater/apply.rs
index 967b491..388d5b3 100644
--- a/src/updater/apply.rs
+++ b/src/updater/apply.rs
@@ -14,11 +14,16 @@ pub enum SelfUpdateOutcome {
pub enum InstallationEnvironment {
DirectReplace,
Homebrew,
+ Termux,
ReadOnly,
WindowsHelper,
}
pub fn detect_environment(exe_path: &Path) -> InstallationEnvironment {
+ if super::artifact::is_termux_environment() {
+ return InstallationEnvironment::Termux;
+ }
+
if is_homebrew_managed(exe_path) {
return InstallationEnvironment::Homebrew;
}
@@ -84,6 +89,11 @@ pub fn apply_staged_binary(
"This installation is managed by Homebrew. Run: brew upgrade moviebox-tui".to_string(),
))
}
+ InstallationEnvironment::Termux => {
+ Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
+ ))
+ }
InstallationEnvironment::ReadOnly => {
Ok(SelfUpdateOutcome::RequiresManualUpgrade(
"MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
@@ -183,11 +193,20 @@ fn render_helper_script(staged_path: &Path, current_exe: &Path, pid: u32) -> Str
" timeout /t 1 /nobreak >NUL".to_string(),
" goto wait_loop".to_string(),
")".to_string(),
+ "set /a attempts=0".to_string(),
+ ":move_loop".to_string(),
format!(
- "move /y \"{}\" \"{}\"",
+ "move /y \"{}\" \"{}\" >NUL 2>&1",
staged_path.to_string_lossy(),
current_exe.to_string_lossy()
),
+ "if %ERRORLEVEL% NEQ 0 (".to_string(),
+ " set /a attempts+=1".to_string(),
+ " if %attempts% LSS 5 (".to_string(),
+ " timeout /t 1 /nobreak >NUL".to_string(),
+ " goto move_loop".to_string(),
+ " )".to_string(),
+ ")".to_string(),
format!(
"if exist \"{}\" del /f /q \"{}\"",
staged_path.to_string_lossy(),
@@ -274,8 +293,10 @@ mod tests {
"tasklist /FI \"PID eq 4242\" 2>NUL | %SystemRoot%\\System32\\find.exe \"4242\" >NUL"
));
assert!(script.contains(
- "move /y \"C:\\App\\update dir\\.moviebox_update_staged.exe\" \"C:\\App\\moviebox-tui.exe\""
+ "move /y \"C:\\App\\update dir\\.moviebox_update_staged.exe\" \"C:\\App\\moviebox-tui.exe\" >NUL 2>&1"
));
+ assert!(script.contains(":move_loop"));
+ assert!(script.contains("if %attempts% LSS 5 ("));
assert!(script.contains(
"if exist \"C:\\App\\update dir\\.moviebox_update_staged.exe\" del /f /q \"C:\\App\\update dir\\.moviebox_update_staged.exe\""
));
diff --git a/src/updater/artifact.rs b/src/updater/artifact.rs
index 776b86f..9df2d47 100644
--- a/src/updater/artifact.rs
+++ b/src/updater/artifact.rs
@@ -78,13 +78,39 @@ pub fn is_termux_environment() -> bool {
}
impl Release {
- pub fn find_compatible_asset(&self, platform: TargetPlatform) -> Option<&ReleaseAsset> {
+ pub fn find_compatible_asset(&self, platform: TargetPlatform) -> Option<ReleaseAsset> {
let expected = platform.expected_asset_name();
- self.assets.iter().find(|a| a.name == expected)
+ if let Some(asset) = self.assets.iter().find(|a| a.name == expected) {
+ return Some(asset.clone());
+ }
+ if self.assets.is_empty() && !self.tag_name.is_empty() {
+ return Some(ReleaseAsset {
+ name: expected.to_string(),
+ download_url: format!(
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/{}/{expected}",
+ self.tag_name
+ ),
+ size: None,
+ });
+ }
+ None
}
- pub fn find_checksum_asset(&self) -> Option<&ReleaseAsset> {
- self.assets.iter().find(|a| a.name == "SHA256SUMS")
+ pub fn find_checksum_asset(&self) -> Option<ReleaseAsset> {
+ if let Some(asset) = self.assets.iter().find(|a| a.name == "SHA256SUMS") {
+ return Some(asset.clone());
+ }
+ if self.assets.is_empty() && !self.tag_name.is_empty() {
+ return Some(ReleaseAsset {
+ name: "SHA256SUMS".to_string(),
+ download_url: format!(
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/{}/SHA256SUMS",
+ self.tag_name
+ ),
+ size: None,
+ });
+ }
+ None
}
pub fn is_compatible_with_current_platform(&self) -> bool {
@@ -93,3 +119,61 @@ impl Release {
.is_some()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_synthetic_asset_url_generation_on_empty_assets() {
+ let empty_assets_release = Release {
+ version: "0.1.16".to_string(),
+ tag_name: "v0.1.16".to_string(),
+ notes: "Fallback tag release".to_string(),
+ assets: Vec::new(),
+ };
+
+ let linux_asset = empty_assets_release
+ .find_compatible_asset(TargetPlatform::LinuxX64)
+ .expect("should generate synthetic asset");
+ assert_eq!(linux_asset.name, "MovieBox_Linux_x64.tar.gz");
+ assert_eq!(
+ linux_asset.download_url,
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/v0.1.16/MovieBox_Linux_x64.tar.gz"
+ );
+
+ let mac_asset = empty_assets_release
+ .find_compatible_asset(TargetPlatform::MacosUniversal)
+ .expect("should generate synthetic asset");
+ assert_eq!(mac_asset.name, "MovieBox_macOS_Universal.tar.gz");
+ assert_eq!(
+ mac_asset.download_url,
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/v0.1.16/MovieBox_macOS_Universal.tar.gz"
+ );
+
+ let checksum = empty_assets_release
+ .find_checksum_asset()
+ .expect("should generate synthetic checksum");
+ assert_eq!(checksum.name, "SHA256SUMS");
+ assert_eq!(
+ checksum.download_url,
+ "https://github.com/mesamirh/MovieBox-Tui/releases/download/v0.1.16/SHA256SUMS"
+ );
+ }
+
+ #[test]
+ fn test_empty_tag_does_not_generate_synthetic_assets() {
+ let untagged = Release {
+ version: "0.1.16".to_string(),
+ tag_name: String::new(),
+ notes: String::new(),
+ assets: Vec::new(),
+ };
+ assert!(
+ untagged
+ .find_compatible_asset(TargetPlatform::LinuxX64)
+ .is_none()
+ );
+ assert!(untagged.find_checksum_asset().is_none());
+ }
+}
diff --git a/src/updater/mod.rs b/src/updater/mod.rs
index 66ec87d..ecc2020 100644
--- a/src/updater/mod.rs
+++ b/src/updater/mod.rs
@@ -16,6 +16,30 @@ pub async fn perform_self_update(
release: &Release,
progress_sender: Option<&tokio::sync::mpsc::UnboundedSender<String>>,
) -> Result<SelfUpdateOutcome, String> {
+ let current_exe = std::env::current_exe()
+ .map_err(|e| format!("failed to get current executable path: {e}"))?;
+
+ let env = detect_environment(&current_exe);
+ match env {
+ InstallationEnvironment::Homebrew => {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui"
+ .to_string(),
+ ));
+ }
+ InstallationEnvironment::Termux => {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
+ ));
+ }
+ InstallationEnvironment::ReadOnly => {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
+ ));
+ }
+ InstallationEnvironment::DirectReplace | InstallationEnvironment::WindowsHelper => {}
+ }
+
let platform = TargetPlatform::current().ok_or_else(|| {
"current operating system or architecture is not supported for in-app self-update"
.to_string()
@@ -31,22 +55,6 @@ pub async fn perform_self_update(
let checksum_asset = release
.find_checksum_asset()
.ok_or_else(|| "no SHA256SUMS checksum file found in GitHub release".to_string())?;
-
- let current_exe = std::env::current_exe()
- .map_err(|e| format!("failed to get current executable path: {e}"))?;
-
- let env = detect_environment(&current_exe);
- if env == InstallationEnvironment::Homebrew {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui".to_string(),
- ));
- }
- if env == InstallationEnvironment::ReadOnly {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
- ));
- }
-
let temp_dir = tempfile::Builder::new()
.prefix("moviebox_update_")
.tempdir()
diff --git a/tests/update_lifecycle.rs b/tests/update_lifecycle.rs
index 33f7b5d..d87e9e8 100644
--- a/tests/update_lifecycle.rs
+++ b/tests/update_lifecycle.rs
@@ -46,10 +46,12 @@ async fn test_update_check_guard_clears_on_success() {
app.handle_action(Action::CheckForUpdates).await;
assert!(app.state().is_checking_updates);
- app.handle_action(Action::UpdateAvailable(Ok(Some((
- "0.1.13".to_string(),
- "Release notes content".to_string(),
- )))))
+ app.handle_action(Action::UpdateAvailable(Ok(Some(Release {
+ version: "0.1.13".to_string(),
+ tag_name: "v0.1.13".to_string(),
+ notes: "Release notes content".to_string(),
+ assets: Vec::new(),
+ }))))
.await;
assert!(!app.state().is_checking_updates);
@@ -462,3 +464,47 @@ fn test_update_asset_rejects_wrong_platform() {
assert!(TargetPlatform::detect("solaris", "x86_64", false).is_none());
assert!(TargetPlatform::detect("netbsd", "x86_64", false).is_none());
}
+
+#[tokio::test]
+async fn test_update_editing_mode_input_isolation() {
+ let mut app = App::new();
+ app.state_mut().update_available =
+ Some(("0.1.16".to_string(), "New release notes".to_string()));
+ app.state_mut().input_mode = moviebox_tui::tui::state::InputMode::Editing;
+
+ let u_key = crossterm::event::KeyEvent::new(
+ crossterm::event::KeyCode::Char('u'),
+ crossterm::event::KeyModifiers::empty(),
+ );
+ app.handle_action(Action::Key(u_key)).await;
+ assert!(app.state().update_available.is_some());
+ assert!(!app.state().is_updating);
+ assert_eq!(app.state().search_query.as_str(), "u");
+}
+
+#[tokio::test]
+async fn test_update_is_updating_blocks_keys_and_mouse() {
+ let mut app = App::new();
+ app.state_mut().is_updating = true;
+ let q_key = crossterm::event::KeyEvent::new(
+ crossterm::event::KeyCode::Char('q'),
+ crossterm::event::KeyModifiers::empty(),
+ );
+ app.handle_action(Action::Key(q_key)).await;
+ app.handle_action(Action::MouseClick(10, 10)).await;
+ assert!(app.state().is_updating);
+}
+
+#[tokio::test]
+async fn test_update_progress_message_tracking() {
+ let mut app = App::new();
+ app.handle_action(Action::SelfUpdateProgress(
+ "Downloading binary...".to_string(),
+ ))
+ .await;
+
+ assert_eq!(
+ app.state().update_progress_msg.as_deref(),
+ Some("Downloading binary...")
+ );
+}