Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
feat: introduce async stream loading with delay and dynamic details layout adjustments
Samir Hossains3ea5f0828278
diff --git a/src/tui/app.rs b/src/tui/app.rsindex 230c7cf..5b85fda 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -138,6 +138,7 @@ impl App {self.state.is_tv_mode = false;self.state.is_loading = false;self.state.is_fetching_streams = false;+ self.state.stream_error = None;self.state.search_results.clear();self.state.search_suggestions.clear();self.state.search_preview = None;@@ -261,6 +262,7 @@ impl App {self.state.selected_season = se;self.state.selected_episode = ep;self.state.resource_list_state.select(None);+ self.state.stream_error = None;self.state.active_resource_request = self.state.active_resource_request.wrapping_add(1);let memory_cached = self@@ -277,19 +279,31 @@ impl App {let cached = memory_cached.or_else(|| disk_cached.flatten());if let Some(streams) = cached {- let count = streams.len();if let Some(pool) = self.state.stream_pool.get_mut(&id) {pool.episode_index.insert((se, ep), streams.clone());}- let mut result = serde_json::Map::new();- result.insert("list".to_string(), serde_json::Value::Array(streams));- self.state.selected_resources = Some(serde_json::Value::Object(result));- self.state.is_loading = false;- self.state.is_fetching_streams = false;- self.state.resource_list_state.select(Some(0));- self.state.status_message = format!("{count} streams loaded from cache.");+ self.state.selected_resources = None;+ self.state.is_loading = true;+ self.state.is_fetching_streams = true;+ self.state.status_message = "Loading streams...".to_string();self.state.status_timer = 90;self.state.pending_episode_fetch = None;+ let sender = self.action_sender.clone();+ let context = self.request_context();+ let request_id = self.state.active_resource_request;+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_millis(120)).await;+ sender+ .send(Action::EpisodeStreamsReady(+ context,+ request_id,+ id,+ se,+ ep,+ serde_json::Value::Array(streams),+ ))+ .ok();+ });} else {self.state.selected_resources = None;self.state.is_loading = true;@@ -2568,6 +2582,9 @@ impl App {self.state.active_screen = Screen::Details;self.state.selected_details = None;self.state.selected_resources = None;+ self.state.is_loading = true;+ self.state.is_fetching_streams = false;+ self.state.stream_error = None;self.state.resource_list_state.select(None);self.state.language_list_state.select(Some(0));self.state.season_list_state.select(Some(0));@@ -3466,6 +3483,7 @@ impl App {self.state.is_loading = true;self.state.is_fetching_streams = true;self.state.selected_resources = None;+ self.state.stream_error = None;let context = self.request_context();if context.provider == ProviderKind::FourKHdHub {@@ -3518,16 +3536,22 @@ impl App {if let Some(pool) = self.state.stream_pool.get_mut(&subject_id) {if !force_refresh {if let Some(cached) = pool.episode_index.get(&(season, episode)) {- self.action_sender- .send(Action::EpisodeStreamsReady(- context,- request_id,- subject_id.clone(),- season,- episode,- serde_json::Value::Array(cached.clone()),- ))- .ok();+ let sender = self.action_sender.clone();+ let cached = cached.clone();+ let cached_subject_id = subject_id.clone();+ tokio::spawn(async move {+ tokio::time::sleep(std::time::Duration::from_millis(120)).await;+ sender+ .send(Action::EpisodeStreamsReady(+ context,+ request_id,+ cached_subject_id,+ season,+ episode,+ serde_json::Value::Array(cached),+ ))+ .ok();+ });return None;}}@@ -3563,6 +3587,7 @@ impl App {}).await{+ tokio::time::sleep(std::time::Duration::from_millis(120)).await;sender.send(Action::SetStatus("Loaded from cache.".to_string())).ok();@@ -3842,6 +3867,7 @@ impl App {self.state.selected_resources = Some(serde_json::Value::Object(result));self.state.is_loading = false;self.state.is_fetching_streams = false;+ self.state.stream_error = None;self.state.resource_list_state.select(if count > 0 { Some(0) } else { None });@@ -3923,6 +3949,7 @@ impl App {self.state.is_loading = false;self.state.is_fetching_streams = false;self.state.selected_resources = None;+ self.state.stream_error = Some(err.clone());self.state.status_message = format!("Error: {}", err);self.state.status_timer = 150;}diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rsindex e38c548..148d6aa 100644--- a/src/tui/screens/details.rs+++ b/src/tui/screens/details.rs@@ -31,13 +31,47 @@ impl DetailsLayoutTier {}}- fn header_height(self, area: Rect) -> u16 {- match self {- Self::Wide => area.height.saturating_sub(18).clamp(10, 12),- Self::Medium => area.height.saturating_sub(17).clamp(9, 11),- Self::Narrow => area.height.saturating_sub(16).clamp(7, 9),- Self::Tiny => area.height.saturating_sub(12).clamp(4, 6),- }+ fn header_height(self, area: Rect, details: Option<&serde_json::Value>) -> u16 {+ let (minimum, maximum, synopsis_limit, reserved_width) = match self {+ Self::Wide => (9, 12, 3, 30),+ Self::Medium => (8, 11, 2, 24),+ Self::Narrow => (7, 9, 2, 4),+ Self::Tiny => (4, 6, 1, 4),+ };+ let available_maximum = area.height.saturating_sub(match self {+ Self::Wide => 18,+ Self::Medium => 17,+ Self::Narrow => 16,+ Self::Tiny => 12,+ });+ let maximum = maximum.min(available_maximum.max(minimum));++ let Some(details) = details else {+ return minimum.min(maximum);+ };+ let synopsis = details+ .get("description")+ .and_then(|value| value.as_str())+ .or_else(|| details.get("intro").and_then(|value| value.as_str()))+ .unwrap_or_default();+ let text_width = area.width.saturating_sub(reserved_width).max(20) as usize;+ let title = details+ .get("title")+ .and_then(|value| value.as_str())+ .unwrap_or_default();+ let title_rows = (crate::tui::text::width(title) + 14)+ .div_ceil(text_width)+ .clamp(1, 2);+ let synopsis_rows = crate::tui::text::width(synopsis)+ .div_ceil(text_width)+ .clamp(1, synopsis_limit);+ let metadata_rows = match self {+ Self::Wide | Self::Medium => 5,+ Self::Narrow => 4,+ Self::Tiny => 3,+ };+ let content_rows = metadata_rows + title_rows.saturating_sub(1) + synopsis_rows;+ (content_rows as u16 + 2).clamp(minimum, maximum)}fn footer_height(self) -> u16 {@@ -47,7 +81,7 @@ impl DetailsLayoutTier {pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme) {let tier = DetailsLayoutTier::for_area(area);- let header_height = tier.header_height(area);+ let header_height = tier.header_height(area, state.selected_details.as_ref());let footer_height = tier.footer_height();let chunks = Layout::vertical([Constraint::Length(header_height),@@ -186,9 +220,20 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)&& inner_area.height >= 6&& inner_area.width >= 60;let poster_width = if show_poster {- ((inner_area.height as f32 * 1.33).ceil() as u16)- .clamp(10, 22)- .min(inner_area.width / 3)+ let width_for_height = state+ .poster_image+ .as_ref()+ .zip(state.image_picker.as_ref())+ .map(|(image, picker)| {+ let font = picker.font_size();+ let target_pixel_height =+ u64::from(inner_area.height) * u64::from(font.height.max(1));+ let target_pixel_width = target_pixel_height * u64::from(image.width())+ / u64::from(image.height().max(1));+ target_pixel_width.div_ceil(u64::from(font.width.max(1))) as u16+ })+ .unwrap_or_else(|| (inner_area.height as f32 * 1.5).ceil() as u16);+ width_for_height.clamp(10, 26).min(inner_area.width / 3)} else {0};@@ -202,13 +247,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)]).split(inner_area);- let poster_height = ((poster_width as f32) / 1.33).ceil() as u16;- let poster_height = h_chunks[0].height.min(poster_height);- let poster_area = ratatui::layout::Rect {- y: h_chunks[0].y + h_chunks[0].height.saturating_sub(poster_height) / 2,- height: poster_height,- ..h_chunks[0]- };+ let poster_area = h_chunks[0];let right_area = h_chunks[2];if show_poster && state.image_supported {@@ -331,13 +370,16 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)} else if matches!(tier, DetailsLayoutTier::Narrow) {top_meta.truncate(4);}+ let title_width = crate::tui::text::width(&title)+ + crate::tui::text::width(&format!(" ★ IMDb {}", imdb_rating));+ let title_rows = title_width+ .div_ceil(right_area.width.max(1) as usize)+ .clamp(1, 2);+ let metadata_height = (top_meta.len() + title_rows.saturating_sub(1)) as u16;let meta_chunks = Layout::default().direction(Direction::Vertical)- .constraints([- Constraint::Length(top_meta.len() as u16),- Constraint::Min(0),- ])+ .constraints([Constraint::Length(metadata_height), Constraint::Min(0)]).split(right_area);let meta_p = Paragraph::new(top_meta).wrap(Wrap { trim: true });@@ -922,9 +964,14 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme).and_then(|d| d.as_array()).is_some_and(|a| a.len() > 1);- let is_busy = state.is_loading || state.is_fetching_streams;+ let waiting_for_language = has_multiple_dubs && !state.language_chosen;+ let has_error = state.stream_error.is_some();- let msg = if is_busy {+ let msg = if waiting_for_language {+ "Choose an audio track to load streams.".to_string()+ } else if let Some(error) = &state.stream_error {+ format!("{error} — press r to retry.")+ } else {let spinner = if state.basic_terminal {let frames = ['-', '\\', '|', '/'];frames[(state.tick_count as usize) % frames.len()]@@ -933,20 +980,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)frames[(state.tick_count as usize) % frames.len()]};format!("{} Loading streams...", spinner)- } else if has_multiple_dubs && !state.language_chosen {- "Choose an audio track to load streams.".to_string()- } else if state.status_message.to_lowercase().contains("no streams")- || state.status_message.to_lowercase().contains("error")- {- state.status_message.clone()- } else {- "No streams found — press r to retry.".to_string()};- let style = if is_busy || (has_multiple_dubs && !state.language_chosen) {- theme.text_dim- } else {+ let style = if has_error {theme.error+ } else {+ theme.text_dim};if !msg.is_empty() {diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex 7814592..a754f2f 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -550,7 +550,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let has_results = !state.search_results.is_empty();let suggestion_height =if state.input_mode == InputMode::Editing && !state.search_suggestions.is_empty() {- state.search_suggestions.len().min(6) as u16 + 2+ state.search_suggestions.len().min(6) as u16 + 3} else {0};@@ -856,7 +856,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme){let search_area = search_bar_area;let visible_count = state.search_suggestions.len().min(6);- let dropdown_height = visible_count as u16 + 2;+ let dropdown_height = visible_count as u16 + 3;let selected_index = state.suggest_index.unwrap_or(0);let suggestion_offset = selected_index.saturating_add(1)@@ -893,6 +893,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)Constraint::Length(1),Constraint::Length(visible_count as u16),Constraint::Length(1),+ Constraint::Length(1),]).split(dropdown_area);let items: Vec<ratatui::widgets::ListItem> = state@@ -970,10 +971,18 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)])}.centered();+ let separator_symbol = if state.basic_terminal { "-" } else { "─" };+ let separator = separator_symbol.repeat(dropdown_rows[2].width as usize);frame.render_widget(- Paragraph::new(footer).style(Style::default().bg(surface)),+ Paragraph::new(separator)+ .style(theme.surface1.bg(surface))+ .alignment(Alignment::Center),dropdown_rows[2],);+ frame.render_widget(+ Paragraph::new(footer).style(Style::default().bg(surface)),+ dropdown_rows[3],+ );if state.search_suggestions.len() > visible_count {let mut scrollbar_state = ratatui::widgets::ScrollbarState::default().content_length(state.search_suggestions.len())diff --git a/src/tui/state.rs b/src/tui/state.rsindex 822065f..1d924aa 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -80,6 +80,7 @@ pub struct AppState {pub is_waiting_for_download_stream: bool,pub is_downloading: bool,pub is_fetching_streams: bool,+ pub stream_error: Option<String>,pub preview_cache: lru::LruCache<String, serde_json::Value>,pub resource_list_state: ListState,@@ -188,6 +189,7 @@ impl Default for AppState {is_waiting_for_download_stream: false,is_downloading: false,is_fetching_streams: false,+ stream_error: None,preview_cache: lru::LruCache::new(std::num::NonZeroUsize::new(30).unwrap()),resource_list_state: ListState::default(),