Skip to content

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

fix(fourkhdhub): resolve mediator redirectors and separate playback mirrors

Samir Hossainse2bc2b1a8729
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1247f5c..8e3a19c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -30,11 +30,22 @@
- **Concise Error and Status Messaging**:
- Streamlined `ProviderError::user_message` to output compact, high-signal status messages under 40 characters for mobile and compact viewports.
- Replaced sprawling raw socket errors and leaked endpoint URLs with clear failure reasons (`CircleFTP unreachable: requires BDIX network.`, `MovieBox timed out.`, `Cannot reach 4KHDHub.`, `No results found.`).
- - Shortened 4KHDHub playback and download resolution timeout messages to fit single-row status lines (`4KHDHub timed out. Try another release or Ctrl+P.`).
+ - Shortened 4KHDHub playback and download resolution timeout messages to fit single-row status lines (`4KHDHub timed out.`).
- Sanitized subtitle download/write error strings to prevent raw filesystem/network error leaks.
- Compacted addon torrent stream warning to `Blocked {} torrent streams. HTTP only.`.
- Streamlined player crash fallback diagnostic to `Player exited (code {code}).`.
### Fixed
+- **In-Flight Notification Replacement & Compact Stream Errors**:
+ - Generalized notification category matching in `AppState::notify` across stream and playback domains, ensuring stream resolution errors replace in-flight "Preparing playback" toasts in-place instead of creating visual overlapping.
+ - Compacted 4KHDHub stream error messages from 135-character redundant text blocks to concise messages under 30 characters (`Mirrors dead or expired.`).
+- **4KHDHub Mediator Redirector Resolution**:
+ - Implemented automatic mediator unpacker in `src/providers/fourkhdhub/hubcloud.rs` supporting `greenmotors.club` and `greenmountmotors.` intermediate redirector domains.
+ - Implemented multi-stage decoding pipeline (double Base64, ROT13, JSON extraction) to transparently recover downstream HubCloud and HubDrive mirror endpoints without external browser dependencies.
+ - Excluded mediator domains from direct file classification in `parser.rs` and added mediator domain rejection to `validate_playback_url`.
+- **Playback vs Download Mirror Resolution Separation**:
+ - Introduced `ResolutionIntent` (`Playback` vs `Download`) in `src/providers/models.rs` and wired through `resolve_release`.
+ - For playback, prioritized seekable multi-connection video CDNs (`pixel.hubcloud.` -> Google Video CDN, Cloudflare R2, PixelDrain API) while deprioritizing single-use download workers (`workers.dev`).
+ - Added `downloadQuotaExceeded` and `Access Denied` error body detection in `FourKHdHubClient::preflight` to instantly reject exhausted worker links and prevent IINA HTTP authentication dialogs.
- **4KHDHub Multi-Stream Deduplication**:
- Fixed an issue where 4KHDHub stream releases were prematurely collapsed into a single item by scoping query-string-insensitive URL deduplication strictly to MovieBox CDN streams.
- Upgraded 4KHDHub stream cache schema to `v4_` to invalidate stale single-stream caches.
diff --git a/docs/providers.md b/docs/providers.md
index 5fc081a..e5e7668 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -76,7 +76,10 @@ Adding a new streaming or BDIX provider to MovieBox TUI takes 3 simple steps:
- `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 a bounded range probe (`Range: bytes=0-8191`) 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 (Cloudflare R2 / S3 / Seekable Streams → Storage → PixelDrain API → Google UserContent / Direct Attachments), automatically decoding base64 `Watch Online` mirrors (`vdplay.pages.dev/?u=...`).
+- `hubcloud.rs` scores and prioritizes candidate streams based on `ResolutionIntent`:
+ - **Playback (`ResolutionIntent::Playback`)**: Prioritizes seekable multi-connection streaming CDNs (`pixel.hubcloud.` -> Google Video CDN, Cloudflare R2, PixelDrain API) while deprioritizing single-use download workers (`workers.dev`) to prevent HTTP 403 token-burn and player authentication popups.
+ - **Download (`ResolutionIntent::Download`)**: Permits both high-speed streaming CDNs and direct file download proxies for maximum throughput.
+- **Mediator Redirector Resolution**: `hubcloud.rs::resolve_greenmotors` transparently unpacks intermediate JavaScript mediator domains (`greenmotors.club`, `greenmountmotors.`) using a multi-stage decoding pipeline (double Base64, ROT13, JSON extraction) to recover downstream `hubcloud.` and `hubdrive.` mirror endpoints without requiring an external browser engine.
- **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,
diff --git a/src/providers/fourkhdhub/client.rs b/src/providers/fourkhdhub/client.rs
index c4561e7..bc742bb 100644
--- a/src/providers/fourkhdhub/client.rs
+++ b/src/providers/fourkhdhub/client.rs
@@ -1,5 +1,7 @@
use super::{hubcloud, parser};
-use crate::providers::models::{CatalogItem, MediaDetails, PlaybackSource, ProviderKind, Release};
+use crate::providers::models::{
+ CatalogItem, MediaDetails, PlaybackSource, ProviderKind, Release, ResolutionIntent,
+};
use reqwest::Url;
const DEFAULT_BASE_URL: &str = "https://4khdhub.one/";
@@ -16,6 +18,16 @@ pub enum FourKHdHubError {
#[error("no playable mirrors: {0}")]
NoPlayableMirror(String),
}
+impl FourKHdHubError {
+ pub fn user_message(&self) -> &'static str {
+ match self {
+ Self::Network(_) => "Cannot reach 4KHDHub.",
+ Self::InvalidUrl(_) => "Invalid 4KHDHub URL.",
+ Self::Parse(_) => "4KHDHub parse error.",
+ Self::NoPlayableMirror(_) => "Mirrors dead or expired.",
+ }
+ }
+}
#[derive(Clone)]
pub struct FourKHdHubClient {
@@ -80,6 +92,7 @@ impl FourKHdHubClient {
pub async fn resolve_release(
&self,
release: &Release,
+ intent: ResolutionIntent,
) -> Result<PlaybackSource, FourKHdHubError> {
if release.provider != ProviderKind::FourKHdHub {
return Err(FourKHdHubError::Parse(
@@ -95,15 +108,19 @@ impl FourKHdHubClient {
async move {
let fetch = async {
if mirror_url.contains("hubcloud.") {
- hubcloud::resolve(&client, &mirror_url).await
+ hubcloud::resolve(&client, &mirror_url, intent).await
} else if mirror_url.contains("hubdrive.") {
- hubcloud::resolve_hubdrive(&client, &mirror_url).await
+ hubcloud::resolve_hubdrive(&client, &mirror_url, intent).await
+ } else if mirror_url.contains("greenmotors.")
+ || mirror_url.contains("greenmountmotors.")
+ {
+ hubcloud::resolve_greenmotors(&client, &mirror_url, intent).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)
+ tokio::time::timeout(std::time::Duration::from_millis(7000), fetch)
.await
.map_err(|_| {
FourKHdHubError::NoPlayableMirror("mirror resolver timed out".into())
@@ -116,7 +133,7 @@ impl FourKHdHubClient {
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);
+ let score = hubcloud::score(&url, &label, intent);
candidates.push((score, url, label, headers));
}
}
@@ -219,6 +236,9 @@ impl FourKHdHubClient {
|| body_lower.contains("404 not found")
|| body_lower.contains("link has expired")
|| body_lower.contains("expired")
+ || body_lower.contains("access denied")
+ || body_lower.contains("downloadquotaexceeded")
+ || body_lower.contains("generate link again")
{
return Err(FourKHdHubError::NoPlayableMirror(
"upstream mirror reported expired file link".into(),
@@ -264,6 +284,9 @@ impl FourKHdHubClient {
|| wrapped_lower.contains("file not found")
|| wrapped_lower.contains("404 not found")
|| wrapped_lower.contains("expired")
+ || wrapped_lower.contains("access denied")
+ || wrapped_lower.contains("downloadquotaexceeded")
+ || wrapped_lower.contains("generate link again")
{
return Err(FourKHdHubError::NoPlayableMirror(
"upstream mirror reported expired file link".into(),
@@ -330,7 +353,12 @@ mod tests {
mirrors: Vec::new(),
resource_id: None,
};
- assert!(client.resolve_release(&release).await.is_err());
+ assert!(
+ client
+ .resolve_release(&release, ResolutionIntent::Playback)
+ .await
+ .is_err()
+ );
}
#[test]
diff --git a/src/providers/fourkhdhub/hubcloud.rs b/src/providers/fourkhdhub/hubcloud.rs
index a8bb653..a6b22db 100644
--- a/src/providers/fourkhdhub/hubcloud.rs
+++ b/src/providers/fourkhdhub/hubcloud.rs
@@ -1,4 +1,5 @@
use super::client::FourKHdHubError;
+use crate::providers::models::ResolutionIntent;
use reqwest::Url;
use scraper::{Html, Selector};
use std::net::IpAddr;
@@ -12,6 +13,7 @@ static SEL_LINKS: LazyLock<Selector> = LazyLock::new(|| Selector::parse("a[href]
pub async fn resolve(
client: &reqwest::Client,
drive_url: &str,
+ intent: ResolutionIntent,
) -> Result<Vec<(String, String, Vec<(String, String)>)>, FourKHdHubError> {
validate_resolver_url(drive_url)?;
let drive_html = client
@@ -42,7 +44,13 @@ pub async fn resolve(
let mut candidates = extract_script_pixeldrain_urls(&resolver_html)
.into_iter()
- .map(|url| (score(&url, "PixelDrain"), url, "PixelDrain".to_string()))
+ .map(|url| {
+ (
+ score(&url, "PixelDrain", intent),
+ url,
+ "PixelDrain".to_string(),
+ )
+ })
.collect::<Vec<_>>();
candidates.extend(
resolver
@@ -54,14 +62,14 @@ pub async fn resolve(
&& let Ok(valid) = validate_playback_url(&unwrapped)
{
return Some((
- score(&valid, "Watch Online"),
+ score(&valid, "Watch Online", intent),
valid,
"Watch Online".to_string(),
));
}
validate_playback_url(href).ok().map(|url| {
let url = pixeldrain_api_url(&url).unwrap_or(url);
- (score(&url, &label), url, clean_label(&label))
+ (score(&url, &label, intent), url, clean_label(&label))
})
})
.collect::<Vec<_>>(),
@@ -84,6 +92,7 @@ pub async fn resolve(
pub async fn resolve_hubdrive(
client: &reqwest::Client,
drive_url: &str,
+ intent: ResolutionIntent,
) -> Result<Vec<(String, String, Vec<(String, String)>)>, FourKHdHubError> {
validate_hubdrive_url(drive_url)?;
let html = client
@@ -95,7 +104,111 @@ pub async fn resolve_hubdrive(
.await?;
let hubcloud_url = extract_hubcloud_drive_url(&html)
.ok_or_else(|| FourKHdHubError::Parse("HubDrive HubCloud mirror missing".into()))?;
- resolve(client, &hubcloud_url).await
+ resolve(client, &hubcloud_url, intent).await
+}
+
+pub async fn resolve_greenmotors(
+ client: &reqwest::Client,
+ drive_url: &str,
+ intent: ResolutionIntent,
+) -> Result<Vec<(String, String, Vec<(String, String)>)>, FourKHdHubError> {
+ validate_greenmotors_url(drive_url)?;
+ let html = client
+ .get(drive_url)
+ .send()
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ let target_url = unpack_greenmotors_url(&html)
+ .ok_or_else(|| FourKHdHubError::Parse("GreenMotors mirror target missing".into()))?;
+ if target_url.contains("hubcloud.") {
+ resolve(client, &target_url, intent).await
+ } else if target_url.contains("hubdrive.") {
+ resolve_hubdrive(client, &target_url, intent).await
+ } else {
+ validate_playback_url(&target_url).map(|url| vec![(url, "Direct".to_string(), Vec::new())])
+ }
+}
+
+fn validate_greenmotors_url(raw: &str) -> Result<(), FourKHdHubError> {
+ let url = Url::parse(raw).map_err(|_| FourKHdHubError::InvalidUrl(raw.into()))?;
+ let host = url.host_str().unwrap_or_default();
+ if url.scheme() != "https"
+ || (!host.contains("greenmotors.") && !host.contains("greenmountmotors."))
+ {
+ return Err(FourKHdHubError::InvalidUrl(raw.into()));
+ }
+ Ok(())
+}
+
+fn unpack_greenmotors_url(html: &str) -> Option<String> {
+ let payload = extract_greenmotors_payload(html)?;
+ decode_greenmotors_payload(&payload)
+}
+
+fn extract_greenmotors_payload(html: &str) -> Option<String> {
+ let needle = "s(";
+ let mut search_idx = 0;
+ while let Some(pos) = html[search_idx..].find(needle) {
+ let abs_pos = search_idx + pos + needle.len();
+ let rest = html[abs_pos..].trim_start();
+ let after_key = if let Some(stripped) = rest.strip_prefix("'o'") {
+ stripped
+ } else if let Some(stripped) = rest.strip_prefix("\"o\"") {
+ stripped
+ } else {
+ search_idx = abs_pos;
+ continue;
+ };
+ let after_comma = if let Some(stripped) = after_key.trim_start().strip_prefix(',') {
+ stripped
+ } else {
+ search_idx = abs_pos;
+ continue;
+ };
+ let trimmed = after_comma.trim_start();
+ let quote = match trimmed.chars().next() {
+ Some(c @ ('\'' | '"')) => c,
+ _ => {
+ search_idx = abs_pos;
+ continue;
+ }
+ };
+ let payload_slice = &trimmed[1..];
+ if let Some(end) = payload_slice.find(quote) {
+ return Some(payload_slice[..end].to_string());
+ }
+ search_idx = abs_pos;
+ }
+ None
+}
+
+fn rot13(input: &str) -> String {
+ input
+ .chars()
+ .map(|c| match c {
+ 'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char,
+ 'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char,
+ _ => c,
+ })
+ .collect()
+}
+
+fn decode_greenmotors_payload(payload: &str) -> Option<String> {
+ use base64::Engine;
+ let b64 = &base64::engine::general_purpose::STANDARD;
+ let step1_bytes = b64.decode(payload.as_bytes()).ok()?;
+ let step1_str = String::from_utf8(step1_bytes).ok()?;
+ let step2_bytes = b64.decode(step1_str.as_bytes()).ok()?;
+ let step2_str = String::from_utf8(step2_bytes).ok()?;
+ let step3_rot = rot13(&step2_str);
+ let step4_bytes = b64.decode(step3_rot.as_bytes()).ok()?;
+ let step4_str = String::from_utf8(step4_bytes).ok()?;
+ let json_val: serde_json::Value = serde_json::from_str(&step4_str).ok()?;
+ let target_b64 = json_val.get("o")?.as_str()?;
+ let target_bytes = b64.decode(target_b64.as_bytes()).ok()?;
+ String::from_utf8(target_bytes).ok()
}
fn extract_hubcloud_drive_url(html: &str) -> Option<String> {
@@ -217,6 +330,8 @@ pub fn validate_playback_url(raw: &str) -> Result<String, FourKHdHubError> {
|| path.ends_with(".zip")
|| path.contains("login.php")
|| path.contains("logout")
+ || host.contains("greenmotors.")
+ || host.contains("greenmountmotors.")
{
return Err(FourKHdHubError::InvalidUrl(raw.into()));
}
@@ -284,37 +399,72 @@ fn is_public_ip(address: IpAddr) -> bool {
}
}
-pub fn score(url: &str, label: &str) -> u8 {
+pub fn score(url: &str, label: &str, intent: ResolutionIntent) -> u8 {
let value = format!("{} {}", url, label).to_ascii_lowercase();
- if value.contains("cloudflarestorage.com")
- || value.contains("r2.cloudflarestorage.com")
- || value.contains("fsl server")
- || value.contains("r2.dev")
- || value.contains("workers.dev")
- || value.contains("watch online")
- {
- 0
- } else if value.contains("storage.googleapis.com")
- || value.contains("hubcloud.cx/re/")
- || value.contains("hubcloud.fans/re/")
- {
- 1
- } else if value.contains("pixeldrain.com")
- || value.contains("pixeldrain.dev")
- || value.contains("pixel.hubcloud.")
- || value.contains("pixeldrain")
- {
- 2
- } else if value.contains("googleusercontent.com")
- || value.contains("googlevideo.com")
- || value.contains("testzip.php")
- || value.contains("vcloud.php")
- || value.contains("drive.php")
- || value.contains("gpdl.")
- {
- 3
- } else {
- 4
+ match intent {
+ ResolutionIntent::Playback => {
+ if value.contains("pixel.hubcloud.")
+ || value.contains("googleusercontent.com")
+ || value.contains("googlevideo.com")
+ || value.contains("cloudflarestorage.com")
+ || value.contains("r2.cloudflarestorage.com")
+ || value.contains("fsl server")
+ || value.contains("r2.dev")
+ || value.contains("watch online")
+ {
+ 0
+ } else if value.contains("storage.googleapis.com")
+ || value.contains("hubcloud.cx/re/")
+ || value.contains("hubcloud.fans/re/")
+ {
+ 1
+ } else if value.contains("pixeldrain.com")
+ || value.contains("pixeldrain.dev")
+ || value.contains("pixeldrain")
+ {
+ 2
+ } else if value.contains("testzip.php")
+ || value.contains("vcloud.php")
+ || value.contains("drive.php")
+ || value.contains("gpdl.")
+ {
+ 3
+ } else {
+ 4
+ }
+ }
+ ResolutionIntent::Download => {
+ if value.contains("pixel.hubcloud.")
+ || value.contains("googleusercontent.com")
+ || value.contains("cloudflarestorage.com")
+ || value.contains("r2.cloudflarestorage.com")
+ || value.contains("fsl server")
+ || value.contains("r2.dev")
+ || value.contains("workers.dev")
+ || value.contains("watch online")
+ {
+ 0
+ } else if value.contains("storage.googleapis.com")
+ || value.contains("hubcloud.cx/re/")
+ || value.contains("hubcloud.fans/re/")
+ {
+ 1
+ } else if value.contains("pixeldrain.com")
+ || value.contains("pixeldrain.dev")
+ || value.contains("pixeldrain")
+ {
+ 2
+ } else if value.contains("googlevideo.com")
+ || value.contains("testzip.php")
+ || value.contains("vcloud.php")
+ || value.contains("drive.php")
+ || value.contains("gpdl.")
+ {
+ 3
+ } else {
+ 4
+ }
+ }
}
}
@@ -353,28 +503,78 @@ mod tests {
fn scores_mirrors_by_priority() {
assert_eq!(
score(
- "https://c357acb6.r2.cloudflarestorage.com/file.mkv",
- "FSL Server"
+ "https://pixel.hubcloud.ist/?id=123",
+ "Download [Server : 10Gbps]",
+ ResolutionIntent::Playback
),
0
);
assert_eq!(
- score("https://worker.sub.workers.dev/file.mkv", "Cloudflare"),
+ score(
+ "https://worker.sub.workers.dev/file.mkv",
+ "Cloudflare",
+ ResolutionIntent::Playback
+ ),
+ 4
+ );
+ assert_eq!(
+ score(
+ "https://worker.sub.workers.dev/file.mkv",
+ "Cloudflare",
+ ResolutionIntent::Download
+ ),
0
);
assert_eq!(
- score("https://storage.googleapis.com/bucket/file.mkv", "Storage"),
+ score(
+ "https://c357acb6.r2.cloudflarestorage.com/file.mkv",
+ "FSL Server",
+ ResolutionIntent::Playback
+ ),
+ 0
+ );
+ assert_eq!(
+ score(
+ "https://storage.googleapis.com/bucket/file.mkv",
+ "Storage",
+ ResolutionIntent::Playback
+ ),
1
);
assert_eq!(
- score("https://pixeldrain.com/api/file/abc?download", "PixelDrain"),
+ score(
+ "https://pixeldrain.com/api/file/abc?download",
+ "PixelDrain",
+ ResolutionIntent::Playback
+ ),
2
);
assert_eq!(
- score("https://hubcloud.cx/testzip.php?id=123", "Fast Direct"),
- 3
+ score(
+ "https://unknown-mirror.org/file.mkv",
+ "Unknown",
+ ResolutionIntent::Playback
+ ),
+ 4
+ );
+ }
+
+ #[test]
+ fn decodes_greenmotors_payload_pipeline() {
+ let payload = "Y214WE0xWjNZbXRhVUdwMmIxQldObFo2ZFRCeFZVOXRRbmxxYVV0UU9XRndla2w1YjNveGFYRlVPV3h3YkRWM2IxVkpka3RRT1dKdk1qRjViMVJUYUUxVVNXeExVRGgyV1ZCWGFWWjNZblpNU0hWR1dsUkJWa2RIVFZweVIzbHBUVk54V0c1NlYxVkNSMU51UkcxSmFreHRRVVZ4ZVdOV1JtRlBlRzlKU1RKTWJVRkNjbnBCYUVwaGVYbHZlWGswU25vMWVISktXbTFIZDFaMmMwUTlQUT09";
+ let target = decode_greenmotors_payload(payload);
+ assert_eq!(
+ target.as_deref(),
+ Some("https://hubcloud.ist/drive/sssrvrzv1fwrssv")
+ );
+ }
+
+ #[test]
+ fn extracts_greenmotors_script_payload() {
+ let snippet = r#"<script>function s(e,t,i){}s('o','TEST_PAYLOAD_ABC123',180000);</script>"#;
+ assert_eq!(
+ extract_greenmotors_payload(snippet).as_deref(),
+ Some("TEST_PAYLOAD_ABC123")
);
- assert_eq!(score("https://gpdl.example.com/stream", "Google Drive"), 3);
- assert_eq!(score("https://unknown-mirror.org/file.mkv", "Unknown"), 4);
}
}
diff --git a/src/providers/fourkhdhub/parser.rs b/src/providers/fourkhdhub/parser.rs
index 2f04324..928805f 100644
--- a/src/providers/fourkhdhub/parser.rs
+++ b/src/providers/fourkhdhub/parser.rs
@@ -187,7 +187,10 @@ pub fn parse_releases(
label,
resolver_url: href.to_string(),
headers: Vec::new(),
- direct_file: !href.contains("hubcloud.") && !href.contains("hubdrive."),
+ direct_file: !href.contains("hubcloud.")
+ && !href.contains("hubdrive.")
+ && !href.contains("greenmotors.")
+ && !href.contains("greenmountmotors."),
})
})
.collect::<Vec<_>>();
diff --git a/src/providers/mod.rs b/src/providers/mod.rs
index 4bdd8cf..3750a93 100644
--- a/src/providers/mod.rs
+++ b/src/providers/mod.rs
@@ -9,7 +9,7 @@ pub use tv as m3u;
pub use models::{
AudioTrackOption, CatalogItem, Episode, MediaDetails, MediaType, PlaybackSource, ProviderError,
- ProviderKind, ProviderMediaId, Release, Season, SourceMirror, SubtitleOption,
+ ProviderKind, ProviderMediaId, Release, ResolutionIntent, Season, SourceMirror, SubtitleOption,
};
use serde::{Deserialize, Serialize};
diff --git a/src/providers/models.rs b/src/providers/models.rs
index 202c312..cca78c2 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -199,6 +199,11 @@ impl MediaDetails {
}
}
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ResolutionIntent {
+ Playback,
+ Download,
+}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceMirror {
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index dfbb0d5..48de18e 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -532,7 +532,10 @@ impl App {
tokio::spawn(async move {
let result = tokio::time::timeout(
std::time::Duration::from_secs(18),
- client.resolve_release(&release),
+ client.resolve_release(
+ &release,
+ crate::providers::ResolutionIntent::Download,
+ ),
)
.await;
match result {
@@ -548,14 +551,17 @@ impl App {
Ok(Err(error)) => {
log::error!("4KHDHub download resolve failed: {error}");
sender
- .send(Action::SetStatus(format!("Error: 4KHDHub: {error}")))
+ .send(Action::SetStatus(format!(
+ "Error: 4KHDHub: {}",
+ error.user_message()
+ )))
.ok();
}
Err(_) => {
log::error!("4KHDHub download resolve timed out");
sender
.send(Action::SetStatus(
- "Error: 4KHDHub timed out. Try another release or Ctrl+P.".to_string(),
+ "Error: 4KHDHub: Timed out.".to_string(),
))
.ok();
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index e9f1967..da3b619 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -745,7 +745,10 @@ impl App {
tokio::spawn(async move {
let result = tokio::time::timeout(
std::time::Duration::from_secs(18),
- client.resolve_release(&release),
+ client.resolve_release(
+ &release,
+ crate::providers::ResolutionIntent::Playback,
+ ),
)
.await;
match result {
@@ -756,7 +759,10 @@ impl App {
log::error!("4KHDHub resolve failed: {error}");
sender.send(Action::PlayerExited).ok();
sender
- .send(Action::SetStatus(format!("Error: 4KHDHub: {error}")))
+ .send(Action::SetStatus(format!(
+ "Error: 4KHDHub: {}",
+ error.user_message()
+ )))
.ok();
}
Err(_) => {
@@ -764,7 +770,7 @@ impl App {
sender.send(Action::PlayerExited).ok();
sender
.send(Action::SetStatus(
- "Error: 4KHDHub timed out. Try another release or Ctrl+P.".to_string(),
+ "Error: 4KHDHub: Timed out.".to_string(),
))
.ok();
}
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 724ecd5..e188401 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -654,12 +654,17 @@ impl App {
if msg.starts_with("Error:") {
log::error!("{msg}");
let body = msg.trim_start_matches("Error:").trim();
- let title = if body.starts_with("4KHDHub") {
- "4KHDHub Stream Unavailable"
+ let (title, clean_body) = if let Some(rest) = body
+ .strip_prefix("4KHDHub:")
+ .or_else(|| body.strip_prefix("4KHDHub"))
+ {
+ let trimmed = rest.trim_start_matches(':').trim();
+ ("4KHDHub Stream Unavailable", trimmed)
} else {
- "Operation failed"
+ ("Operation failed", body)
};
- self.state.notify(NotificationKind::Error, title, body);
+ self.state
+ .notify(NotificationKind::Error, title, clean_body);
} else {
self.state.set_status_default(msg);
}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 4b8bbbf..96755ff 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -649,35 +649,18 @@ impl AppState {
return true;
}
let is_playback = |s: &str| {
- s.eq_ignore_ascii_case("Playback")
- || s.eq_ignore_ascii_case("Preparing playback")
- || s.eq_ignore_ascii_case("Opening Player")
- || s.eq_ignore_ascii_case("Playback Cancelled")
- || s.eq_ignore_ascii_case("Playback unavailable")
- || s.to_lowercase().contains("player")
- };
- let is_download = |s: &str| {
- s.eq_ignore_ascii_case("Download")
- || s.eq_ignore_ascii_case("Preparing download")
- || s.eq_ignore_ascii_case("Download Started")
- || s.eq_ignore_ascii_case("Download complete")
- || s.eq_ignore_ascii_case("Cancelling download")
- || s.eq_ignore_ascii_case("Download failed")
- || s.to_lowercase().contains("download")
+ let lower = s.to_lowercase();
+ lower.contains("playback")
+ || lower.contains("player")
+ || lower.contains("stream")
+ || lower.contains("mpv")
};
+ let is_download = |s: &str| s.to_lowercase().contains("download");
let is_update = |s: &str| {
- s.eq_ignore_ascii_case("Updates")
- || s.eq_ignore_ascii_case("Checking for updates")
- || s.eq_ignore_ascii_case("Up to date")
- || s.eq_ignore_ascii_case("Update check failed")
- || s.eq_ignore_ascii_case("Homebrew Upgrade")
- };
- let is_cache = |s: &str| {
- s.eq_ignore_ascii_case("Cache")
- || s.eq_ignore_ascii_case("Clearing Cache")
- || s.eq_ignore_ascii_case("Cache Cleared")
- || s.eq_ignore_ascii_case("Cache Clear Failed")
+ let lower = s.to_lowercase();
+ lower.contains("update") || lower.contains("upgrade")
};
+ let is_cache = |s: &str| s.to_lowercase().contains("cache");
(is_playback(a) && is_playback(b))
|| (is_download(a) && is_download(b))
|| (is_update(a) && is_update(b))
@@ -1636,6 +1619,14 @@ mod tests {
assert_eq!(state.notifications.len(), 1);
assert_eq!(state.notifications[0].title, "Opening Player");
+ state.notify(
+ crate::tui::overlay::NotificationKind::Error,
+ "4KHDHub Stream Unavailable",
+ "Mirrors dead or expired.",
+ );
+ assert_eq!(state.notifications.len(), 1);
+ assert_eq!(state.notifications[0].title, "4KHDHub Stream Unavailable");
+ assert_eq!(state.notifications[0].message, "Mirrors dead or expired.");
state.notify(
crate::tui::overlay::NotificationKind::Info,
"Preparing download",
diff --git a/tests/live_stream_verification.rs b/tests/live_stream_verification.rs
index ff695d9..aba6fdd 100644
--- a/tests/live_stream_verification.rs
+++ b/tests/live_stream_verification.rs
@@ -440,7 +440,10 @@ async fn test_live_fourkhdhub_movie_resolution() {
for release in &releases {
println!("Attempting resolve for: {}", release.filename);
let start = std::time::Instant::now();
- match client.resolve_release(release).await {
+ match client
+ .resolve_release(release, moviebox_tui::providers::ResolutionIntent::Playback)
+ .await
+ {
Ok(source) => {
println!(
"Resolved in {:?}: {} [{}]",
@@ -488,7 +491,10 @@ async fn test_live_fourkhdhub_game_of_thrones_resolution() {
release.filename
);
let start = std::time::Instant::now();
- match client.resolve_release(release).await {
+ match client
+ .resolve_release(release, moviebox_tui::providers::ResolutionIntent::Playback)
+ .await
+ {
Ok(source) => {
println!(
"SUCCESS in {:?}: {} [{}]",