Skip to content

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

fix(moviebox): optimize subtitle aggregation latency and series season defaulting

Samir Hossainsbbe1e069cec3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 19028e8..9f1fa6b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,18 +18,27 @@
- Added documentation build integrity validation step in CI hygiene pipeline (`.github/workflows/ci.yml`).
### Fixed
+- **Series Season Default & Episode List Rendering Normalization**:
+ - Initialized unselected series search results with `season: 0`, preventing catalog season counts from masquerading as watch history progress and erroneously defaulting multi-season shows (e.g. *Breaking Bad*) to their final season on initial selection.
+ - Guarded history pre-seeding in search submission strictly to `/history` queries and active continue-watching items, ensuring search results always open at Season 1 Episode 1 for new series while resuming at the user's progress for previously watched shows.
+ - Authoritatively resolved target season and episode in `DetailsSuccess`, preserving in-view season and episode positions across audio dub switches while defaulting fresh series navigation to Season 1 Episode 1.
+ - Replaced `"· "` unwatched episode status prefix with clean whitespace padding, eliminating double middots (`· · EP 01`) and stray dots before unselected episodes in the details pane.
+ - Guarded duration formatting against empty strings in `MediaDetails`, eliminating duplicate bullet dividers (`· ·`) in the metadata header for series without runtime durations.
- **Accurate Playback & Download Preparation Notifications**:
- Replaced misleading "Fetching subtitles" toast notifications during stream and episode download preparation with accurate stream preparation notices (`Preparing <filename>...` and `Resolving episode stream...`), eliminating false subtitle retrieval messages when streams rely on embedded subtitles or contain no external captions.
- Clarified external subtitle download failure status to `External subtitle unavailable; playing stream directly.` to prevent ambiguity when video containers carry built-in subtitles.
- Standardized download mirror error notice to `No downloadable mirrors were found for this release.` and normalized notification title casing.
-- **MovieBox Subtitle Resolution & Multi-Language Track Extraction**:
- - Resolved full multi-language subtitle availability (English, Bengali, Arabic, Filipino, Hindi, Indonesian, Urdu) on MovieBox by linking genuine upload `resourceId` identifiers to releases instead of internal CDN transcoding stream IDs, and aggregating captions across audio dub siblings in `MovieBoxService::get_ext_captions`.
+- **MovieBox Subtitle Resolution & High-Speed Multi-Tier Aggregation**:
+ - Implemented multi-tier subtitle resolution in `MovieBoxService::get_ext_captions` with immediate early-exit (< 250ms) when the active stream provides rich subtitles (≥ 5 tracks), eliminating 15–20 superfluous sibling network round-trips that previously triggered 15-second playback resolution timeouts.
+ - Replaced sequential nested loops for sibling dub crawls with concurrent parallel dispatch via `futures::future::join_all`, bounding multi-dub subtitle aggregation (e.g. *Ek Deewane Ki Deewaniyat*) to < 1.2s.
+ - Added asynchronous background subtitle cache pre-warming in `Action::EpisodeStreamsReady`, fetching and caching subtitle options as soon as streams are received so that pressing Enter on a stream yields an instant < 1ms cache hit.
+ - Resolved full multi-language subtitle availability (English, Bengali, Arabic, Chinese, Filipino, French, Hindi, Indonesian, Malay, Portuguese, Punjabi, Russian, Urdu) on MovieBox by linking genuine upload `resourceId` identifiers to releases instead of internal CDN transcoding stream IDs.
- Filtered out 34-byte dummy placeholder caption files returned by transcoding endpoints and deduplicated subtitle tracks by language and download URL.
- Added automatic fallback to subject resources in `MovieBoxService::get_ext_captions` when a stream ID does not directly attach captions.
- Added `in_id` language code mapping to `sanitize_language_label` for localized Indonesian subtitle display.
- Registered `draw_subtitle_picker` in `App::draw`, restoring the visual "Subtitles" modal picker overlay during stream playback and download preparation when external captions exist.
- Tightened modal picker vertical height calculation in `picker_layout`, eliminating blank gap lines between the last list item and the bottom divider for short lists.
- - Replaced synthetic non-numeric resource ID generation in `get_selected_resource_id` with direct `Release.resource_id` resolution, preventing HTTP 400 parameter parsing errors against the `/wefeed-mobile-bff/subject-api/get-ext-captions` endpoint.
+ - Hardened `Action::PlayStream` error handling with structured diagnostic warnings on subtitle timeout or resolution failure before dispatching direct playback.
- **Termux Android Player Exit Code 126 & Intent Bridge Resolution**:
- Eliminated `Player Error: Crash code: 126 (/system/bin/am[11]: /data/data/com.termux/files/usr/bin/cmd: Permission denied)` crash in Termux on Android 10+ by prioritizing native Termux openers (`termux-open`, `termux-open-url`, `termux-am`) and strictly avoiding unprivileged `/system/bin/am` shell script calls.
- Preserved `LD_PRELOAD` for Termux applet compatibility while prepending system paths (`/system/bin:/system/xbin`) for system command invocations.
diff --git a/src/models.rs b/src/models.rs
index d4f0380..281fd90 100644
--- a/src/models.rs
+++ b/src/models.rs
@@ -78,7 +78,7 @@ impl SearchResult {
},
release_year: item.year.unwrap_or_default(),
cover_url: item.poster_url,
- season: item.season_count.unwrap_or(0),
+ season: 0,
episode: 1,
provider: item.id.provider,
}
diff --git a/src/providers/moviebox/adapt.rs b/src/providers/moviebox/adapt.rs
index 9d7842a..d7442a3 100644
--- a/src/providers/moviebox/adapt.rs
+++ b/src/providers/moviebox/adapt.rs
@@ -324,9 +324,15 @@ pub fn moviebox_details_json_to_media_details(
let duration = subject.get("duration").and_then(|d| {
if let Some(n) = d.as_u64() {
- Some(format!("{}m", n / 60))
+ if n > 0 {
+ Some(format!("{}m", n / 60))
+ } else {
+ None
+ }
} else {
- d.as_str().map(|s| s.to_string())
+ d.as_str()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty() && s != "0m" && s != "0")
}
});
diff --git a/src/service.rs b/src/service.rs
index 64fbf78..1e684dd 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -199,57 +199,55 @@ impl MovieBoxService {
let mut all_captions = Vec::new();
let mut seen_urls = std::collections::HashSet::new();
- let mut append_captions = |opts: Vec<crate::providers::models::SubtitleOption>| {
- for opt in opts {
- if seen_urls.insert(opt.url.clone()) {
- all_captions.push(opt);
- }
- }
- };
-
if let Ok(payload) = self.client.get_ext_captions(subject_id, resource_id).await {
- append_captions(crate::providers::moviebox::adapt::captions_json_to_options(
- &payload,
- ));
- }
-
- let mut subjects_to_check = vec![subject_id.to_string()];
- for sib in sibling_ids {
- if !sib.is_empty() && !subjects_to_check.contains(sib) && subjects_to_check.len() < 5 {
- subjects_to_check.push(sib.clone());
- }
+ Self::append_unique_captions(
+ &mut all_captions,
+ &mut seen_urls,
+ crate::providers::moviebox::adapt::captions_json_to_options(&payload),
+ );
}
- for sid in &subjects_to_check {
- if let Ok((items, _)) = self.client.fetch_resource_page(sid, 0, 1).await {
- for item in items {
- let item_rid =
- item.get("resourceId")
- .or_else(|| item.get("id"))
- .and_then(|v| {
- if let Some(n) = v.as_i64() {
- Some(n.to_string())
- } else if let Some(n) = v.as_u64() {
- Some(n.to_string())
- } else {
- v.as_str().map(|s| s.to_string())
+ if all_captions.len() < 5 && !sibling_ids.is_empty() {
+ let mut sibling_futs = Vec::new();
+ for sib in sibling_ids.iter().take(3) {
+ if !sib.is_empty() && sib != subject_id {
+ let client = &self.client;
+ sibling_futs.push(async move {
+ if let Ok((items, _)) = client.fetch_resource_page(sib, 0, 1).await {
+ if let Some(item) = items.first() {
+ let item_rid = item
+ .get("resourceId")
+ .or_else(|| item.get("id"))
+ .and_then(|v| {
+ if let Some(n) = v.as_i64() {
+ Some(n.to_string())
+ } else if let Some(n) = v.as_u64() {
+ Some(n.to_string())
+ } else {
+ v.as_str().map(|s| s.to_string())
+ }
+ });
+ if let Some(rid) = item_rid {
+ if let Ok(res_payload) = client.get_ext_captions(sib, &rid).await {
+ return crate::providers::moviebox::adapt::captions_json_to_options(
+ &res_payload,
+ );
+ }
}
- });
- if let Some(rid) = item_rid {
- if sid != subject_id || rid != resource_id {
- if let Ok(res_payload) = self.client.get_ext_captions(sid, &rid).await {
- append_captions(
- crate::providers::moviebox::adapt::captions_json_to_options(
- &res_payload,
- ),
- );
}
}
- }
+ Vec::new()
+ });
}
}
- }
+ if !sibling_futs.is_empty() {
+ let sibling_results = futures::future::join_all(sibling_futs).await;
+ for res in sibling_results {
+ Self::append_unique_captions(&mut all_captions, &mut seen_urls, res);
+ }
+ }
+ }
let mut deduplicated: Vec<crate::providers::models::SubtitleOption> = Vec::new();
let mut seen_languages = std::collections::HashSet::new();
for sub in all_captions {
@@ -274,6 +272,18 @@ impl MovieBoxService {
Ok(deduplicated)
}
+ fn append_unique_captions(
+ target: &mut Vec<crate::providers::models::SubtitleOption>,
+ seen_urls: &mut std::collections::HashSet<String>,
+ opts: Vec<crate::providers::models::SubtitleOption>,
+ ) {
+ for opt in opts {
+ if seen_urls.insert(opt.url.clone()) {
+ target.push(opt);
+ }
+ }
+ }
+
pub async fn fetch_poster_bytes(&self, url: &str) -> Option<Vec<u8>> {
let response = self
.http_client
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index d3308d4..2d68cd7 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -792,8 +792,7 @@ impl App {
.state
.search_query
.trim()
- .eq_ignore_ascii_case("/history")
- || (item.season > 0 && item.episode > 0);
+ .eq_ignore_ascii_case("/history");
let se = if is_history && item.season > 0 {
item.season
} else {
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 4a99b72..b6e8224 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -662,7 +662,16 @@ impl App {
.send(Action::ShowSubtitlePopup(source_clone.url, res))
.ok();
}
- _ => {
+ Err(_) => {
+ log::warn!(
+ "[playback] Subtitle resolution timed out after 15s for rid={rid}"
+ );
+ sender.send(Action::DispatchPlayback(source_clone)).ok();
+ }
+ Ok(Err(err)) => {
+ log::warn!(
+ "[playback] Subtitle resolution failed for rid={rid}: {err}"
+ );
sender.send(Action::DispatchPlayback(source_clone)).ok();
}
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index b2af95e..5bbf6a2 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -328,13 +328,10 @@ impl App {
};
let release_year = item.year.clone().unwrap_or_default();
let cover_url = item.poster_url.clone();
- let season = item.season_count.unwrap_or(0);
-
if let Some(existing) =
self.state.search_results.iter_mut().find(|r| r.id == id)
{
- if season > existing.season {
- existing.season = season;
+ if existing.title.is_empty() {
existing.title = clean_title;
existing.stype = stype;
existing.release_year = release_year;
@@ -372,7 +369,7 @@ impl App {
stype,
release_year,
cover_url,
- season,
+ season: 0,
episode: 1,
provider: context.provider,
});
@@ -1021,15 +1018,21 @@ impl App {
}
}
- let target_season = if self.state.selected_season > 0 {
- self.state.selected_season
- } else {
- default_season
- };
- let target_episode = if self.state.selected_episode > 0 {
- self.state.selected_episode
+ let (target_season, target_episode) = if self.state.language_chosen {
+ (
+ if self.state.selected_season > 0 {
+ self.state.selected_season
+ } else {
+ default_season
+ },
+ if self.state.selected_episode > 0 {
+ self.state.selected_episode
+ } else {
+ default_episode
+ },
+ )
} else {
- default_episode
+ (default_season, default_episode)
};
let season_idx = self
@@ -1818,6 +1821,58 @@ impl App {
self.state
.set_status_default(format!("{} streams available.", count));
+ if count > 0 {
+ if let Some(rid) = self
+ .state
+ .selected_resources
+ .first()
+ .and_then(|r| r.resource_id.clone())
+ {
+ let subject_id = self.state.active_subject_id.clone().unwrap_or_default();
+ let service = self.service.clone();
+ let sibling_ids: Vec<String> = self
+ .state
+ .selected_details
+ .as_ref()
+ .map(|d| {
+ let mut ids = vec![d.id.value.clone()];
+ ids.extend(d.dubs.iter().map(|dub| dub.subject_id.clone()));
+ ids.retain(|s| !s.is_empty());
+ ids.sort();
+ ids.dedup();
+ ids
+ })
+ .unwrap_or_default();
+ tokio::spawn(async move {
+ let already_cached = tokio::task::spawn_blocking({
+ let subject_id = subject_id.clone();
+ let rid = rid.clone();
+ move || {
+ crate::cache::get_captions_cache_typed(&subject_id, &rid)
+ .is_some()
+ }
+ })
+ .await
+ .unwrap_or(false);
+
+ if !already_cached {
+ if let Ok(res) = service
+ .get_ext_captions(&subject_id, &rid, &sibling_ids)
+ .await
+ {
+ tokio::task::spawn_blocking(move || {
+ crate::cache::set_captions_cache_typed(
+ &subject_id,
+ &rid,
+ &res,
+ );
+ });
+ }
+ }
+ });
+ }
+ }
+
if self.state.is_waiting_for_download_stream {
self.state.is_waiting_for_download_stream = false;
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index 4d38455..efb2868 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -518,7 +518,6 @@ impl App {
};
let release_year = item.year.clone().unwrap_or_default();
let cover_url = item.poster_url.clone();
- let season = item.season_count.unwrap_or(0);
let metrics = metrics_map.get(&id).copied().unwrap_or_default();
if let Some(existing) = self.state.search_results.iter_mut().find(|r| r.id == id) {
@@ -528,8 +527,7 @@ impl App {
stored_metrics.recent_rating =
stored_metrics.recent_rating.or(metrics.recent_rating);
stored_metrics.popularity = stored_metrics.popularity.or(metrics.popularity);
- if season > existing.season {
- existing.season = season;
+ if existing.title.is_empty() {
existing.title = clean_title;
existing.stype = stype;
existing.release_year = release_year;
@@ -568,7 +566,7 @@ impl App {
stype,
release_year,
cover_url,
- season,
+ season: 0,
episode: 1,
provider: item.id.provider,
});
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index cb4c39e..db79b93 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -328,8 +328,16 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
} else {
"N/A".to_string()
};
- let duration = details.duration.as_deref().unwrap_or("N/A");
- let imdb_rating = details.imdb_rating.as_deref().unwrap_or("N/A");
+ let duration = details
+ .duration
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ .unwrap_or("N/A");
+ let imdb_rating = details
+ .imdb_rating
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ .unwrap_or("N/A");
let tagline = details.tagline.as_deref();
let details_block = Block::default()
@@ -469,12 +477,12 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
Span::styled(type_str, theme.accent.add_modifier(Modifier::BOLD)),
];
- if duration != "N/A" {
+ if !duration.trim().is_empty() && duration != "N/A" {
badge_spans.push(Span::styled(bullet_sep, theme.overlay0));
badge_spans.push(Span::styled(duration, theme.subtext1));
}
- if imdb_rating != "N/A" {
+ if !imdb_rating.trim().is_empty() && imdb_rating != "N/A" {
badge_spans.push(Span::styled(bullet_sep, theme.overlay0));
if state.basic_terminal {
badge_spans.push(Span::styled("IMDb ", theme.rating));
@@ -903,7 +911,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
} else {
"▶ "
};
- let unwatched_sym = if state.basic_terminal { "[ ] " } else { "· " };
+ let unwatched_sym = if state.basic_terminal { " " } else { " " };
ep_numbers
.iter()
.map(|&ep| {
@@ -2296,6 +2304,65 @@ mod tests {
assert!(content.contains("EP 01"));
assert!(content.contains("EP 02"));
assert!(content.contains("EP 10"));
+ assert!(!content.contains("· ·"));
+ assert!(!content.contains("· EP"));
+ }
+
+ #[test]
+ fn test_details_header_metadata_suppresses_empty_duration_and_double_middot() {
+ let backend = ratatui::backend::TestBackend::new(100, 30);
+ let mut terminal = ratatui::Terminal::new(backend).unwrap();
+ let mut state = AppState {
+ active_subject_id: Some("test_series_metadata".to_string()),
+ selected_details: Some(MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "test_series_metadata".to_string(),
+ },
+ title: "Breaking Bad".to_string(),
+ media_type: MediaType::Series,
+ year: Some("2008".to_string()),
+ description: None,
+ tagline: None,
+ imdb_rating: Some("9.5".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: Some("".to_string()),
+ genres: vec![],
+ seasons: vec![Season {
+ number: 1,
+ episodes: vec![],
+ }],
+ dubs: vec![],
+ }),
+ available_seasons: vec![Season {
+ number: 1,
+ episodes: vec![],
+ }],
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ terminal
+ .draw(|frame| {
+ draw(frame, frame.area(), &mut state, &theme);
+ })
+ .unwrap();
+
+ let buffer = terminal.backend().buffer();
+ let content = buffer
+ .content()
+ .iter()
+ .map(|cell| cell.symbol())
+ .collect::<String>();
+ assert!(content.contains("2008"));
+ assert!(content.contains("Series"));
+ assert!(content.contains("9.5"));
+ assert!(!content.contains("· ·"));
+ assert!(!content.contains("· ·"));
}
#[test]
diff --git a/tests/content_pipeline.rs b/tests/content_pipeline.rs
index bc13cf7..316b5f7 100644
--- a/tests/content_pipeline.rs
+++ b/tests/content_pipeline.rs
@@ -1,7 +1,8 @@
use moviebox_tui::{
models::SearchResult,
providers::models::{
- CatalogItem, MediaDetails, MediaType, ProviderKind, ProviderMediaId, RequestContext,
+ CatalogItem, Episode, MediaDetails, MediaType, ProviderKind, ProviderMediaId,
+ RequestContext, Season,
},
tui::{
action::Action,
@@ -373,3 +374,212 @@ async fn test_search_preview_and_details_metadata_isolation() {
);
assert_eq!(matching_fallback.director.as_deref(), Some("New Director"));
}
+#[tokio::test]
+async fn test_series_details_defaults_to_season_one_when_no_history() {
+ let mut app = App::new();
+ app.state_mut().active_provider = ProviderKind::MovieBox;
+ app.state_mut().active_screen = Screen::Details;
+ app.state_mut().active_subject_id = Some("bb_series".to_string());
+ app.state_mut().selected_season = 1;
+ app.state_mut().selected_episode = 1;
+ app.state_mut().active_details_request = 1;
+
+ let context = RequestContext {
+ provider: ProviderKind::MovieBox,
+ generation: app.state().provider_generation,
+ };
+
+ let seasons = (1..=5)
+ .map(|s| Season {
+ number: s,
+ episodes: (1..=10)
+ .map(|e| Episode {
+ season: s,
+ number: e,
+ title: None,
+ })
+ .collect(),
+ })
+ .collect();
+
+ let details = MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "bb_series".to_string(),
+ },
+ title: "Breaking Bad".to_string(),
+ media_type: MediaType::Series,
+ year: Some("2008".to_string()),
+ description: None,
+ tagline: None,
+ imdb_rating: Some("9.5".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: vec![],
+ seasons,
+ dubs: vec![],
+ };
+
+ app.handle_action(Action::DetailsSuccess(
+ context,
+ 1,
+ "bb_series".to_string(),
+ details,
+ ))
+ .await;
+
+ assert_eq!(app.state().selected_season, 1);
+ assert_eq!(app.state().selected_episode, 1);
+ assert_eq!(app.state().season_list_state.selected(), Some(0));
+ assert_eq!(app.state().episode_list_state.selected(), Some(0));
+}
+
+#[tokio::test]
+async fn test_series_details_resumes_watch_history() {
+ let mut app = App::new();
+ app.state_mut().active_provider = ProviderKind::MovieBox;
+ app.state_mut().active_screen = Screen::Details;
+ app.state_mut().selected_season = 1;
+ app.state_mut().selected_episode = 1;
+ app.state_mut()
+ .history
+ .recent
+ .push(moviebox_tui::history::WatchHistoryItem {
+ provider: "moviebox".to_string(),
+ subject_id: "bb_series".to_string(),
+ title: "Breaking Bad".to_string(),
+ stype: 2,
+ season: 3,
+ episode: 7,
+ duration_seconds: Some(3000),
+ progress_seconds: 500,
+ completed: false,
+ timestamp: 1000,
+ release_year: "2008".to_string(),
+ cover_url: None,
+ });
+ app.state_mut().active_details_request = 1;
+
+ let context = RequestContext {
+ provider: ProviderKind::MovieBox,
+ generation: app.state().provider_generation,
+ };
+
+ let seasons = (1..=5)
+ .map(|s| Season {
+ number: s,
+ episodes: (1..=10)
+ .map(|e| Episode {
+ season: s,
+ number: e,
+ title: None,
+ })
+ .collect(),
+ })
+ .collect();
+
+ let details = MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "bb_series".to_string(),
+ },
+ title: "Breaking Bad".to_string(),
+ media_type: MediaType::Series,
+ year: Some("2008".to_string()),
+ description: None,
+ tagline: None,
+ imdb_rating: Some("9.5".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: vec![],
+ seasons,
+ dubs: vec![],
+ };
+
+ app.handle_action(Action::DetailsSuccess(
+ context,
+ 1,
+ "bb_series".to_string(),
+ details,
+ ))
+ .await;
+
+ assert_eq!(app.state().selected_season, 3);
+ assert_eq!(app.state().selected_episode, 7);
+ assert_eq!(app.state().season_list_state.selected(), Some(2));
+ assert_eq!(app.state().episode_list_state.selected(), Some(6));
+}
+
+#[tokio::test]
+async fn test_series_details_preserves_season_and_episode_on_language_switch() {
+ let mut app = App::new();
+ app.state_mut().active_provider = ProviderKind::MovieBox;
+ app.state_mut().active_screen = Screen::Details;
+ app.state_mut().active_subject_id = Some("bb_series".to_string());
+ app.state_mut().language_chosen = true;
+ app.state_mut().selected_season = 4;
+ app.state_mut().selected_episode = 2;
+
+ app.state_mut().active_details_request = 1;
+
+ let context = RequestContext {
+ provider: ProviderKind::MovieBox,
+ generation: app.state().provider_generation,
+ };
+
+ let seasons = (1..=5)
+ .map(|s| Season {
+ number: s,
+ episodes: (1..=10)
+ .map(|e| Episode {
+ season: s,
+ number: e,
+ title: None,
+ })
+ .collect(),
+ })
+ .collect();
+
+ let details = MediaDetails {
+ id: ProviderMediaId {
+ provider: ProviderKind::MovieBox,
+ value: "bb_series".to_string(),
+ },
+ title: "Breaking Bad".to_string(),
+ media_type: MediaType::Series,
+ year: Some("2008".to_string()),
+ description: None,
+ tagline: None,
+ imdb_rating: Some("9.5".to_string()),
+ director: None,
+ stars: None,
+ prints: None,
+ audios: None,
+ poster_url: None,
+ duration: None,
+ genres: vec![],
+ seasons,
+ dubs: vec![],
+ };
+
+ app.handle_action(Action::DetailsSuccess(
+ context,
+ 1,
+ "bb_series".to_string(),
+ details,
+ ))
+ .await;
+
+ assert_eq!(app.state().selected_season, 4);
+ assert_eq!(app.state().selected_episode, 2);
+ assert_eq!(app.state().season_list_state.selected(), Some(3));
+ assert_eq!(app.state().episode_list_state.selected(), Some(1));
+}
diff --git a/tests/live_stream_verification.rs b/tests/live_stream_verification.rs
index 515896b..b1636c4 100644
--- a/tests/live_stream_verification.rs
+++ b/tests/live_stream_verification.rs
@@ -417,3 +417,53 @@ async fn test_live_moviebox_captions_end_to_end() {
.any(|c| c.name.contains("বাংলা") || c.name.eq_ignore_ascii_case("Bengali"))
);
}
+
+#[tokio::test]
+#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
+async fn test_live_moviebox_breaking_bad_series_captions_latency() {
+ let service = moviebox_tui::service::MovieBoxService::new();
+ service.client.init().await.expect("client init successful");
+
+ let subject_id = "6207982430134357800";
+ let releases = service
+ .client
+ .episode_streams(subject_id, 1, 1)
+ .await
+ .expect("fetch episode streams");
+ assert!(!releases.is_empty());
+
+ let release = &releases[0];
+ let resource_id = release
+ .resource_id
+ .as_deref()
+ .expect("must have resource_id");
+
+ let sibling_ids = vec![
+ "1382465867459478920".to_string(),
+ "9185019261486531816".to_string(),
+ ];
+
+ let t0 = std::time::Instant::now();
+ let captions = service
+ .get_ext_captions(subject_id, resource_id, &sibling_ids)
+ .await
+ .expect("fetch captions");
+ let elapsed = t0.elapsed();
+
+ assert!(
+ elapsed < std::time::Duration::from_secs(3),
+ "captions resolution should complete within 3 seconds, took {:.2?}",
+ elapsed
+ );
+ assert!(
+ captions.len() >= 10,
+ "should return >= 10 languages for Breaking Bad S1E1, got {}",
+ captions.len()
+ );
+ assert!(
+ captions
+ .iter()
+ .any(|c| c.name.eq_ignore_ascii_case("English")),
+ "must include English"
+ );
+}
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index ed43728..fa2ebee 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -776,6 +776,36 @@ async fn test_history_item_enter_pre_seeds_season_and_episode() {
assert_eq!(app.state().selected_episode, 7);
assert!(!app.state().auto_play_on_ready);
}
+#[tokio::test]
+async fn test_search_series_submit_defaults_to_season_one() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ app.state_mut().input_mode = InputMode::Normal;
+ app.state_mut().search_query.set_content("Breaking Bad");
+ app.state_mut().search_results.push(SearchResult {
+ id: "1382465867459478920".to_string(),
+ title: "Breaking Bad".to_string(),
+ stype: 2,
+ release_year: "2008".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 1,
+ provider: ProviderKind::MovieBox,
+ });
+ app.state_mut().search_list_state.select(Some(0));
+ app.state_mut().last_search_edit =
+ std::time::Instant::now() - std::time::Duration::from_secs(1);
+
+ app.handle_action(Action::Submit).await;
+
+ assert_eq!(app.state().active_screen, Screen::Details);
+ assert_eq!(
+ app.state().active_subject_id.as_deref(),
+ Some("1382465867459478920")
+ );
+ assert_eq!(app.state().selected_season, 1);
+ assert_eq!(app.state().selected_episode, 1);
+}
#[tokio::test]
async fn test_no_results_and_error_state_rendering_hints() {