Skip to content

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

feat(playback): support android intent streaming via loopback proxy

Samir Hossainsf0ed35c28d30
diff --git a/docs/known-issues.md b/docs/known-issues.md
index 630b894..5aa82a6 100644
--- a/docs/known-issues.md
+++ b/docs/known-issues.md
@@ -4,11 +4,11 @@ Tracked here so future work and issue reports reference the same facts.
## Latent / by-design
-- **`supports_headers` is compatibility policy, not just a parser guard.** Sources that
- carry authentication headers (e.g. MovieBox CloudFront signed cookies) exercise it for Android intent and VLC playback.
- Android intent and VLC players support unauthenticated streams (CircleFTP, DhakaFlix, IPTV, direct streams) as well as streams
- with standard `referer`/`user-agent` headers (4KHDHub). Streams requiring custom cookies or auth tokens trip the compatibility
- gate and guide the user to mpv. Keep `player.rs::supports_headers` in sync with VLC and Android opener capabilities.
+- **`supports_headers` routes authenticated streams via loopback proxy.** Sources that
+ carry authentication headers (e.g. MovieBox CloudFront signed cookies) automatically
+ route through the local detached HTTP loopback proxy (`src/proxy.rs`) for both VLC and
+ Android Intent playback, streaming video chunks over localhost without requiring player-side
+ cookie support.
- **BDIX clients use nested `if let Ok` pyramids** in search handling; they work and
are logged, but are harder to read. Flattening is deferred (behavior-neutral refactor
with moderate churn).
diff --git a/src/main.rs b/src/main.rs
index 4abfa8f..bd10adb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -74,9 +74,10 @@ async fn main() -> std::io::Result<()> {
.get(pos + 2)
.cloned()
.unwrap_or_else(|| "[]".to_string());
+ let sub_url = args.get(pos + 3).cloned().filter(|s| !s.is_empty());
let headers: Vec<(String, String)> =
serde_json::from_str(&headers_json).unwrap_or_default();
- moviebox_tui::proxy::run_sidecar(target_url, headers).await;
+ moviebox_tui::proxy::run_sidecar(target_url, headers, sub_url).await;
return Ok(());
}
if args.iter().any(|arg| arg == "--help" || arg == "-h") {
diff --git a/src/player.rs b/src/player.rs
index 9a82090..8462d12 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -77,20 +77,23 @@ pub fn supports_headers(kind: PlayerKind, headers: &[(String, String)]) -> bool
PlayerKind::Mpv => true,
PlayerKind::Iina => true,
PlayerKind::Vlc => true,
- PlayerKind::AndroidIntent => headers.iter().all(|(name, _)| {
- name.eq_ignore_ascii_case("referer") || name.eq_ignore_ascii_case("user-agent")
- }),
+ PlayerKind::AndroidIntent => true,
}
}
pub fn header_capable_players() -> &'static [PlayerKind] {
#[cfg(target_os = "macos")]
{
- &[PlayerKind::Mpv, PlayerKind::Iina, PlayerKind::Vlc]
+ &[
+ PlayerKind::Mpv,
+ PlayerKind::Iina,
+ PlayerKind::Vlc,
+ PlayerKind::AndroidIntent,
+ ]
}
#[cfg(not(target_os = "macos"))]
{
- &[PlayerKind::Mpv, PlayerKind::Vlc]
+ &[PlayerKind::Mpv, PlayerKind::Vlc, PlayerKind::AndroidIntent]
}
}
@@ -240,7 +243,14 @@ fn append_android_intent_extras(
) {
if let Some(sub) = subtitle {
cmd.arg("-e").arg("subtitles_location").arg(sub);
+ cmd.arg("--eu").arg("subtitles_location").arg(sub);
cmd.arg("-e").arg("subs").arg(sub);
+ cmd.arg("--esal").arg("subs").arg(sub);
+ cmd.arg("-e").arg("subs.enable").arg(sub);
+ cmd.arg("--esal").arg("subs.enable").arg(sub);
+ cmd.arg("-e").arg("sub").arg(sub);
+ cmd.arg("--eu").arg("sub").arg(sub);
+ cmd.arg("-e").arg("title_subtitle").arg(sub);
}
for (name, value) in headers {
if name.eq_ignore_ascii_case("user-agent") {
@@ -1412,9 +1422,9 @@ mod tests {
}
#[test]
- fn header_support_rejects_android_cookies_and_allows_vlc_proxy() {
+ fn header_support_allows_android_cookies_and_vlc_proxy() {
let headers = vec![("Cookie".into(), "session=secret".into())];
- assert!(!supports_headers(PlayerKind::AndroidIntent, &headers));
+ assert!(supports_headers(PlayerKind::AndroidIntent, &headers));
assert!(supports_headers(PlayerKind::Vlc, &headers));
assert!(supports_headers(
PlayerKind::Vlc,
diff --git a/src/proxy.rs b/src/proxy.rs
index 56a22f0..a7c0343 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -28,16 +28,21 @@ impl Drop for ConnectionGuard {
}
}
-pub fn spawn_sidecar(target_url: &str, headers: &[(String, String)]) -> Result<String, String> {
+pub fn spawn_sidecar(
+ target_url: &str,
+ headers: &[(String, String)],
+ subtitle_url: Option<&str>,
+) -> Result<String, String> {
let exe = std::env::current_exe()
.ok()
.or_else(|| std::env::args().next().map(PathBuf::from))
.ok_or_else(|| "unable to locate current executable".to_string())?;
let headers_json = serde_json::to_string(headers).unwrap_or_else(|_| "[]".to_string());
+ let sub_arg = subtitle_url.unwrap_or("");
let mut cmd = Command::new(exe);
- cmd.args(["--proxy-for-vlc", target_url, &headers_json]);
+ cmd.args(["--proxy-for-vlc", target_url, &headers_json, sub_arg]);
cmd.stdin(Stdio::null());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::null());
@@ -100,7 +105,11 @@ pub fn spawn_sidecar(target_url: &str, headers: &[(String, String)]) -> Result<S
Ok(format!("http://127.0.0.1:{port}{proxy_path}"))
}
-pub async fn run_sidecar(target_url: String, headers: Vec<(String, String)>) {
+pub async fn run_sidecar(
+ target_url: String,
+ headers: Vec<(String, String)>,
+ subtitle_url: Option<String>,
+) {
let client = crate::net::http_client_builder()
.connect_timeout(Duration::from_secs(15))
.build()
@@ -163,13 +172,21 @@ pub async fn run_sidecar(target_url: String, headers: Vec<(String, String)>) {
}
}
+ let sub_opt = subtitle_url.clone();
tokio::spawn(async move {
let _guard = ConnectionGuard {
conns: active_conns,
activity,
};
- let _ =
- handle_connection(stream, port, &client, &headers, target_host.as_deref()).await;
+ let _ = handle_connection(
+ stream,
+ port,
+ &client,
+ &headers,
+ target_host.as_deref(),
+ sub_opt.as_deref(),
+ )
+ .await;
});
}
}
@@ -192,6 +209,7 @@ async fn handle_connection(
client: &reqwest::Client,
auth_headers: &[(String, String)],
target_host: Option<&str>,
+ subtitle_url: Option<&str>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let (reader, mut writer) = stream.into_split();
let mut buf_reader = BufReader::new(reader);
@@ -312,7 +330,7 @@ async fn handle_connection(
return Ok(());
}
let manifest_str = String::from_utf8_lossy(&manifest_bytes);
- let rewritten = rewrite_dash_manifest(&manifest_str, proxy_port, target_host);
+ let rewritten = rewrite_dash_manifest(&manifest_str, proxy_port, target_host, subtitle_url);
let rewritten_bytes = rewritten.as_bytes();
let headers_out = format!(
@@ -338,6 +356,16 @@ async fn handle_connection(
.await?;
}
}
+ writer
+ .write_all(b"Access-Control-Allow-Origin: *\r\n")
+ .await?;
+ if target_url.ends_with(".srt") {
+ writer
+ .write_all(b"Content-Type: application/x-subrip\r\n")
+ .await?;
+ } else if target_url.ends_with(".vtt") {
+ writer.write_all(b"Content-Type: text/vtt\r\n").await?;
+ }
}
writer.write_all(b"Connection: close\r\n\r\n").await?;
@@ -359,6 +387,11 @@ async fn handle_connection(
fn extract_target_url(path_and_query: &str) -> Option<String> {
let raw = path_and_query.strip_prefix('/')?;
+ if let Some(rest) = raw.strip_prefix("sub/") {
+ if let Ok(decoded) = percent_encoding::percent_decode_str(rest).decode_utf8() {
+ return Some(decoded.into_owned());
+ }
+ }
if let Some(rest) = raw.strip_prefix("https/") {
Some(format!("https://{rest}"))
} else if let Some(rest) = raw.strip_prefix("http/") {
@@ -382,7 +415,12 @@ fn extract_target_url(path_and_query: &str) -> Option<String> {
}
}
-fn rewrite_dash_manifest(manifest: &str, proxy_port: u16, target_host: Option<&str>) -> String {
+fn rewrite_dash_manifest(
+ manifest: &str,
+ proxy_port: u16,
+ target_host: Option<&str>,
+ subtitle_url: Option<&str>,
+) -> String {
let Some(host) = target_host else {
return manifest.to_string();
};
@@ -393,9 +431,31 @@ fn rewrite_dash_manifest(manifest: &str, proxy_port: u16, target_host: Option<&s
let proxy_https = format!("http://127.0.0.1:{proxy_port}/https/{host}/");
let proxy_http = format!("http://127.0.0.1:{proxy_port}/http/{host}/");
- manifest
+ let mut rewritten = manifest
.replace(&https_prefix, &proxy_https)
- .replace(&http_prefix, &proxy_http)
+ .replace(&http_prefix, &proxy_http);
+
+ if let Some(sub) = subtitle_url {
+ if !sub.is_empty() {
+ let encoded_sub =
+ percent_encoding::utf8_percent_encode(sub, percent_encoding::NON_ALPHANUMERIC);
+ let sub_proxy_url = format!("http://127.0.0.1:{proxy_port}/sub/{encoded_sub}");
+ let sub_adaptation_set = format!(
+ r#"<AdaptationSet contentType="text" mimeType="text/vtt" lang="en">
+ <Role schemeIdUri="urn:mpeg:dash:role:2011" value="subtitle"/>
+ <Representation id="sub_en" bandwidth="1000">
+ <BaseURL>{sub_proxy_url}</BaseURL>
+ </Representation>
+ </AdaptationSet>
+</Period>"#
+ );
+ if rewritten.contains("</Period>") {
+ rewritten = rewritten.replacen("</Period>", &sub_adaptation_set, 1);
+ }
+ }
+ }
+
+ rewritten
}
#[cfg(test)]
@@ -449,7 +509,7 @@ mod tests {
</Period>
</MPD>"#;
- let rewritten = rewrite_dash_manifest(manifest, 8888, Some("sacdn.example.com"));
+ let rewritten = rewrite_dash_manifest(manifest, 8888, Some("sacdn.example.com"), None);
assert!(
rewritten.contains("https://standards.iso.org/schema.xsd"),
@@ -475,7 +535,7 @@ mod tests {
#[test]
fn test_rewrite_dash_manifest_with_explicit_port() {
let manifest = r#"<MPD><Period><BaseURL>https://cdn.example.com:8080/dash/seg.mp4</BaseURL></Period></MPD>"#;
- let rewritten = rewrite_dash_manifest(manifest, 9999, Some("cdn.example.com:8080"));
+ let rewritten = rewrite_dash_manifest(manifest, 9999, Some("cdn.example.com:8080"), None);
assert!(
rewritten.contains("http://127.0.0.1:9999/https/cdn.example.com:8080/dash/seg.mp4"),
"Port must be preserved in proxy route"
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 9b7b3f8..dd15094 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -303,11 +303,13 @@ impl App {
let mut temporary_subtitle = None;
if matches!(
kind,
- crate::tui::state::PlayerKind::Vlc | crate::tui::state::PlayerKind::Iina
- ) && let Some(url) = subtitle
+ crate::tui::state::PlayerKind::Vlc
+ | crate::tui::state::PlayerKind::Iina
+ | crate::tui::state::PlayerKind::AndroidIntent
+ ) && let Some(ref url) = subtitle
{
let download_res = crate::service::MovieBoxService::new()
- .download_subtitle_file(&url, &headers)
+ .download_subtitle_file(url, &headers)
.await;
match download_res {
Ok(path) => {
@@ -319,7 +321,7 @@ impl App {
log::warn!(
"subtitle download failed for {:?} player, playing without subtitles (url was {})",
kind,
- crate::logging::sanitize_url(&url)
+ crate::logging::sanitize_url(url)
);
let _ = sender.send(Action::SetStatus(
"External subtitle unavailable; playing stream directly.".to_string(),
@@ -332,31 +334,55 @@ impl App {
.as_ref()
.map(|(p, s, se, ep)| (p.as_str(), s.as_str(), *se, *ep));
- let needs_proxy = matches!(kind, crate::tui::state::PlayerKind::Vlc)
- && headers.iter().any(|(name, _)| {
- !name.eq_ignore_ascii_case("referer")
- && !name.eq_ignore_ascii_case("user-agent")
- });
+ let needs_proxy = matches!(
+ kind,
+ crate::tui::state::PlayerKind::Vlc | crate::tui::state::PlayerKind::AndroidIntent
+ ) && headers.iter().any(|(name, _)| {
+ !name.eq_ignore_ascii_case("referer") && !name.eq_ignore_ascii_case("user-agent")
+ });
- let effective_link = if needs_proxy {
- match crate::proxy::spawn_sidecar(&link, &headers) {
- Ok(local_url) => local_url,
+ let (effective_link, effective_subtitle) = if needs_proxy {
+ match crate::proxy::spawn_sidecar(&link, &headers, subtitle.as_deref()) {
+ Ok(local_url) => {
+ let sub_url =
+ if matches!(kind, crate::tui::state::PlayerKind::AndroidIntent) {
+ if let Some(remote_sub) = &subtitle {
+ if let Some(authority) = local_url
+ .strip_prefix("http://")
+ .and_then(|s| s.split('/').next())
+ {
+ let encoded = percent_encoding::utf8_percent_encode(
+ remote_sub,
+ percent_encoding::NON_ALPHANUMERIC,
+ );
+ Some(format!("http://{authority}/sub/{encoded}"))
+ } else {
+ local_subtitle.clone()
+ }
+ } else {
+ local_subtitle.clone()
+ }
+ } else {
+ local_subtitle.clone()
+ };
+ (local_url, sub_url)
+ }
Err(err) => {
- log::error!("Failed to spawn VLC proxy sidecar: {err}");
+ log::error!("Failed to spawn stream proxy sidecar: {err}");
let _ = sender.send(Action::SetStatus(format!(
- "VLC stream initialization failed: {err}"
+ "Stream proxy initialization failed: {err}"
)));
return;
}
}
} else {
- link.clone()
+ (link.clone(), local_subtitle.clone())
};
let mut command = crate::tui::player::command(
kind,
&effective_link,
- local_subtitle.as_deref(),
+ effective_subtitle.as_deref(),
&headers,
window,
resume_seconds,
@@ -1004,12 +1030,10 @@ mod tests {
source_label: "Multi-Res".to_string(),
};
- app.dispatch_playback_or_notify(source);
-
- assert!(!app.state.is_resolving_playback);
- assert!(app.state.pending_playback_source.is_none());
- assert!(!app.state.player_picker_popup);
- assert!(!app.state.notifications.is_empty());
+ assert_eq!(
+ app.resolve_playback_player(&source),
+ super::PlaybackResolution::Available(crate::tui::state::PlayerKind::AndroidIntent)
+ );
}
#[tokio::test]
async fn test_explicit_player_incompatible_does_not_launch_alternative() {
@@ -1031,27 +1055,12 @@ mod tests {
let resolution = app.resolve_playback_player(&source);
assert_eq!(
resolution,
- super::PlaybackResolution::ExplicitPlayerIncompatible {
- chosen: crate::tui::state::PlayerKind::AndroidIntent,
- compatible_alternatives: vec![crate::tui::state::PlayerKind::Mpv],
- }
+ super::PlaybackResolution::Available(crate::tui::state::PlayerKind::AndroidIntent)
);
app.state.is_resolving_playback = true;
app.dispatch_playback_or_notify(source);
-
- assert!(!app.state.is_resolving_playback);
assert!(app.state.pending_playback_source.is_none());
- assert!(!app.state.player_picker_popup);
-
- let notification = app.state.notifications.back().expect("notification posted");
- assert_eq!(notification.title, "Android Player Incompatible");
- assert!(
- notification
- .message
- .contains("Android Player lacks header support")
- );
- assert!(notification.message.contains("mpv"));
}
#[tokio::test]
@@ -1134,10 +1143,7 @@ mod tests {
};
assert_eq!(
app.resolve_playback_player(&auth_source),
- super::PlaybackResolution::ExplicitPlayerIncompatible {
- chosen: crate::tui::state::PlayerKind::AndroidIntent,
- compatible_alternatives: vec![],
- }
+ super::PlaybackResolution::Available(crate::tui::state::PlayerKind::AndroidIntent)
);
}