Skip to content

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

feat: add update notifications, tab navigation, and image caching to TUI

Samir Hossains309e76de184e
diff --git a/Cargo.toml b/Cargo.toml
index 163c12c..c6354f9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "moviebox-tui"
-version = "0.1.1"
+version = "0.1.2"
edition = "2024"
description = "A terminal user interface (TUI) client for MovieBox API."
repository = "https://github.com/mesamirh/MovieBox-Tui"
@@ -12,10 +12,13 @@ readme = "README.md"
rust-version = "1.85.0"
[dependencies]
+arboard = "3.6.1"
base64 = "0.22.1"
crossterm = "0.29.0"
+dirs = "6.0.0"
hmac = "0.13.0"
image = "0.25.10"
+lru = "0.18.1"
md-5 = "0.11.0"
rand = "0.10.2"
ratatui = "0.30.2"
@@ -25,6 +28,7 @@ serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.150"
thiserror = "2.0.18"
tokio = { version = "1.52.3", features = ["full"] }
+update-informer = "1.3.0"
url = "2.5.8"
[lib]
diff --git a/src/tui/action.rs b/src/tui/action.rs
index daedd7c..ad48a08 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -17,6 +17,7 @@ pub enum Action {
MoveLeft,
MoveRight,
Submit,
+ TabPane,
FetchPreview(String),
PreviewSuccess(String, serde_json::Value),
PreviewFailure(String),
@@ -40,4 +41,5 @@ pub enum Action {
ResourcesFailure(String),
PosterSuccess(String, std::sync::Arc<image::DynamicImage>),
Log(String),
+ UpdateAvailable(String),
}
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 4f7ccc1..fff23fd 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -9,6 +9,7 @@ use crate::tui::{
theme::Theme,
};
use crate::v3::client::MovieBoxClient;
+use update_informer::Check;
pub struct App {
state: AppState,
@@ -99,6 +100,16 @@ impl App {
}
});
+ let update_sender = self.action_sender.clone();
+ tokio::task::spawn_blocking(move || {
+ let pkg_name = env!("CARGO_PKG_NAME");
+ let current_version = env!("CARGO_PKG_VERSION");
+ let informer = update_informer::new(update_informer::registry::Crates, pkg_name, current_version);
+ if let Ok(Some(version)) = informer.check_version() {
+ update_sender.send(Action::UpdateAvailable(version.to_string())).ok();
+ }
+ });
+
loop {
terminal.draw(|frame| self.draw(frame))?;
@@ -171,6 +182,11 @@ impl App {
return Some(());
}
+ if key.code == KeyCode::F(1) {
+ self.action_sender.send(Action::ToggleHelp).ok();
+ return Some(());
+ }
+
match self.state.input_mode {
InputMode::Editing => match key.code {
KeyCode::Esc => {
@@ -235,9 +251,6 @@ impl App {
KeyCode::Char('q') => {
self.action_sender.send(Action::Quit).ok();
}
- KeyCode::Char('/') => {
- self.state.input_mode = InputMode::Editing;
- }
KeyCode::Char(c)
if (key.modifiers.is_empty()
|| key.modifiers == KeyModifiers::SHIFT) =>
@@ -267,6 +280,9 @@ impl App {
KeyCode::Char('b') | KeyCode::Esc => {
self.action_sender.send(Action::GoBack).ok();
}
+ KeyCode::Tab => {
+ self.action_sender.send(Action::TabPane).ok();
+ }
KeyCode::Up | KeyCode::Char('k') => {
self.action_sender.send(Action::MoveUp).ok();
}
@@ -366,8 +382,6 @@ impl App {
self.state.search_query.clear();
self.state.search_preview = None;
self.state.status_message = "Search cleared.".to_string(); self.state.status_timer = 150;
- } else {
- self.action_sender.send(Action::Quit).ok();
}
}
Screen::Search => {
@@ -623,6 +637,33 @@ impl App {
_ => {}
}
}
+ Action::TabPane => {
+ if self.state.active_screen == Screen::Details {
+ use crate::tui::state::DetailsPane;
+ let has_languages = self.state.selected_details.as_ref()
+ .and_then(|d| d.get("dubs"))
+ .and_then(|d| d.as_array())
+ .is_some_and(|a| a.len() > 1);
+
+ let is_series = self.state.selected_details.as_ref()
+ .and_then(|d| d.get("stype").or_else(|| d.get("subjectType")))
+ .and_then(|t| t.as_i64())
+ .is_some_and(|t| t == 2);
+
+ self.state.details_pane = match self.state.details_pane {
+ DetailsPane::Languages => {
+ if is_series { DetailsPane::Seasons } else { DetailsPane::Streams }
+ }
+ DetailsPane::Seasons => DetailsPane::Episodes,
+ DetailsPane::Episodes => DetailsPane::Streams,
+ DetailsPane::Streams => {
+ if has_languages { DetailsPane::Languages }
+ else if is_series { DetailsPane::Seasons }
+ else { DetailsPane::Streams }
+ }
+ };
+ }
+ }
Action::MoveDown => {
if self.state.subtitle_popup {
let current = self.state.subtitle_list_state.selected().unwrap_or(0);
@@ -827,12 +868,15 @@ impl App {
});
}
Action::PreviewSuccess(id, json) => {
- let current_id = self
- .state
- .search_list_state
- .selected()
- .and_then(|idx| self.state.search_results.get(idx))
- .map(|res| res.id.clone());
+ let current_id = if self.state.active_screen == Screen::Details {
+ self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_str()).map(|s| s.to_string())
+ } else {
+ self.state
+ .search_list_state
+ .selected()
+ .and_then(|idx| self.state.search_results.get(idx))
+ .map(|res| res.id.clone())
+ };
if current_id.as_deref() != Some(id.as_str()) {
return None;
@@ -842,14 +886,17 @@ impl App {
self.state.search_preview = Some(json.clone());
self.state.poster_image = None;
self.state.poster_protocol = None;
- if let Some(cover_val) = json.get("cover")
+ if let Some(cached_img) = self.state.image_cache.get(&id) {
+ self.state.poster_image = Some((**cached_img).clone());
+ } else if let Some(cover_val) = json.get("cover")
&& let Some(url) = cover_val.get("url").and_then(|u| u.as_str())
{
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
tokio::spawn(async move {
- if let Ok(resp) = reqwest::get(&url_clone).await
+ let client = reqwest::Client::new();
+ if let Ok(resp) = client.get(&url_clone).header("User-Agent", "MovieBox-Tui/1.0").send().await
&& let Ok(bytes) = resp.bytes().await
&& let Ok(img) = image::load_from_memory(&bytes)
{
@@ -860,12 +907,17 @@ impl App {
}
}
Action::PosterSuccess(id, img) => {
- let current_id = self
- .state
- .search_list_state
- .selected()
- .and_then(|idx| self.state.search_results.get(idx))
- .map(|res| res.id.clone());
+ self.state.image_cache.put(id.clone(), img.clone());
+
+ let current_id = if self.state.active_screen == Screen::Details {
+ self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_str()).map(|s| s.to_string())
+ } else {
+ self.state
+ .search_list_state
+ .selected()
+ .and_then(|idx| self.state.search_results.get(idx))
+ .map(|res| res.id.clone())
+ };
if current_id.as_deref() == Some(id.as_str()) {
self.state.poster_image = Some((*img).clone());
@@ -881,18 +933,12 @@ impl App {
if self.state.active_screen == Screen::Details
&& let Some(link) = self.get_selected_link()
{
- use std::io::Write;
- use std::process::{Command, Stdio};
- let child = Command::new("pbcopy").stdin(Stdio::piped()).spawn();
- if let Ok(mut child) = child {
- if let Some(mut stdin) = child.stdin.take() {
- let _ = stdin.write_all(link.as_bytes());
- }
- let _ = child.wait();
+ if let Ok(mut clipboard) = arboard::Clipboard::new() {
+ let _ = clipboard.set_text(link.clone());
self.state.toast_message = Some("[ ✓ ] Copied stream link!".to_string());
self.state.toast_timer = 30;
self.state.add_log(
- "Stream link successfully copied to macOS clipboard.".to_string(),
+ "Stream link successfully copied to clipboard.".to_string(),
);
} else {
self.state.status_message = format!("Link: {}", link); self.state.status_timer = 150;
@@ -966,7 +1012,7 @@ impl App {
if cmd.spawn().is_ok() {
self.state.add_log("MPV started successfully.".to_string());
} else {
- self.state.toast_message = Some("[ ✗ ] Failed to launch MPV!".to_string());
+ self.state.toast_message = Some("[ ! ] Error: mpv player not found in PATH".to_string());
self.state.toast_timer = 60;
self.state.add_log("Error starting mpv process. Command failed.".to_string());
}
@@ -993,9 +1039,8 @@ impl App {
ext
);
- let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
- let filepath = std::path::PathBuf::from(home)
- .join("Downloads")
+ let filepath = dirs::download_dir()
+ .unwrap_or_else(|| std::path::PathBuf::from("."))
.join(&filename);
if let Some(link) = link_opt {
@@ -1415,11 +1460,29 @@ impl App {
}
}
Action::DetailsSuccess(id, payload) => {
- let _ = std::fs::write(
- "debug_details.json",
- serde_json::to_string_pretty(&payload).unwrap(),
- );
self.state.selected_details = Some(payload.clone());
+
+ if self.state.poster_image.is_none() {
+ if let Some(cached_img) = self.state.image_cache.get(&id) {
+ self.state.poster_image = Some((**cached_img).clone());
+ } else if let Some(cover_val) = payload.get("cover")
+ && let Some(url) = cover_val.get("url").and_then(|u| u.as_str())
+ {
+ let url_clone = url.to_string();
+ let action_tx = self.action_sender.clone();
+ let id_clone = id.clone();
+ tokio::spawn(async move {
+ let client = reqwest::Client::new();
+ if let Ok(resp) = client.get(&url_clone).header("User-Agent", "MovieBox-Tui/1.0").send().await
+ && let Ok(bytes) = resp.bytes().await
+ && let Ok(img) = image::load_from_memory(&bytes)
+ {
+ let _ = action_tx.send(Action::PosterSuccess(id_clone, std::sync::Arc::new(img)));
+ }
+ });
+ }
+ }
+
let stype = payload
.get("subjectType")
.and_then(|s| s.as_i64())
@@ -1574,6 +1637,9 @@ impl App {
Action::Log(msg) => {
self.state.add_log(msg);
}
+ Action::UpdateAvailable(version) => {
+ self.state.update_available = Some(version);
+ }
}
None
}
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index ce0e85e..763d823 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -259,19 +259,41 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.split(bottom_area)
} else {
let mut c = Vec::new();
- if has_languages {
- c.push(Constraint::Length(18));
- }
- if is_series {
- c.push(Constraint::Length(15));
- c.push(Constraint::Length(15));
+ if has_languages || is_series {
+ c.push(Constraint::Length(22)); // Left side panel
}
- c.push(Constraint::Min(1));
+ c.push(Constraint::Min(1)); // Streams panel
Layout::default()
.direction(Direction::Horizontal)
.constraints(c)
.split(bottom_area)
};
+
+ let mut left_panel_chunks: std::rc::Rc<[ratatui::layout::Rect]> = std::rc::Rc::new([]);
+ if (!has_languages || state.language_chosen) && (has_languages || is_series) {
+ let mut v_constraints = Vec::new();
+ if has_languages {
+ let mut h = 3;
+ if let Some(dubs) = details_json.get("dubs").and_then(|d| d.as_array()) {
+ h = (dubs.len() as u16) + 2;
+ }
+ v_constraints.push(Constraint::Max(h));
+ }
+ if is_series {
+ let seasons_count = state.available_seasons.len() as u16;
+ let mut eps_count = 1;
+ if let Some(season) = state.available_seasons.get(state.season_list_state.selected().unwrap_or(0)) {
+ eps_count = season.get("maxEp").and_then(|m| m.as_i64()).unwrap_or(1) as u16;
+ }
+ v_constraints.push(Constraint::Max(seasons_count + 2));
+ v_constraints.push(Constraint::Max(eps_count + 2));
+ }
+ v_constraints.push(Constraint::Min(0));
+ left_panel_chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints(v_constraints)
+ .split(bottom_chunks[0]);
+ }
if has_languages {
use ratatui::widgets::{List, ListItem};
@@ -323,14 +345,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.split(bottom_chunks[1]);
v_split[1]
} else {
- let v_split = Layout::default()
- .direction(Direction::Vertical)
- .constraints([
- Constraint::Length(list_height),
- Constraint::Min(0),
- ])
- .split(bottom_chunks[0]);
- v_split[0]
+ left_panel_chunks[0]
};
frame.render_stateful_widget(lang_list, lang_area, &mut state.language_list_state);
}
@@ -365,9 +380,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.highlight_symbol(">> ");
let seasons_area = if has_languages {
- bottom_chunks[1]
+ left_panel_chunks[1]
} else {
- bottom_chunks[0]
+ left_panel_chunks[0]
};
frame.render_stateful_widget(seasons_list, seasons_area, &mut state.season_list_state);
@@ -400,25 +415,17 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.highlight_symbol(">> ");
let eps_area = if has_languages {
- bottom_chunks[2]
+ left_panel_chunks[2]
} else {
- bottom_chunks[1]
+ left_panel_chunks[1]
};
frame.render_stateful_widget(eps_list, eps_area, &mut state.episode_list_state);
}
- let streams_area = if is_series {
- if has_languages {
- bottom_chunks[3]
- } else {
- bottom_chunks[2]
- }
+ let streams_area = if has_languages || is_series {
+ bottom_chunks[1]
} else {
- if has_languages {
- bottom_chunks[1]
- } else {
- bottom_chunks[0]
- }
+ bottom_chunks[0]
};
let streams_border = if state.details_pane == crate::tui::state::DetailsPane::Streams {
theme.border_focus
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index aad7ab5..028ab00 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -171,10 +171,17 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
frame.render_widget(search_bar, search_bar_area);
- let legend = Paragraph::new("/ Search ↑↓ Browse ? Help")
+ let legend = Paragraph::new("Type to Search ↑↓ Browse F1/? Help")
.alignment(Alignment::Center)
.style(theme.text_dim);
frame.render_widget(legend, vertical_chunks[6]);
+
+ if let Some(version_str) = &state.update_available {
+ let update_text = Paragraph::new(format!("Update v{} available! Run: cargo install moviebox-tui", version_str))
+ .alignment(Alignment::Center)
+ .style(theme.highlight);
+ frame.render_widget(update_text, vertical_chunks[7]);
+ }
}
} else {
let desired_height = if state.is_loading {
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 9844b5f..b377272 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -60,6 +60,7 @@ pub struct AppState {
pub poster_image: Option<image::DynamicImage>,
pub poster_protocol: Option<(ratatui::layout::Rect, ratatui_image::protocol::Protocol)>,
pub image_picker: Option<ratatui_image::picker::Picker>,
+ pub image_cache: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,
pub show_logs: bool,
pub show_help: bool,
@@ -70,9 +71,9 @@ pub struct AppState {
pub is_loading: bool,
pub status_message: String,
pub status_timer: usize,
-
pub toast_message: Option<String>,
pub toast_timer: usize,
+ pub update_available: Option<String>,
pub download_progress: Option<f64>,
pub download_status: Option<String>,
@@ -118,6 +119,7 @@ impl Default for AppState {
poster_image: None,
poster_protocol: None,
image_picker: None,
+ image_cache: lru::LruCache::new(std::num::NonZeroUsize::new(10).unwrap()),
show_logs: false,
show_help: false,
logs: vec!["MovieBox-Tui started.".to_string()],
@@ -128,6 +130,7 @@ impl Default for AppState {
status_timer: 0,
toast_message: None,
toast_timer: 0,
+ update_available: None,
download_progress: None,
download_status: None,
cancel_download: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
diff --git a/src/v3/client.rs b/src/v3/client.rs
index a32512a..8d084fc 100644
--- a/src/v3/client.rs
+++ b/src/v3/client.rs
@@ -66,17 +66,6 @@ impl MovieBoxClient {
}
}
- pub fn user_agent(&self) -> &str {
- &self.user_agent
- }
-
- pub fn client_info(&self) -> &str {
- &self.client_info
- }
-
- pub fn spoofed_ip(&self) -> &str {
- &self.spoofed_ip
- }
pub async fn init(&self) -> Result<(), ScraperError> {
let path = "/wefeed-mobile-bff/tab-operating?page=1&tabId=0&version=";
@@ -163,11 +152,12 @@ impl MovieBoxClient {
let mut active_idx = self.active_base_idx.write().await;
*active_idx = idx;
- return self.parse_response(resp).await;
- }
- Err(_) => {
- continue;
+ match self.parse_response(resp).await {
+ Ok(val) => return Ok(val),
+ Err(_) => continue,
+ }
}
+ Err(_) => continue,
}
}
@@ -180,7 +170,17 @@ impl MovieBoxClient {
return Err(ScraperError::ApiStatus(status.as_u16()));
}
- let body_val: Value = resp.json().await?;
+ let raw_text = match resp.text().await {
+ Ok(t) => t,
+ Err(e) => return Err(ScraperError::Reqwest(e)),
+ };
+
+ let body_val: Value = match serde_json::from_str(&raw_text) {
+ Ok(v) => v,
+ Err(e) => {
+ return Err(ScraperError::Json(e));
+ }
+ };
if let Some(data) = body_val.get("data") {
Ok(data.clone())
diff --git a/src/v3/mod.rs b/src/v3/mod.rs
index 24b0479..9ae6201 100644
--- a/src/v3/mod.rs
+++ b/src/v3/mod.rs
@@ -5,22 +5,10 @@ use client::{ScraperError, MovieBoxClient};
use serde_json::{Value, json};
impl MovieBoxClient {
- pub async fn get_homepage(&self, page: usize) -> Result<Value, ScraperError> {
- let path = format!(
- "/wefeed-mobile-bff/tab-operating?page={}&tabId=0&version=",
- page
- );
- self.get(&path).await
- }
-
pub async fn search(&self, query: &str, page: usize) -> Result<Value, ScraperError> {
self.search_with_tab(query, page, "All").await
}
- pub async fn search_movies(&self, query: &str, page: usize) -> Result<Value, ScraperError> {
- self.search_with_tab(query, page, "MovieTV").await
- }
-
pub async fn suggest(&self, query: &str) -> Result<Value, ScraperError> {
let payload = json!({
"keyword": query,
@@ -84,25 +72,6 @@ impl MovieBoxClient {
self.get(&path).await
}
- pub async fn get_play_info(
- &self,
- subject_id: &str,
- season: usize,
- episode: usize,
- ) -> Result<Value, ScraperError> {
- let path = if season == 0 && episode == 0 {
- format!(
- "/wefeed-mobile-bff/subject-api/play-info?subjectId={}",
- subject_id
- )
- } else {
- format!(
- "/wefeed-mobile-bff/subject-api/play-info?subjectId={}&se={}&ep={}",
- subject_id, season, episode
- )
- };
- self.get(&path).await
- }
pub async fn get_all_resources(
&self,
@@ -118,7 +87,10 @@ impl MovieBoxClient {
let sid = subject_id.to_string();
let r = res.to_string();
handles.push(tokio::spawn(async move {
- c.get_resources(&sid, season, episode, 1, Some(&r)).await
+ tokio::time::timeout(
+ std::time::Duration::from_secs(4),
+ c.get_resources(&sid, season, episode, 1, Some(&r))
+ ).await.unwrap_or(Err(ScraperError::ApiStatus(408)))
}));
}