Skip to content

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

refactor(core): decouple headless service and models for gui readiness

Samir Hossainscf340860b497
diff --git a/src/lib.rs b/src/lib.rs
index 3b95f3e..02671fd 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -3,7 +3,9 @@ pub mod config;
pub mod download;
pub mod history;
pub mod logging;
+pub mod models;
pub mod player;
pub mod providers;
+pub mod service;
pub mod tui;
pub mod updater;
diff --git a/src/models.rs b/src/models.rs
new file mode 100644
index 0000000..58c7cac
--- /dev/null
+++ b/src/models.rs
@@ -0,0 +1,131 @@
+pub use crate::providers::models::ProviderKind;
+use serde::{Deserialize, Serialize};
+use std::collections::{HashMap, HashSet};
+use std::time::{Duration, Instant};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SearchResult {
+ pub id: String,
+ pub title: String,
+ pub stype: i64,
+ pub release_year: String,
+ pub cover_url: Option<String>,
+ pub season: usize,
+ pub episode: usize,
+ pub provider: ProviderKind,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum BrowseMetric {
+ Trending,
+ Rating,
+ RecentRating,
+ Popularity,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum BrowsePreset {
+ Trending,
+ TopRatedAllTime,
+ TopRatedRecent,
+ MostWatched,
+}
+
+impl BrowsePreset {
+ pub const ALL: [Self; 4] = [
+ Self::Trending,
+ Self::TopRatedAllTime,
+ Self::TopRatedRecent,
+ Self::MostWatched,
+ ];
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Trending => "Trending Now",
+ Self::TopRatedAllTime => "Top Rated (All-Time)",
+ Self::TopRatedRecent => "Top Rated (Recent Releases)",
+ Self::MostWatched => "Most Watched",
+ }
+ }
+
+ pub fn metric(self) -> BrowseMetric {
+ match self {
+ Self::Trending => BrowseMetric::Trending,
+ Self::TopRatedAllTime => BrowseMetric::Rating,
+ Self::TopRatedRecent => BrowseMetric::RecentRating,
+ Self::MostWatched => BrowseMetric::Popularity,
+ }
+ }
+
+ pub fn descending(self) -> bool {
+ true
+ }
+}
+
+#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
+pub struct BrowseMetrics {
+ pub trending: Option<f64>,
+ pub rating: Option<f64>,
+ pub recent_rating: Option<f64>,
+ pub popularity: Option<f64>,
+}
+
+impl BrowseMetrics {
+ pub fn value(self, metric: BrowseMetric) -> Option<f64> {
+ match metric {
+ BrowseMetric::Trending => self.trending,
+ BrowseMetric::Rating => self.rating,
+ BrowseMetric::RecentRating => self.recent_rating,
+ BrowseMetric::Popularity => self.popularity,
+ }
+ }
+}
+
+#[derive(Debug, Default, Clone)]
+pub struct SubjectStreamPool {
+ pub episode_index: HashMap<(usize, usize), Vec<serde_json::Value>>,
+ pub fetched_pages: HashMap<u32, HashSet<usize>>,
+ pub total_pages: HashMap<u32, usize>,
+ pub available_resolutions: Vec<u32>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum NotificationKind {
+ Info,
+ Success,
+ Warning,
+ Error,
+}
+
+#[derive(Debug, Clone)]
+pub struct Notification {
+ pub kind: NotificationKind,
+ pub title: String,
+ pub message: String,
+ pub expires_at: Instant,
+}
+
+impl Notification {
+ pub fn new(
+ kind: NotificationKind,
+ title: impl Into<String>,
+ message: impl Into<String>,
+ ) -> Self {
+ let duration = match kind {
+ NotificationKind::Info => Duration::from_secs(4),
+ NotificationKind::Success => Duration::from_secs(5),
+ NotificationKind::Warning => Duration::from_secs(7),
+ NotificationKind::Error => Duration::from_secs(10),
+ };
+ Self {
+ kind,
+ title: title.into(),
+ message: message.into(),
+ expires_at: Instant::now() + duration,
+ }
+ }
+
+ pub fn expired(&self) -> bool {
+ Instant::now() >= self.expires_at
+ }
+}
diff --git a/src/service.rs b/src/service.rs
new file mode 100644
index 0000000..96954c1
--- /dev/null
+++ b/src/service.rs
@@ -0,0 +1,361 @@
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use crate::models::BrowseMetrics;
+use crate::providers::Provider;
+use crate::providers::bdix::circleftp::CircleFtpClient;
+use crate::providers::bdix::dhakaflix::client::DhakaFlixClient;
+use crate::providers::fourkhdhub::FourKHdHubClient;
+use crate::providers::models::ProviderKind;
+use crate::providers::moviebox::client::MovieBoxClient;
+
+#[derive(Clone)]
+pub struct MovieBoxService {
+ pub client: MovieBoxClient,
+ pub fourk_client: Option<FourKHdHubClient>,
+ pub circleftp_client: CircleFtpClient,
+ pub dhakaflix_client: DhakaFlixClient,
+ pub http_client: reqwest::Client,
+}
+
+impl Default for MovieBoxService {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MovieBoxService {
+ pub fn new() -> Self {
+ let http_client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(15))
+ .build()
+ .unwrap_or_default();
+
+ Self {
+ client: MovieBoxClient::new(),
+ fourk_client: FourKHdHubClient::new().ok(),
+ circleftp_client: CircleFtpClient::new(),
+ dhakaflix_client: DhakaFlixClient::new(),
+ http_client,
+ }
+ }
+
+ pub fn http_client(&self) -> &reqwest::Client {
+ &self.http_client
+ }
+
+ pub async fn suggest(&self, query: &str) -> Result<serde_json::Value, String> {
+ self.client.suggest(query).await.map_err(|e| e.to_string())
+ }
+
+ pub async fn search(
+ &self,
+ provider: ProviderKind,
+ query: &str,
+ page: usize,
+ ) -> Result<serde_json::Value, String> {
+ match provider {
+ ProviderKind::MovieBox => Provider::search(&self.client, query, page).await,
+ ProviderKind::FourKHdHub => {
+ let fourk = self
+ .fourk_client
+ .as_ref()
+ .ok_or_else(|| "4KHDHub provider is unavailable".to_string())?;
+ Provider::search(fourk, query, page).await
+ }
+ ProviderKind::BdixCircleFtp => {
+ Provider::search(&self.circleftp_client, query, page).await
+ }
+ ProviderKind::BdixDhakaFlix => {
+ Provider::search(&self.dhakaflix_client, query, page).await
+ }
+ }
+ }
+
+ pub async fn details(
+ &self,
+ provider: ProviderKind,
+ subject_id: &str,
+ ) -> Result<serde_json::Value, String> {
+ match provider {
+ ProviderKind::MovieBox => Provider::details(&self.client, subject_id).await,
+ ProviderKind::FourKHdHub => {
+ let fourk = self
+ .fourk_client
+ .as_ref()
+ .ok_or_else(|| "4KHDHub provider is unavailable".to_string())?;
+ Provider::details(fourk, subject_id).await
+ }
+ ProviderKind::BdixCircleFtp => {
+ Provider::details(&self.circleftp_client, subject_id).await
+ }
+ ProviderKind::BdixDhakaFlix => {
+ Provider::details(&self.dhakaflix_client, subject_id).await
+ }
+ }
+ }
+
+ pub async fn homepage(&self, tab_id: &str, page: usize) -> Result<serde_json::Value, String> {
+ self.client
+ .get_homepage(tab_id, page)
+ .await
+ .map_err(|e| e.to_string())
+ }
+
+ pub async fn fetch_collection_resolutions(&self, subject_id: &str) -> Result<Vec<u32>, String> {
+ self.client
+ .fetch_collection_resolutions(subject_id)
+ .await
+ .map_err(|e| e.to_string())
+ }
+
+ pub async fn get_ext_captions(
+ &self,
+ subject_id: &str,
+ resource_id: &str,
+ ) -> Result<serde_json::Value, String> {
+ self.client
+ .get_ext_captions(subject_id, resource_id)
+ .await
+ .map_err(|e| e.to_string())
+ }
+
+ pub async fn fetch_poster_bytes(&self, url: &str) -> Option<Vec<u8>> {
+ let response = self
+ .http_client
+ .get(url)
+ .header("User-Agent", "MovieBox-Tui/1.0")
+ .send()
+ .await
+ .ok()?
+ .error_for_status()
+ .ok()?;
+ Some(response.bytes().await.ok()?.to_vec())
+ }
+
+ pub async fn download_subtitle_file(
+ &self,
+ url: &str,
+ headers: &[(String, String)],
+ ) -> Result<PathBuf, String> {
+ let mut request = self.http_client.get(url);
+ for (name, value) in headers {
+ request = request.header(name.as_str(), value.as_str());
+ }
+
+ let response = tokio::time::timeout(std::time::Duration::from_secs(30), request.send())
+ .await
+ .map_err(|_| "Subtitle download timed out".to_string())?
+ .map_err(|e| format!("Failed to request subtitle: {e}"))?
+ .error_for_status()
+ .map_err(|e| format!("Subtitle response status error: {e}"))?;
+
+ let bytes = response
+ .bytes()
+ .await
+ .map_err(|e| format!("Failed to read subtitle bytes: {e}"))?;
+
+ let extension = url
+ .rsplit('.')
+ .next()
+ .map(|e| e.to_ascii_lowercase())
+ .filter(|e| matches!(e.as_str(), "srt" | "vtt" | "ass" | "ssa" | "sub"))
+ .unwrap_or_else(|| "srt".to_string());
+
+ let base_dir = resolve_subtitle_dir();
+ let _ = std::fs::create_dir_all(&base_dir);
+
+ let path = base_dir.join(format!(
+ "{}_{}.{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos(),
+ extension
+ ));
+
+ tokio::fs::write(&path, bytes)
+ .await
+ .map_err(|e| format!("Failed to write subtitle file: {e}"))?;
+
+ Ok(path)
+ }
+}
+
+pub async fn decode_poster(bytes: Vec<u8>) -> Option<Arc<image::DynamicImage>> {
+ tokio::task::spawn_blocking(move || image::load_from_memory(&bytes))
+ .await
+ .ok()?
+ .ok()
+ .map(Arc::new)
+}
+
+pub fn extract_cover_url(val: &serde_json::Value) -> Option<String> {
+ let keys = [
+ "cover",
+ "poster",
+ "pic",
+ "coverUrl",
+ "cover_url",
+ "posterUrl",
+ "poster_url",
+ "thumbnail",
+ "image",
+ "logo",
+ "imgUrl",
+ "img_url",
+ ];
+ for key in keys {
+ if let Some(v) = val.get(key) {
+ if let Some(s) = v.as_str() {
+ if !s.is_empty() {
+ return Some(s.to_string());
+ }
+ } else if let Some(url) = v.get("url").and_then(|u| u.as_str()) {
+ if !url.is_empty() {
+ return Some(url.to_string());
+ }
+ }
+ }
+ }
+ None
+}
+
+pub fn metric_value(item: &serde_json::Value, keys: &[&str]) -> Option<f64> {
+ let mut containers = vec![item];
+ if let Some(metadata) = item.get("metadata") {
+ containers.push(metadata);
+ }
+ if let Some(meta) = item.get("meta") {
+ containers.push(meta);
+ }
+
+ containers.into_iter().find_map(|container| {
+ keys.iter().find_map(|key| {
+ let value = container.get(*key)?;
+ value
+ .as_f64()
+ .or_else(|| value.as_i64().map(|number| number as f64))
+ .or_else(|| value.as_str().and_then(|text| text.parse::<f64>().ok()))
+ })
+ })
+}
+
+pub fn extract_browse_metrics(item: &serde_json::Value) -> BrowseMetrics {
+ BrowseMetrics {
+ trending: metric_value(
+ item,
+ &["__browse_rank", "imdb_trending", "imdbTrending", "trending"],
+ ),
+ rating: metric_value(
+ item,
+ &["imdbRatingValue", "imdbRate", "imdb_rating", "imdbRating"],
+ ),
+ recent_rating: metric_value(
+ item,
+ &[
+ "imdb_rating_30d",
+ "imdbRating30Days",
+ "imdbRatingLast30Days",
+ "imdb_rating_recent",
+ "imdbRatingValue",
+ "imdbRate",
+ ],
+ ),
+ popularity: metric_value(
+ item,
+ &[
+ "__browse_rank",
+ "imdb_popularity",
+ "imdbPopularity",
+ "popularity",
+ "viewers",
+ ],
+ ),
+ }
+}
+
+pub fn subject_id(value: &serde_json::Value) -> Option<String> {
+ value
+ .as_i64()
+ .map(|n| n.to_string())
+ .or_else(|| value.as_str().map(|s| s.to_string()))
+}
+
+pub fn stype(value: &serde_json::Value) -> i64 {
+ value
+ .get("subjectType")
+ .and_then(|s| s.as_i64())
+ .or_else(|| value.get("stype").and_then(|s| s.as_i64()))
+ .unwrap_or(1)
+}
+
+pub fn caption_options(payload: &serde_json::Value) -> Vec<(String, String)> {
+ let mut options = vec![("None".to_string(), "".to_string())];
+ options.extend(
+ crate::providers::moviebox::adapt::captions_json_to_options(payload)
+ .into_iter()
+ .map(|subtitle| (subtitle.name, subtitle.url)),
+ );
+ options
+}
+
+pub fn caption_url_for(payload: &serde_json::Value, language: &str) -> Option<String> {
+ crate::providers::moviebox::adapt::captions_json_to_options(payload)
+ .into_iter()
+ .find(|subtitle| subtitle.name == language)
+ .map(|subtitle| subtitle.url)
+}
+
+pub fn resolve_subtitle_dir() -> PathBuf {
+ if let Some(home) = dirs::home_dir() {
+ let storage = home.join("storage/downloads/moviebox_subs");
+ if home.join("storage/downloads").exists() {
+ let _ = std::fs::create_dir_all(&storage);
+ return storage;
+ }
+ }
+ std::env::temp_dir().join("moviebox-tui/subs")
+}
+
+pub fn ensure_moviebox_subdir(path: &Path) -> PathBuf {
+ let is_already_mb = path
+ .file_name()
+ .map(|name| {
+ let s = name.to_string_lossy();
+ s.eq_ignore_ascii_case("MovieBox-TUI") || s.eq_ignore_ascii_case("MovieBox")
+ })
+ .unwrap_or(false);
+
+ if is_already_mb {
+ path.to_path_buf()
+ } else {
+ path.join("MovieBox-TUI")
+ }
+}
+
+pub fn resolve_download_dir(custom_dir: Option<&Path>) -> PathBuf {
+ if let Some(custom) = custom_dir {
+ if std::fs::create_dir_all(custom).is_ok() {
+ let probe = custom.join(format!(".mb_probe_{}", std::process::id()));
+ if std::fs::write(&probe, b"ok").is_ok() {
+ let _ = std::fs::remove_file(&probe);
+ return ensure_moviebox_subdir(custom);
+ }
+ }
+ }
+
+ let base_dir = dirs::download_dir()
+ .or_else(|| dirs::home_dir().map(|h| h.join("Downloads")))
+ .unwrap_or_else(|| PathBuf::from("."));
+
+ if let Some(home) = dirs::home_dir() {
+ let android_storage = home.join("storage/downloads");
+ if android_storage.exists() {
+ return ensure_moviebox_subdir(&android_storage);
+ }
+ }
+
+ ensure_moviebox_subdir(&base_dir)
+}
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 3e55355..3fb35bc 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -2,67 +2,9 @@ use super::App;
use crate::providers::models::ProviderKind;
use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
-fn ensure_moviebox_subdir(path: &std::path::Path) -> std::path::PathBuf {
- let is_already_mb = path
- .file_name()
- .map(|name| {
- let s = name.to_string_lossy();
- s.eq_ignore_ascii_case("MovieBox-TUI") || s.eq_ignore_ascii_case("MovieBox")
- })
- .unwrap_or(false);
-
- if is_already_mb {
- path.to_path_buf()
- } else {
- path.join("MovieBox-TUI")
- }
-}
-
impl App {
pub(super) fn resolve_download_base_dir(&self) -> std::path::PathBuf {
- if let Some(ref custom_dir) = self.state.download_dir {
- static LAST_PROBE: std::sync::Mutex<Option<(std::path::PathBuf, std::time::Instant)>> =
- std::sync::Mutex::new(None);
- let mut cached_ok = false;
- if let Ok(guard) = LAST_PROBE.lock() {
- if let Some((ref path, time)) = *guard {
- if path == custom_dir && time.elapsed().as_secs() < 60 {
- cached_ok = true;
- }
- }
- }
- if cached_ok {
- return ensure_moviebox_subdir(custom_dir);
- }
- if std::fs::create_dir_all(custom_dir).is_ok() {
- let probe = custom_dir.join(format!(".mb_probe_{}", std::process::id()));
- if std::fs::write(&probe, b"ok").is_ok() {
- let _ = std::fs::remove_file(&probe);
- if let Ok(mut guard) = LAST_PROBE.lock() {
- *guard = Some((custom_dir.clone(), std::time::Instant::now()));
- }
- return ensure_moviebox_subdir(custom_dir);
- }
- }
- log::warn!("Custom download directory inaccessible; falling back to default");
- }
-
- let base_dir = dirs::download_dir()
- .or_else(|| dirs::home_dir().map(|h| h.join("Downloads")))
- .unwrap_or_else(|| std::path::PathBuf::from("."));
-
- let base_dir = if let Some(home) = dirs::home_dir() {
- let android_storage = home.join("storage/downloads");
- if android_storage.exists() {
- android_storage
- } else {
- base_dir
- }
- } else {
- base_dir
- };
-
- ensure_moviebox_subdir(&base_dir)
+ crate::service::resolve_download_dir(self.state.download_dir.as_deref())
}
pub(super) fn start_resilient_download(
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index e59df98..3ff2922 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -20,6 +20,7 @@ mod tv;
pub struct App {
state: AppState,
theme: Theme,
+ service: std::sync::Arc<crate::service::MovieBoxService>,
client: MovieBoxClient,
fourk_client: Option<FourKHdHubClient>,
circleftp_client: crate::providers::bdix::circleftp::CircleFtpClient,
@@ -66,13 +67,16 @@ impl App {
state.active_theme_kind = "Mocha".to_string();
}
+ let service = std::sync::Arc::new(crate::service::MovieBoxService::new());
+
let app = Self {
theme,
state,
- client: MovieBoxClient::new(),
- fourk_client: FourKHdHubClient::new().ok(),
- circleftp_client: crate::providers::bdix::circleftp::CircleFtpClient::new(),
- dhakaflix_client: crate::providers::bdix::dhakaflix::client::DhakaFlixClient::new(),
+ client: service.client.clone(),
+ fourk_client: service.fourk_client.clone(),
+ circleftp_client: service.circleftp_client.clone(),
+ dhakaflix_client: service.dhakaflix_client.clone(),
+ service,
action_sender,
action_receiver,
};
diff --git a/src/tui/app/network.rs b/src/tui/app/network.rs
index 820af77..3257d52 100644
--- a/src/tui/app/network.rs
+++ b/src/tui/app/network.rs
@@ -1,7 +1,9 @@
use crate::providers::{
- Provider, fourkhdhub::FourKHdHubClient, models::ProviderKind, moviebox::client::MovieBoxClient,
+ fourkhdhub::FourKHdHubClient, models::ProviderKind, moviebox::client::MovieBoxClient,
};
+pub(super) use crate::service::decode_poster;
+
pub(super) async fn fetch_poster_bytes(client: &reqwest::Client, url: &str) -> Option<Vec<u8>> {
let response = client
.get(url)
@@ -14,14 +16,6 @@ pub(super) async fn fetch_poster_bytes(client: &reqwest::Client, url: &str) -> O
Some(response.bytes().await.ok()?.to_vec())
}
-pub(super) async fn decode_poster(bytes: Vec<u8>) -> Option<std::sync::Arc<image::DynamicImage>> {
- tokio::task::spawn_blocking(move || image::load_from_memory(&bytes))
- .await
- .ok()?
- .ok()
- .map(std::sync::Arc::new)
-}
-
pub(super) async fn provider_search(
moviebox: &MovieBoxClient,
fourk: Option<&FourKHdHubClient>,
@@ -31,15 +25,14 @@ pub(super) async fn provider_search(
query: &str,
page: usize,
) -> Result<serde_json::Value, String> {
- match provider {
- ProviderKind::MovieBox => Provider::search(moviebox, query, page).await,
- ProviderKind::FourKHdHub => {
- let fourk = fourk.ok_or_else(|| "4KHDHub provider is unavailable".to_string())?;
- Provider::search(fourk, query, page).await
- }
- ProviderKind::BdixCircleFtp => Provider::search(circleftp, query, page).await,
- ProviderKind::BdixDhakaFlix => Provider::search(dhakaflix, query, page).await,
- }
+ let service = crate::service::MovieBoxService {
+ client: moviebox.clone(),
+ fourk_client: fourk.cloned(),
+ circleftp_client: circleftp.clone(),
+ dhakaflix_client: dhakaflix.clone(),
+ http_client: moviebox.http_client().clone(),
+ };
+ service.search(provider, query, page).await
}
pub(super) async fn provider_details(
@@ -50,13 +43,12 @@ pub(super) async fn provider_details(
provider: ProviderKind,
subject_id: &str,
) -> Result<serde_json::Value, String> {
- match provider {
- ProviderKind::MovieBox => Provider::details(moviebox, subject_id).await,
- ProviderKind::FourKHdHub => {
- let fourk = fourk.ok_or_else(|| "4KHDHub provider is unavailable".to_string())?;
- Provider::details(fourk, subject_id).await
- }
- ProviderKind::BdixCircleFtp => Provider::details(circleftp, subject_id).await,
- ProviderKind::BdixDhakaFlix => Provider::details(dhakaflix, subject_id).await,
- }
+ let service = crate::service::MovieBoxService {
+ client: moviebox.clone(),
+ fourk_client: fourk.cloned(),
+ circleftp_client: circleftp.clone(),
+ dhakaflix_client: dhakaflix.clone(),
+ http_client: moviebox.http_client().clone(),
+ };
+ service.details(provider, subject_id).await
}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index b6a3be8..97972af 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -2,36 +2,7 @@ use super::App;
use crate::providers::models::ProviderKind;
use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
-pub(crate) fn extract_cover_url(val: &serde_json::Value) -> Option<String> {
- let keys = [
- "cover",
- "poster",
- "pic",
- "coverUrl",
- "cover_url",
- "posterUrl",
- "poster_url",
- "thumbnail",
- "image",
- "logo",
- "imgUrl",
- "img_url",
- ];
- for key in keys {
- if let Some(v) = val.get(key) {
- if let Some(s) = v.as_str() {
- if !s.is_empty() {
- return Some(s.to_string());
- }
- } else if let Some(url) = v.get("url").and_then(|u| u.as_str()) {
- if !url.is_empty() {
- return Some(url.to_string());
- }
- }
- }
- }
- None
-}
+pub(crate) use crate::service::extract_cover_url;
impl App {
fn preferred_playback_player(
@@ -129,7 +100,6 @@ impl App {
) {
let history_item = self.build_watch_history_item();
- let client = self.client.http_client().clone();
let sender = self.action_sender.clone();
let cell_size = self
.state
@@ -154,58 +124,24 @@ impl App {
crate::tui::state::PlayerKind::Vlc | crate::tui::state::PlayerKind::Iina
) && let Some(url) = subtitle
{
- let mut request = client.get(&url);
- for (name, value) in &headers {
- request = request.header(name.as_str(), value.as_str());
- }
- let mut downloaded = false;
- if let Ok(Ok(response)) =
- tokio::time::timeout(std::time::Duration::from_secs(30), request.send()).await
- && let Ok(response) = response.error_for_status()
- && let Ok(bytes) = response.bytes().await
- {
- let extension = url
- .rsplit('.')
- .next()
- .map(|e| e.to_ascii_lowercase())
- .filter(|e| matches!(e.as_str(), "srt" | "vtt" | "ass" | "ssa" | "sub"))
- .unwrap_or_else(|| "srt".to_string());
- let base_dir = if let Some(home) = dirs::home_dir() {
- let storage = home.join("storage/downloads/moviebox_subs");
- if home.join("storage/downloads").exists() {
- let _ = std::fs::create_dir_all(&storage);
- storage
- } else {
- std::env::temp_dir().join("moviebox-tui/subs")
- }
- } else {
- std::env::temp_dir().join("moviebox-tui/subs")
- };
- let _ = std::fs::create_dir_all(&base_dir);
- let path = base_dir.join(format!(
- "{}_{}.{}",
- std::process::id(),
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos(),
- extension
- ));
- if tokio::fs::write(&path, bytes).await.is_ok() {
+ let download_res = crate::service::MovieBoxService::new()
+ .download_subtitle_file(&url, &headers)
+ .await;
+ match download_res {
+ Ok(path) => {
local_subtitle = Some(path.to_string_lossy().into_owned());
temporary_subtitle = Some(path);
- downloaded = true;
}
- }
- if !downloaded {
- log::warn!(
- "subtitle download failed for {:?} player, playing without subtitles (url was {})",
- kind,
- crate::logging::sanitize_url(&url)
- );
- let _ = sender.send(Action::SetStatus(
- "Subtitles unavailable; playing without subtitles.".to_string(),
- ));
+ Err(_) => {
+ log::warn!(
+ "subtitle download failed for {:?} player, playing without subtitles (url was {})",
+ kind,
+ crate::logging::sanitize_url(&url)
+ );
+ let _ = sender.send(Action::SetStatus(
+ "Subtitles unavailable; playing without subtitles.".to_string(),
+ ));
+ }
}
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 5e415d7..1009127 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -64,11 +64,11 @@ impl App {
return None;
}
- let client = self.client.clone();
+ let service = self.service.clone();
let sender = self.action_sender.clone();
let query_clone = query.clone();
tokio::spawn(async move {
- if let Ok(res) = client.suggest(&query_clone).await {
+ if let Ok(res) = service.suggest(&query_clone).await {
sender
.send(Action::SuggestSuccess(request_id, query_clone, res))
.ok();
@@ -1164,10 +1164,10 @@ impl App {
self.trigger_episode_fetch();
return None;
}
- let client = self.client.clone();
+ let service = self.service.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
- let resolutions = client
+ let resolutions = service
.fetch_collection_resolutions(&subject_id)
.await
.unwrap_or_default();
@@ -1737,13 +1737,13 @@ impl App {
if is_season_queue {
let subject_id = self.state.active_subject_id.clone().unwrap_or_default();
if let Some(rid) = self.get_selected_resource_id() {
- let client = self.client.clone();
+ let service = self.service.clone();
let sender = self.action_sender.clone();
let pref = self.state.season_subtitle_preference.clone();
let no_pref = pref.is_none();
tokio::spawn(async move {
- if let Ok(res) = client.get_ext_captions(&subject_id, &rid).await {
+ if let Ok(res) = service.get_ext_captions(&subject_id, &rid).await {
if no_pref {
sender.send(Action::ShowDownloadSubtitlePopup(res)).ok();
} else if let Some(pref_lang) = pref {
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index 35e1963..36c3166 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -1,65 +1,12 @@
use super::{App, network};
use crate::providers::models::{ProviderKind, RequestContext};
+use crate::service::extract_browse_metrics;
use crate::tui::{
action::Action,
overlay::NotificationKind,
- state::{BrowseMetrics, BrowsePreset, InputMode, Screen, SearchResult},
+ state::{BrowsePreset, InputMode, Screen, SearchResult},
};
-fn metric_value(item: &serde_json::Value, keys: &[&str]) -> Option<f64> {
- let mut containers = vec![item];
- if let Some(metadata) = item.get("metadata") {
- containers.push(metadata);
- }
- if let Some(meta) = item.get("meta") {
- containers.push(meta);
- }
-
- containers.into_iter().find_map(|container| {
- keys.iter().find_map(|key| {
- let value = container.get(*key)?;
- value
- .as_f64()
- .or_else(|| value.as_i64().map(|number| number as f64))
- .or_else(|| value.as_str().and_then(|text| text.parse::<f64>().ok()))
- })
- })
-}
-
-fn extract_browse_metrics(item: &serde_json::Value) -> BrowseMetrics {
- BrowseMetrics {
- trending: metric_value(
- item,
- &["__browse_rank", "imdb_trending", "imdbTrending", "trending"],
- ),
- rating: metric_value(
- item,
- &["imdbRatingValue", "imdbRate", "imdb_rating", "imdbRating"],
- ),
- recent_rating: metric_value(
- item,
- &[
- "imdb_rating_30d",
- "imdbRating30Days",
- "imdbRatingLast30Days",
- "imdb_rating_recent",
- "imdbRatingValue",
- "imdbRate",
- ],
- ),
- popularity: metric_value(
- item,
- &[
- "__browse_rank",
- "imdb_popularity",
- "imdbPopularity",
- "popularity",
- "viewers",
- ],
- ),
- }
-}
-
fn browse_group_matches(title: &str, preset: BrowsePreset) -> bool {
let title = title.to_lowercase();
match preset {
@@ -402,10 +349,7 @@ impl App {
let request_id = self.state.active_search_request;
let page = 1;
let sender = self.action_sender.clone();
- let client = self.client.clone();
- let fourk_client = self.fourk_client.clone();
- let circleftp_client = self.circleftp_client.clone();
- let dhakaflix_client = self.dhakaflix_client.clone();
+ let service = self.service.clone();
tokio::spawn(async move {
if !force_refresh {
let q = query.clone();
@@ -428,16 +372,7 @@ impl App {
}
}
- let result = network::provider_search(
- &client,
- fourk_client.as_ref(),
- &circleftp_client,
- &dhakaflix_client,
- context.provider,
- &query,
- page,
- )
- .await;
+ let result = service.search(context.provider, &query, page).await;
match result {
Ok(res) => {
let q = query.clone();
@@ -516,10 +451,7 @@ impl App {
context: RequestContext,
) {
let request_id = self.state.active_details_request;
- let client = self.client.clone();
- let fourk_client = self.fourk_client.clone();
- let circleftp_client = self.circleftp_client.clone();
- let dhakaflix_client = self.dhakaflix_client.clone();
+ let service = self.service.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
if !force_refresh {
@@ -541,15 +473,7 @@ impl App {
}
}
- let result = network::provider_details(
- &client,
- fourk_client.as_ref(),
- &circleftp_client,
- &dhakaflix_client,
- context.provider,
- &id,
- )
- .await;
+ let result = service.details(context.provider, &id).await;
match result {
Ok(details) => {
let id_for_cache = id.clone();
@@ -577,7 +501,7 @@ impl App {
pub(super) fn run_homepage_request(&self, tab_id: String, page: usize) {
let request_id = self.state.active_homepage_request;
- let client = self.client.clone();
+ let service = self.service.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
let t_clone = tab_id.clone();
@@ -597,7 +521,7 @@ impl App {
return;
}
- match client.get_homepage(&tab_id, page).await {
+ match service.homepage(&tab_id, page).await {
Ok(res) => {
let r_clone = res.clone();
let t_clone = tab_id.clone();
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index eb69916..746ae71 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -1,5 +1,3 @@
-use std::time::{Duration, Instant};
-
use ratatui::{
Frame,
layout::{Alignment, Constraint, Layout, Rect},
@@ -15,46 +13,7 @@ use crate::tui::theme::Theme;
const MAX_PICKER_ROWS: usize = 8;
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum NotificationKind {
- Info,
- Success,
- Warning,
- Error,
-}
-
-#[derive(Debug, Clone)]
-pub struct Notification {
- pub kind: NotificationKind,
- pub title: String,
- pub message: String,
- expires_at: Instant,
-}
-
-impl Notification {
- pub fn new(
- kind: NotificationKind,
- title: impl Into<String>,
- message: impl Into<String>,
- ) -> Self {
- let duration = match kind {
- NotificationKind::Info => Duration::from_secs(4),
- NotificationKind::Success => Duration::from_secs(5),
- NotificationKind::Warning => Duration::from_secs(7),
- NotificationKind::Error => Duration::from_secs(10),
- };
- Self {
- kind,
- title: title.into(),
- message: message.into(),
- expires_at: Instant::now() + duration,
- }
- }
-
- pub fn expired(&self) -> bool {
- Instant::now() >= self.expires_at
- }
-}
+pub use crate::models::{Notification, NotificationKind};
pub struct PickerSpec<'a> {
pub title: &'a str,
diff --git a/src/tui/state.rs b/src/tui/state.rs
index fd63388..ccc2518 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -24,91 +24,11 @@ pub enum InputMode {
Editing,
}
-#[derive(Debug, Clone)]
-pub struct SearchResult {
- pub id: String,
- pub title: String,
- pub stype: i64,
- pub release_year: String,
- pub cover_url: Option<String>,
- pub season: usize,
- pub episode: usize,
- pub provider: crate::providers::models::ProviderKind,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum BrowseMetric {
- Trending,
- Rating,
- RecentRating,
- Popularity,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum BrowsePreset {
- Trending,
- TopRatedAllTime,
- TopRatedRecent,
- MostWatched,
-}
-
-impl BrowsePreset {
- pub const ALL: [Self; 4] = [
- Self::Trending,
- Self::TopRatedAllTime,
- Self::TopRatedRecent,
- Self::MostWatched,
- ];
-
- pub fn label(self) -> &'static str {
- match self {
- Self::Trending => "Trending Now",
- Self::TopRatedAllTime => "Top Rated (All-Time)",
- Self::TopRatedRecent => "Top Rated (Recent Releases)",
- Self::MostWatched => "Most Watched",
- }
- }
-
- pub fn metric(self) -> BrowseMetric {
- match self {
- Self::Trending => BrowseMetric::Trending,
- Self::TopRatedAllTime => BrowseMetric::Rating,
- Self::TopRatedRecent => BrowseMetric::RecentRating,
- Self::MostWatched => BrowseMetric::Popularity,
- }
- }
-
- pub fn descending(self) -> bool {
- true
- }
-}
-
-#[derive(Debug, Default, Clone, Copy)]
-pub struct BrowseMetrics {
- pub trending: Option<f64>,
- pub rating: Option<f64>,
- pub recent_rating: Option<f64>,
- pub popularity: Option<f64>,
-}
-
-impl BrowseMetrics {
- pub fn value(self, metric: BrowseMetric) -> Option<f64> {
- match metric {
- BrowseMetric::Trending => self.trending,
- BrowseMetric::Rating => self.rating,
- BrowseMetric::RecentRating => self.recent_rating,
- BrowseMetric::Popularity => self.popularity,
- }
- }
-}
-
-#[derive(Debug, Default)]
-pub struct SubjectStreamPool {
- pub episode_index: std::collections::HashMap<(usize, usize), Vec<serde_json::Value>>,
- pub fetched_pages: std::collections::HashMap<u32, std::collections::HashSet<usize>>,
- pub total_pages: std::collections::HashMap<u32, usize>,
- pub available_resolutions: Vec<u32>,
-}
+pub use crate::models::{
+ BrowseMetric, BrowseMetrics, BrowsePreset, Notification, NotificationKind, SearchResult,
+ SubjectStreamPool,
+};
+pub use crate::service::{caption_options, caption_url_for, stype, subject_id};
pub struct AppState {
pub active_provider: ProviderKind,
@@ -448,35 +368,3 @@ impl AppState {
rows
}
}
-
-pub fn subject_id(value: &serde_json::Value) -> Option<String> {
- value
- .as_i64()
- .map(|n| n.to_string())
- .or_else(|| value.as_str().map(|s| s.to_string()))
-}
-
-pub fn stype(value: &serde_json::Value) -> i64 {
- value
- .get("subjectType")
- .and_then(|s| s.as_i64())
- .or_else(|| value.get("stype").and_then(|s| s.as_i64()))
- .unwrap_or(1)
-}
-
-pub fn caption_options(payload: &serde_json::Value) -> Vec<(String, String)> {
- let mut options = vec![("None".to_string(), "".to_string())];
- options.extend(
- crate::providers::moviebox::adapt::captions_json_to_options(payload)
- .into_iter()
- .map(|subtitle| (subtitle.name, subtitle.url)),
- );
- options
-}
-
-pub fn caption_url_for(payload: &serde_json::Value, language: &str) -> Option<String> {
- crate::providers::moviebox::adapt::captions_json_to_options(payload)
- .into_iter()
- .find(|subtitle| subtitle.name == language)
- .map(|subtitle| subtitle.url)
-}