Skip to content

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

feat(fourkhdhub): parallel stream resolution, mirror scoring, and fast error handling

Samir Hossains490c2ccd5955
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55241a1..f1375a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,12 @@
## [Unreleased]
### Added
+- **4KHDHub Fast Stream Resolution & Bounded Concurrency (`src/providers/fourkhdhub/`)**:
+ - **Path Percent-Encoding Normalization (`hubcloud.rs`)**: Automatic normalization of raw stream URLs containing unencoded spaces, brackets, and special characters using `percent_encoding::utf8_percent_encode` with `NON_ALPHANUMERIC`, preventing `InvalidUrl` errors on complex release paths.
+ - **Prioritized Mirror Scoring (`hubcloud.rs`)**: Refactored candidate stream scoring to prioritize direct Google Video/CDN backends (`score 0`) and PixelDrain API (`score 1`) ahead of storage CDNs (`score 2`) and Cloudflare workers (`score 3`).
+ - **Concurrent Mirror Resolution & Bounded Probing (`client.rs`)**: Concurrently fetches resolver URLs across available release mirrors with a 4.0-second timeout, probing candidates in prioritized chunks of 3 via `futures::future::select_ok` for fast (<2s) playback start.
+ - **Upstream HTML Error Detection (`client.rs`)**: Inspects preflight response bodies for expired file notices (`"Failed to extract link"`, `"Token Expired"`, `"File Not Found"`, `"404"`), rejecting dead torrent mirrors immediately instead of hanging on missing redirect query parameters.
+ - **Actionable User Guidance & Reset Safety (`playback.rs`, `download.rs`, `system.rs`)**: Standardized resolution timeouts to 18s, formatted notifications with specific guidance (`"4KHDHub Stream Unavailable: Mirrors for this release are dead or expired on 4KHDHub. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox."`), and enforced `is_resolving_playback` state reset on all error and cancellation paths.
- **Mode-Aware Dynamic Search Suggestions & Rotating Hints (`src/tui/screens/home.rs`)**: Mode-aware rotating search suggestion hints cycling at 4-second intervals across Streaming, Addon, and TV modes providing title recommendations, slash command discovery, and mode-specific tips with priority fallback for active status messages.
- **Smooth Precision Beam Cursor & Active Keystroke Debounce (`src/tui/screens/home.rs`)**: High-contrast vertical beam cursor (`▎` in `theme.accent`, `█` on basic terminals) with zero gap spacing against ghosted placeholder text, balanced 500ms idle blinking cadence, and active typing debounce preventing mid-keystroke cursor flickering.
- **Multi-`Esc` Search Results Return-to-Homepage Navigation (`src/tui/app/keyboard.rs`)**: Enhanced `Esc` navigation so pressing `Esc` from search results focuses the search input (`InputMode::Editing`), and pressing `Esc` again clears the search state and returns directly to the landing screen / homepage.
diff --git a/docs/providers.md b/docs/providers.md
index 8b9ae6b..891c8c6 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -45,20 +45,15 @@ which `app/playback.rs::launch_player` feeds to the external player.
## 4KHDHub
-- `client.rs::resolve_release` walks the release's mirrors; each candidate goes through
- `preflight` which validates the URL and issues an **open-range** probe
- (`Range: bytes=0-`) so probe-only trap mirrors (which answer a tiny bounded range but
- refuse real streaming) are rejected. The 4KHD referer and a browser user-agent are
- attached so referer-gated CDNs stream in the player too.
-- `hubcloud.rs` resolves hubcloud/hubdrive pages into candidate playable links and
- selects a mirror by score.
+- `client.rs::resolve_release` resolves release mirrors concurrently using bounded-concurrency probing (`select_ok` in batches of 3) with a 3.5s per-probe timeout.
+- Direct links undergo automatic path percent-encoding normalization (`validate_playback_url`) to handle filenames containing unencoded spaces, brackets, and special characters.
+- Preflight probes issue an **open-range** probe (`Range: bytes=0-`) and inspect response bodies for expired mirror errors (`"Failed to extract link"`, `"Token Expired"`, `"404"`) to fail fast on expired torrents.
+- `hubcloud.rs` scores and prioritizes candidate streams (Fast Direct Google/CDN $\to$ PixelDrain $\to$ Storage $\to$ Workers $\to$ Fallbacks).
- **Multilingual audio detection**: `parser.rs::detect_language` parses release titles and
metadata for 30+ regional and international languages (Hindi, Tamil, Telugu, Kannada,
Malayalam, Bengali, Marathi, Punjabi, Gujarati, Urdu, Japanese, Korean, Chinese, Spanish,
French, German, Italian, etc.) and formats all available audio tracks for stream display.
-- Errors are surfaced as `FourKHdHubError`; mirror rejections and the final failure
- reason are logged with the mirror label and a sanitized URL.
-
+- Errors are mapped into `ProviderError::Unavailable` with user-actionable instructions guiding selection of alternate releases.
## BDIX
- `circleftp` and `dhakaflix` scrape FTP-style indexes; both are used behind the
diff --git a/src/providers/fourkhdhub/client.rs b/src/providers/fourkhdhub/client.rs
index 9de3a4b..ec85797 100644
--- a/src/providers/fourkhdhub/client.rs
+++ b/src/providers/fourkhdhub/client.rs
@@ -87,130 +87,201 @@ impl FourKHdHubClient {
));
}
let referer = self.base_url.as_str().trim_end_matches('/').to_string();
- let mut last_error = None;
- for mirror in &release.mirrors {
- let candidates = if mirror.resolver_url.contains("hubcloud.") {
- hubcloud::resolve(&self.client, &mirror.resolver_url).await
- } else if mirror.resolver_url.contains("hubdrive.") {
- hubcloud::resolve_hubdrive(&self.client, &mirror.resolver_url).await
- } else {
- hubcloud::validate_playback_url(&mirror.resolver_url)
- .map(|url| vec![(url, mirror.label.clone(), mirror.headers.clone())])
- };
- if let Ok(candidates) = candidates {
- for (url, label, headers) in candidates {
- let mut merged = headers;
- if !merged
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("referer"))
- {
- merged.push(("Referer".to_string(), referer.clone()));
- }
- if !merged
- .iter()
- .any(|(name, _)| name.eq_ignore_ascii_case("user-agent"))
- {
- merged.push(("User-Agent".to_string(), BROWSER_UA.to_string()));
- }
- match self.preflight(&url, &merged).await {
- Ok(playable_url) => {
- log::info!(
- "4KHDHub mirror playable: {label} ({})",
- crate::logging::sanitize_url(&playable_url)
- );
- return Ok(PlaybackSource {
- provider: ProviderKind::FourKHdHub,
- url: playable_url,
- headers: merged,
- subtitle: None,
- source_label: label,
- });
- }
- Err(error) => {
- log::warn!(
- "4KHDHub mirror rejected ({label}): {error} [{}]",
- crate::logging::sanitize_url(&url)
- );
- last_error = Some(error.to_string());
- }
+ let fetch_futures = release.mirrors.iter().map(|mirror| {
+ let client = self.client.clone();
+ let mirror_url = mirror.resolver_url.clone();
+ let mirror_label = mirror.label.clone();
+ let mirror_headers = mirror.headers.clone();
+ async move {
+ let fetch = async {
+ if mirror_url.contains("hubcloud.") {
+ hubcloud::resolve(&client, &mirror_url).await
+ } else if mirror_url.contains("hubdrive.") {
+ hubcloud::resolve_hubdrive(&client, &mirror_url).await
+ } else {
+ hubcloud::validate_playback_url(&mirror_url)
+ .map(|url| vec![(url, mirror_label, mirror_headers)])
}
+ };
+ tokio::time::timeout(std::time::Duration::from_millis(4000), fetch)
+ .await
+ .map_err(|_| {
+ FourKHdHubError::NoPlayableMirror("mirror resolver timed out".into())
+ })
+ .and_then(|res| res)
+ }
+ });
+ let mirror_results = futures::future::join_all(fetch_futures).await;
+
+ let mut candidates = Vec::new();
+ for cand_list in mirror_results.into_iter().flatten() {
+ for (url, label, headers) in cand_list {
+ let score = hubcloud::score(&url, &label);
+ candidates.push((score, url, label, headers));
+ }
+ }
+ candidates.sort_by_key(|cand| cand.0);
+ let mut unique_candidates = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ for (_, url, label, headers) in candidates {
+ if seen.insert(url.clone()) {
+ unique_candidates.push((url, label, headers));
+ }
+ }
+
+ if unique_candidates.is_empty() {
+ return Err(FourKHdHubError::NoPlayableMirror(
+ "Mirrors for this release are dead or expired on 4KHDHub. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox.".into(),
+ ));
+ }
+
+ for chunk in unique_candidates.chunks(3) {
+ let chunk_futures = chunk.iter().map(|(url, label, headers)| {
+ let this = self.clone();
+ let url = url.clone();
+ let label = label.clone();
+ let mut merged = headers.clone();
+ if !merged
+ .iter()
+ .any(|(name, _)| name.eq_ignore_ascii_case("referer"))
+ {
+ merged.push(("Referer".to_string(), referer.clone()));
}
- } else if let Err(error) = candidates {
- log::warn!("4KHDHub mirror candidates failed: {error}");
- last_error = Some(error.to_string());
+ if !merged
+ .iter()
+ .any(|(name, _)| name.eq_ignore_ascii_case("user-agent"))
+ {
+ merged.push(("User-Agent".to_string(), BROWSER_UA.to_string()));
+ }
+ Box::pin(async move {
+ let playable_url = this.preflight(&url, &merged).await?;
+ Ok::<_, FourKHdHubError>((playable_url, label, merged))
+ })
+ });
+ if let Ok(((playable_url, label, headers), _)) =
+ futures::future::select_ok(chunk_futures).await
+ {
+ log::info!(
+ "4KHDHub mirror playable: {label} ({})",
+ crate::logging::sanitize_url(&playable_url)
+ );
+ return Ok(PlaybackSource {
+ provider: ProviderKind::FourKHdHub,
+ url: playable_url,
+ headers,
+ subtitle: None,
+ source_label: label,
+ });
}
}
+
log::error!(
- "4KHDHub: no playable mirror for release {:?} (last: {:?})",
- release.filename,
- last_error
+ "4KHDHub: no playable mirror for release {:?}",
+ release.filename
);
Err(FourKHdHubError::NoPlayableMirror(
- last_error.unwrap_or_else(|| "all mirrors rejected the stream probe".into()),
+ "Mirrors for this release are dead or expired on 4KHDHub. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox.".into(),
))
}
- async fn preflight(
+ pub async fn preflight(
&self,
url: &str,
headers: &[(String, String)],
) -> Result<String, FourKHdHubError> {
- hubcloud::validate_playback_url(url)?;
- let mut request = self
- .client
- .get(url)
- .header(reqwest::header::RANGE, "bytes=0-");
- for (name, value) in headers {
- request = request.header(name, value);
- }
- let response = request.send().await?.error_for_status()?;
- let mut final_url = response.url().clone();
- hubcloud::validate_playback_url(final_url.as_str())?;
- let content_type = response
- .headers()
- .get(reqwest::header::CONTENT_TYPE)
- .and_then(|value| value.to_str().ok())
- .unwrap_or_default()
- .to_ascii_lowercase();
- if content_type.contains("text/html")
- || content_type.contains("application/zip")
- || content_type.contains("text/plain")
- {
- let wrapped = final_url
- .query_pairs()
- .find(|(name, _)| name == "link")
- .map(|(_, value)| value.into_owned())
- .filter(|value| value.starts_with("https://"))
- .ok_or_else(|| {
- FourKHdHubError::Parse(format!("invalid media content type: {content_type}"))
- })?;
- hubcloud::validate_playback_url(&wrapped)?;
- let mut wrapped_request = self
+ let probe = async {
+ hubcloud::validate_playback_url(url)?;
+ let mut request = self
.client
- .get(&wrapped)
+ .get(url)
.header(reqwest::header::RANGE, "bytes=0-");
for (name, value) in headers {
- wrapped_request = wrapped_request.header(name, value);
+ request = request.header(name, value);
}
- let wrapped_response = wrapped_request.send().await?.error_for_status()?;
- final_url = wrapped_response.url().clone();
+ let response = request.send().await?.error_for_status()?;
+ let mut final_url = response.url().clone();
hubcloud::validate_playback_url(final_url.as_str())?;
- let wrapped_type = wrapped_response
+ let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
.to_ascii_lowercase();
- if wrapped_type.contains("text/html")
- || wrapped_type.contains("application/zip")
- || wrapped_type.contains("text/plain")
+ if content_type.contains("text/html")
+ || content_type.contains("application/zip")
+ || content_type.contains("text/plain")
{
- return Err(FourKHdHubError::Parse(format!(
- "invalid wrapped media content type: {wrapped_type}"
- )));
+ let body_bytes = response.bytes().await.unwrap_or_default();
+ let body_lower = String::from_utf8_lossy(&body_bytes).to_ascii_lowercase();
+ if body_lower.contains("failed to extract link")
+ || body_lower.contains("token expired")
+ || body_lower.contains("file not found")
+ || body_lower.contains("404 not found")
+ || body_lower.contains("link has expired")
+ || body_lower.contains("expired")
+ {
+ return Err(FourKHdHubError::NoPlayableMirror(
+ "upstream mirror reported expired file link".into(),
+ ));
+ }
+
+ let wrapped = final_url
+ .query_pairs()
+ .find(|(name, _)| name == "link")
+ .map(|(_, value)| value.into_owned())
+ .filter(|value| value.starts_with("https://"))
+ .ok_or_else(|| {
+ FourKHdHubError::NoPlayableMirror(format!(
+ "invalid media content type: {content_type}"
+ ))
+ })?;
+ hubcloud::validate_playback_url(&wrapped)?;
+ let mut wrapped_request = self
+ .client
+ .get(&wrapped)
+ .header(reqwest::header::RANGE, "bytes=0-");
+ for (name, value) in headers {
+ wrapped_request = wrapped_request.header(name, value);
+ }
+ let wrapped_response = wrapped_request.send().await?.error_for_status()?;
+ final_url = wrapped_response.url().clone();
+ hubcloud::validate_playback_url(final_url.as_str())?;
+ let wrapped_type = wrapped_response
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or_default()
+ .to_ascii_lowercase();
+ if wrapped_type.contains("text/html")
+ || wrapped_type.contains("application/zip")
+ || wrapped_type.contains("text/plain")
+ {
+ let wrapped_bytes = wrapped_response.bytes().await.unwrap_or_default();
+ let wrapped_lower =
+ String::from_utf8_lossy(&wrapped_bytes).to_ascii_lowercase();
+ if wrapped_lower.contains("failed to extract link")
+ || wrapped_lower.contains("token expired")
+ || wrapped_lower.contains("file not found")
+ || wrapped_lower.contains("404 not found")
+ || wrapped_lower.contains("expired")
+ {
+ return Err(FourKHdHubError::NoPlayableMirror(
+ "upstream mirror reported expired file link".into(),
+ ));
+ }
+ return Err(FourKHdHubError::NoPlayableMirror(format!(
+ "invalid wrapped media content type: {wrapped_type}"
+ )));
+ }
}
- }
- Ok(final_url.to_string())
+ Ok(final_url.to_string())
+ };
+
+ tokio::time::timeout(std::time::Duration::from_millis(3500), probe)
+ .await
+ .map_err(|_| {
+ FourKHdHubError::NoPlayableMirror("mirror preflight probe timed out (3.5s)".into())
+ })?
}
async fn fetch_text(&self, url: Url) -> Result<String, FourKHdHubError> {
@@ -239,3 +310,32 @@ fn build_client() -> reqwest::Client {
.build()
.unwrap_or_default()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn rejects_non_fourkhdhub_release() {
+ let client = FourKHdHubClient::new().expect("client creation");
+ let release = Release {
+ provider: ProviderKind::MovieBox,
+ filename: "test.mkv".into(),
+ quality: None,
+ codec: None,
+ language: None,
+ size_bytes: None,
+ season: None,
+ episode: None,
+ mirrors: Vec::new(),
+ };
+ assert!(client.resolve_release(&release).await.is_err());
+ }
+
+ #[test]
+ fn validates_provider_url_host_matching() {
+ let client = FourKHdHubClient::new().expect("client creation");
+ assert!(client.provider_url("movie/inception-2010").is_ok());
+ assert!(client.provider_url("https://evil.com/movie").is_err());
+ }
+}
diff --git a/src/providers/fourkhdhub/hubcloud.rs b/src/providers/fourkhdhub/hubcloud.rs
index 92df3a4..ff07fd9 100644
--- a/src/providers/fourkhdhub/hubcloud.rs
+++ b/src/providers/fourkhdhub/hubcloud.rs
@@ -40,7 +40,7 @@ pub async fn resolve(
let mut candidates = extract_script_pixeldrain_urls(&resolver_html)
.into_iter()
- .map(|url| (0, url, "PixelDrain".to_string()))
+ .map(|url| (score(&url, "PixelDrain"), url, "PixelDrain".to_string()))
.collect::<Vec<_>>();
candidates.extend(
resolver
@@ -172,7 +172,8 @@ fn validate_hubdrive_url(raw: &str) -> Result<(), FourKHdHubError> {
}
pub fn validate_playback_url(raw: &str) -> Result<String, FourKHdHubError> {
- let url = Url::parse(raw).map_err(|_| FourKHdHubError::InvalidUrl(raw.into()))?;
+ let url =
+ normalize_playback_url_str(raw).ok_or_else(|| FourKHdHubError::InvalidUrl(raw.into()))?;
if url.scheme() != "https" || url.host_str().is_none() {
return Err(FourKHdHubError::InvalidUrl(raw.into()));
}
@@ -192,6 +193,48 @@ pub fn validate_playback_url(raw: &str) -> Result<String, FourKHdHubError> {
Ok(url.to_string())
}
+fn normalize_playback_url_str(raw: &str) -> Option<Url> {
+ if let Ok(url) = Url::parse(raw) {
+ return Some(url);
+ }
+ let (scheme_host, rest) = {
+ let idx = raw.find("://")?;
+ let after_scheme = &raw[idx + 3..];
+ let host_end = after_scheme
+ .find(['/', '?', '#'])
+ .unwrap_or(after_scheme.len());
+ let host = &after_scheme[..host_end];
+ if host.is_empty() || host.contains(' ') {
+ return None;
+ }
+ (&raw[..idx + 3 + host_end], &after_scheme[host_end..])
+ };
+
+ let (path_part, query_fragment) = if let Some(pos) = rest.find(['?', '#']) {
+ (&rest[..pos], &rest[pos..])
+ } else {
+ (rest, "")
+ };
+
+ let encoded_path = path_part
+ .split('/')
+ .map(|segment| {
+ segment
+ .split(':')
+ .map(|sub| {
+ percent_encoding::utf8_percent_encode(sub, percent_encoding::NON_ALPHANUMERIC)
+ .to_string()
+ })
+ .collect::<Vec<_>>()
+ .join(":")
+ })
+ .collect::<Vec<_>>()
+ .join("/");
+
+ let full = format!("{}{}{}", scheme_host, encoded_path, query_fragment);
+ Url::parse(&full).ok()
+}
+
fn is_public_ip(address: IpAddr) -> bool {
match address {
IpAddr::V4(address) => {
@@ -211,15 +254,31 @@ fn is_public_ip(address: IpAddr) -> bool {
}
}
-fn score(url: &str, label: &str) -> u8 {
+pub fn score(url: &str, label: &str) -> u8 {
let value = format!("{} {}", url, label).to_ascii_lowercase();
- if value.contains("pixeldrain") || value.contains("pixel.hubcloud") {
+ if value.contains("googleusercontent.com")
+ || value.contains("googlevideo.com")
+ || value.contains("testzip.php")
+ || value.contains("vcloud.php")
+ || value.contains("drive.php")
+ || value.contains("gpdl.")
+ {
0
- } else if value.contains("gpdl.") || value.contains("googleusercontent") {
+ } else if value.contains("pixeldrain.com")
+ || value.contains("pixeldrain.dev")
+ || value.contains("pixel.hubcloud.")
+ || value.contains("pixeldrain")
+ {
1
- } else if value.contains("workers.dev") || value.contains("r2.dev") {
+ } else if value.contains("storage.googleapis.com")
+ || value.contains("hubcloud.cx/re/")
+ || value.contains("hubcloud.fans/re/")
+ {
2
- } else if value.contains("latent.click") || value.contains("fsl") {
+ } else if value.contains("workers.dev")
+ || value.contains("r2.dev")
+ || value.contains("terapiyo")
+ {
3
} else {
4
@@ -234,3 +293,48 @@ fn clean_label(label: &str) -> String {
clean
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn validates_and_encodes_unencoded_playback_paths() {
+ let raw = "https://cdn.example.com/0:/Game of Thrones/Game.of.Thrones.S01E01.[1080p].mkv";
+ let validated = validate_playback_url(raw).expect("valid url with spaces");
+ assert!(validated.starts_with("https://cdn.example.com/0:/Game%20of%20Thrones/"));
+ assert!(validated.ends_with(".mkv"));
+ }
+
+ #[test]
+ fn rejects_invalid_and_insecure_playback_urls() {
+ assert!(validate_playback_url("http://insecure.com/file.mkv").is_err());
+ assert!(validate_playback_url("https://localhost/file.mkv").is_err());
+ assert!(validate_playback_url("https://127.0.0.1/file.mkv").is_err());
+ assert!(validate_playback_url("https://192.168.1.100/file.mkv").is_err());
+ assert!(validate_playback_url("https://example.com/archive.zip").is_err());
+ assert!(validate_playback_url("https://example.com/login.php").is_err());
+ }
+
+ #[test]
+ fn scores_mirrors_by_priority() {
+ assert_eq!(
+ score("https://hubcloud.cx/testzip.php?id=123", "Fast Direct"),
+ 0
+ );
+ assert_eq!(score("https://gpdl.example.com/stream", "Google Drive"), 0);
+ assert_eq!(
+ score("https://pixeldrain.com/api/file/abc?download", "PixelDrain"),
+ 1
+ );
+ assert_eq!(
+ score("https://storage.googleapis.com/bucket/file.mkv", "Storage"),
+ 2
+ );
+ assert_eq!(
+ score("https://worker.sub.workers.dev/file.mkv", "Cloudflare"),
+ 3
+ );
+ assert_eq!(score("https://unknown-mirror.org/file.mkv", "Unknown"), 4);
+ }
+}
diff --git a/src/providers/fourkhdhub/mod.rs b/src/providers/fourkhdhub/mod.rs
index 96b8fb0..ebed538 100644
--- a/src/providers/fourkhdhub/mod.rs
+++ b/src/providers/fourkhdhub/mod.rs
@@ -14,7 +14,7 @@ impl From<FourKHdHubError> for ProviderError {
FourKHdHubError::Network(e) => ProviderError::Network(e.to_string()),
FourKHdHubError::InvalidUrl(u) => ProviderError::Parsing(format!("Invalid URL: {u}")),
FourKHdHubError::Parse(p) => ProviderError::Parsing(p),
- FourKHdHubError::NoPlayableMirror(_) => ProviderError::NotFound,
+ FourKHdHubError::NoPlayableMirror(msg) => ProviderError::Unavailable(msg),
}
}
}
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 4df3472..25389f4 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -338,7 +338,7 @@ impl App {
let sender = self.action_sender.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
- std::time::Duration::from_secs(15),
+ std::time::Duration::from_secs(18),
client.resolve_release(&release),
)
.await;
@@ -349,18 +349,16 @@ impl App {
.ok();
}
Ok(Err(error)) => {
- log::error!("stream resolve failed: {error}");
+ log::error!("4KHDHub download resolve failed: {error}");
sender
- .send(Action::SetStatus(format!(
- "Error: Resolve failed: {error}"
- )))
+ .send(Action::SetStatus(format!("Error: 4KHDHub: {error}")))
.ok();
}
Err(_) => {
- log::error!("stream resolve timed out");
+ log::error!("4KHDHub download resolve timed out");
sender
.send(Action::SetStatus(
- "Error: Stream resolve timed out".to_string(),
+ "Error: 4KHDHub download resolution timed out. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox.".to_string(),
))
.ok();
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 1613613..b047df8 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -396,7 +396,7 @@ impl App {
let sender = self.action_sender.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
- std::time::Duration::from_secs(15),
+ std::time::Duration::from_secs(18),
client.resolve_release(&release),
)
.await;
@@ -418,16 +418,14 @@ impl App {
Ok(Err(error)) => {
log::error!("4KHDHub resolve failed: {error}");
sender
- .send(Action::SetStatus(format!(
- "Error: 4KHDHub source failed: {error}"
- )))
+ .send(Action::SetStatus(format!("Error: 4KHDHub: {error}")))
.ok();
}
Err(_) => {
log::error!("4KHDHub resolve timed out");
sender
.send(Action::SetStatus(
- "Error: 4KHDHub source resolve timed out".to_string(),
+ "Error: 4KHDHub stream resolution timed out. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox.".to_string(),
))
.ok();
}
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 63b8bc3..46ea9e3 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -685,11 +685,13 @@ impl App {
self.state.is_resolving_playback = false;
if msg.starts_with("Error:") {
log::error!("{msg}");
- self.state.notify(
- NotificationKind::Error,
- "Operation failed",
- msg.trim_start_matches("Error:").trim(),
- );
+ let body = msg.trim_start_matches("Error:").trim();
+ let title = if body.starts_with("4KHDHub") {
+ "4KHDHub Stream Unavailable"
+ } else {
+ "Operation failed"
+ };
+ self.state.notify(NotificationKind::Error, title, body);
} else {
self.state.set_status_default(msg);
}
diff --git a/tests/error_handling.rs b/tests/error_handling.rs
index 80ab2df..1f2507a 100644
--- a/tests/error_handling.rs
+++ b/tests/error_handling.rs
@@ -64,7 +64,7 @@ async fn test_stream_resolve_failure_resets_resolving_flag_and_notifies_user() {
app.state_mut().is_resolving_playback = true;
app.handle_action(Action::SetStatus(
- "Error: 4KHDHub source failed: Stream extraction returned HTTP 403 Forbidden".to_string(),
+ "Error: 4KHDHub: Mirrors for this release are dead or expired on 4KHDHub. Select another release (e.g. 1080p) or press Ctrl+P for MovieBox.".to_string(),
))
.await;
@@ -72,10 +72,11 @@ async fn test_stream_resolve_failure_resets_resolving_flag_and_notifies_user() {
assert!(!app.state().notifications.is_empty());
let notif = app.state().notifications.back().unwrap();
assert_eq!(notif.kind, NotificationKind::Error);
+ assert_eq!(notif.title, "4KHDHub Stream Unavailable");
assert!(
notif
.message
- .contains("Stream extraction returned HTTP 403")
+ .contains("Mirrors for this release are dead or expired")
);
}
diff --git a/tests/live_stream_verification.rs b/tests/live_stream_verification.rs
index d09ab5f..67a351f 100644
--- a/tests/live_stream_verification.rs
+++ b/tests/live_stream_verification.rs
@@ -90,3 +90,89 @@ async fn test_live_series_resolutions_and_streams() {
"Should find at least one real episode stream"
);
}
+
+#[tokio::test]
+#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
+async fn test_live_fourkhdhub_movie_resolution() {
+ let client = moviebox_tui::providers::fourkhdhub::FourKHdHubClient::new()
+ .expect("fourkhdhub client creation");
+ let items = client.search("Inception").await.expect("search Inception");
+ assert!(!items.is_empty(), "Inception search should return results");
+
+ let target = &items[0];
+ println!("Found item: {} ({:?})", target.title, target.id);
+ let releases = client
+ .releases(&target.id.value, 0, 0)
+ .await
+ .expect("fetch movie releases");
+ assert!(!releases.is_empty(), "releases should not be empty");
+
+ for release in &releases {
+ println!("Attempting resolve for: {}", release.filename);
+ let start = std::time::Instant::now();
+ match client.resolve_release(release).await {
+ Ok(source) => {
+ println!(
+ "Resolved in {:?}: {} [{}]",
+ start.elapsed(),
+ source.url,
+ source.source_label
+ );
+ assert!(source.url.starts_with("https://"));
+ break;
+ }
+ Err(e) => {
+ println!("Failed fast in {:?}: {e}", start.elapsed());
+ assert!(start.elapsed() < std::time::Duration::from_secs(8));
+ }
+ }
+ }
+}
+
+#[tokio::test]
+#[ignore = "live network test; run with cargo test --test live_stream_verification -- --ignored"]
+async fn test_live_fourkhdhub_game_of_thrones_resolution() {
+ let client = moviebox_tui::providers::fourkhdhub::FourKHdHubClient::new()
+ .expect("fourkhdhub client creation");
+ let items = client
+ .search("Game of Thrones")
+ .await
+ .expect("search Game of Thrones");
+ assert!(!items.is_empty(), "Game of Thrones search results");
+
+ let target = items
+ .iter()
+ .find(|item| item.title.to_lowercase().contains("thrones"))
+ .expect("Game of Thrones entry");
+ println!("Found series: {} ({:?})", target.title, target.id);
+
+ let releases = client
+ .releases(&target.id.value, 1, 1)
+ .await
+ .expect("releases for S01E01");
+ assert!(!releases.is_empty(), "S01E01 releases found");
+
+ for release in &releases {
+ println!(
+ "Attempting resolve for S01E01 release: {}",
+ release.filename
+ );
+ let start = std::time::Instant::now();
+ match client.resolve_release(release).await {
+ Ok(source) => {
+ println!(
+ "SUCCESS in {:?}: {} [{}]",
+ start.elapsed(),
+ source.url,
+ source.source_label
+ );
+ assert!(source.url.starts_with("https://"));
+ break;
+ }
+ Err(e) => {
+ println!("Failed fast in {:?}: {e}", start.elapsed());
+ assert!(start.elapsed() < std::time::Duration::from_secs(8));
+ }
+ }
+ }
+}
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index fd09126..8a850b5 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -602,7 +602,7 @@ async fn test_esc_in_normal_mode_focuses_search_bar_when_results_present() {
}
#[tokio::test]
-async fn test_esc_in_editing_mode_switches_to_normal_when_results_present() {
+async fn test_esc_in_editing_mode_clears_search_and_switches_to_normal() {
let mut app = App::new();
app.state_mut().active_screen = Screen::Home;
app.state_mut().input_mode = InputMode::Editing;
@@ -622,8 +622,8 @@ async fn test_esc_in_editing_mode_switches_to_normal_when_results_present() {
app.handle_action(Action::Key(esc_key)).await;
assert_eq!(app.state().input_mode, InputMode::Normal);
- assert_eq!(app.state().search_results.len(), 1);
- assert_eq!(app.state().search_query, "matrix");
+ assert!(app.state().search_results.is_empty());
+ assert!(app.state().search_query.is_empty());
}
#[tokio::test]