Skip to content

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

refactor(core): streamline app state, centralize storage paths, and enable addon history parity

Samir Hossainsa2e733f1ae9d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc58057..2406e6b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,13 @@
- Added automatic startup state reconciliation (`reconcile_pending_playback_states`) ensuring watched progress is preserved even when closing the terminal or killing tmux mid-playback.
- Added two-tone smooth scrub line progress bars (`━─────── 1% (2h 18m left) • Watched 11h ago`) and completion status badges (`[✓ Completed]`, `[✓ Watched]`) in `/history` and Details screens.
- Added cross-provider title-based history deduplication and auto-resume from the last watched position.
+- **Addon Mode Watch History Parity**:
+ - Added full watch history support (`/history`) in Addon Mode matching Streaming Mode, enabling seamless watch progress tracking, scrub bars, and completion badges for community HTTP addon content.
+- **Codebase Optimization & Path Centralization**:
+ - Centralized application paths (`config_dir`, `data_dir`, `cache_dir`, `logs_dir`, `scripts_dir`, `playback_state_dir`) in `src/config.rs`.
+ - Streamlined `MovieBoxService` usage across background tasks and removed redundant duplicate client fields from `App` state.
+ - Centralized formatting utilities (`format_file_size`, `format_duration`) in `src/tui/text.rs`.
+ - Modernized `Config` loading and persistence with safe, standard Serde derives.
- **Addon Mode (Community HTTP Addons)**:
- Added full support for community HTTP addon manifests (`/manifest.json`, `/catalog`, `/meta`, `/stream`) with dedicated `Ctrl+A` mode switching.
- Pre-installed and locked Cinemeta out-of-the-box as the default core metadata provider with zero API keys required.
diff --git a/docs/controls.md b/docs/controls.md
index 08725f0..f395229 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -61,7 +61,7 @@ Type these commands directly into the search bar:
| Command | Applicable Mode | Action |
| :--- | :--- | :--- |
| `/browse` | Streaming / Addon | Browse curated views (Trending, Popular) or Addon catalogs (Top Movies, Top Series) |
-| `/history` | Streaming | View watch history with latest progress |
+| `/history` | Streaming / Addon | View watch history with latest progress |
| `/list` | TV | View live TV channels |
| `/config` | TV / Addon | Manage IPTV playlists (TV Mode) or configure HTTP addons (Addon Mode) |
| `/enable-streaming` | All | Enable Streaming Mode navigation in bottom dock |
diff --git a/src/cache.rs b/src/cache.rs
index d907c30..fc2cf2c 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -122,10 +122,9 @@ fn hash_key(value: &str) -> String {
}
pub fn get_provider_cache_dir(provider: ProviderKind, subdir: &str) -> PathBuf {
- let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
- path.push(crate::config::APP_NAME);
- path.push(provider.cache_key());
- path.push(subdir);
+ let path = crate::config::cache_dir()
+ .join(provider.cache_key())
+ .join(subdir);
if !path.exists() {
let _ = fs::create_dir_all(&path);
}
@@ -263,13 +262,12 @@ pub fn invalidate_provider_stream_cache(
}
pub fn clear_all_cache() {
- let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
- path.push(crate::config::APP_NAME);
+ let path = crate::config::cache_dir();
if path.exists() {
let _ = fs::remove_dir_all(&path);
}
- if let Some(data_dir) = dirs::data_dir() {
- let legacy = data_dir.join(crate::config::APP_NAME).join("iptv_cache");
+ if let Some(data_dir) = crate::config::data_dir() {
+ let legacy = data_dir.join("iptv_cache");
if legacy.exists() {
let _ = fs::remove_dir_all(&legacy);
}
@@ -278,8 +276,7 @@ pub fn clear_all_cache() {
pub fn clean_old_cache_background() {
tokio::task::spawn_blocking(|| {
- let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
- path.push(crate::config::APP_NAME);
+ let path = crate::config::cache_dir();
if !path.exists() {
return;
}
diff --git a/src/config.rs b/src/config.rs
index f760f00..23278a5 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -2,6 +2,10 @@ use crate::providers::addons::models::InstalledAddon;
use crate::providers::models::ProviderKind;
use std::path::PathBuf;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(default)]
pub struct Config {
pub auto_update: bool,
pub last_update_check: u64,
@@ -36,90 +40,61 @@ impl Default for Config {
pub const APP_NAME: &str = "moviebox-tui";
-fn path() -> Option<PathBuf> {
- dirs::config_dir().map(|dir| dir.join(APP_NAME).join("config.json"))
+pub fn config_dir() -> Option<PathBuf> {
+ dirs::config_dir().map(|dir| dir.join(APP_NAME))
+}
+
+pub fn data_dir() -> Option<PathBuf> {
+ dirs::data_dir().map(|dir| dir.join(APP_NAME))
+}
+
+pub fn cache_dir() -> PathBuf {
+ dirs::cache_dir()
+ .map(|dir| dir.join(APP_NAME))
+ .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME))
+}
+
+pub fn logs_dir() -> PathBuf {
+ data_dir()
+ .map(|dir| dir.join("logs"))
+ .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME).join("logs"))
+}
+
+pub fn scripts_dir() -> Option<PathBuf> {
+ data_dir().map(|dir| dir.join("scripts"))
+}
+
+pub fn playback_state_dir() -> Option<PathBuf> {
+ data_dir().map(|dir| dir.join("playback"))
+}
+
+pub fn config_path() -> Option<PathBuf> {
+ config_dir().map(|dir| dir.join("config.json"))
}
pub fn addons_path() -> Option<PathBuf> {
- dirs::config_dir().map(|dir| dir.join(APP_NAME).join("addons_config.json"))
+ config_dir().map(|dir| dir.join("addons_config.json"))
}
pub fn tv_path() -> Option<PathBuf> {
- dirs::config_dir().map(|dir| dir.join(APP_NAME).join("tv_config.json"))
+ config_dir().map(|dir| dir.join("tv_config.json"))
}
pub fn load() -> Config {
- let mut config = Config::default();
- let Some(path) = path() else {
- return config;
- };
- let Ok(content) = std::fs::read_to_string(&path) else {
- return config;
- };
- let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) else {
- let _ = std::fs::remove_file(path);
- return config;
- };
- if let Some(v) = value.get("auto_update").and_then(|v| v.as_bool()) {
- config.auto_update = v;
- }
- if let Some(v) = value.get("last_update_check").and_then(|v| v.as_u64()) {
- config.last_update_check = v;
- }
- if let Some(v) = value.get("active_mode").and_then(|v| v.as_str()) {
- config.active_mode = v.to_string();
- }
- if let Some(provider) = value.get("active_provider").and_then(|v| v.as_str()) {
- config.active_provider = ProviderKind::parse(provider).unwrap_or(config.active_provider);
- }
- if let Some(v) = value.get("active_theme").and_then(|v| v.as_str()) {
- config.active_theme = v.to_string();
- }
- if let Some(v) = value.get("bdix_enabled").and_then(|v| v.as_bool()) {
- config.bdix_enabled = v;
- }
- if let Some(v) = value.get("streaming_enabled").and_then(|v| v.as_bool()) {
- config.streaming_enabled = v;
- }
- if let Some(v) = value.get("tv_enabled").and_then(|v| v.as_bool()) {
- config.tv_enabled = v;
- }
- if let Some(v) = value.get("addons_enabled").and_then(|v| v.as_bool()) {
- config.addons_enabled = v;
- }
- if let Some(v) = value.get("default_player").and_then(|v| v.as_str()) {
- config.default_player = Some(v.to_string());
- }
- if let Some(v) = value.get("download_dir").and_then(|v| v.as_str()) {
- config.download_dir = Some(v.to_string());
- }
- config
+ config_path()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|c| serde_json::from_str::<Config>(&c).ok())
+ .unwrap_or_default()
}
pub fn save(config: &Config) {
- let Some(path) = path() else {
+ let Some(path) = config_path() else {
return;
};
- if let Some(app_dir) = path.parent()
- && std::fs::create_dir_all(app_dir).is_err()
- {
- return;
- }
- let json = serde_json::json!({
- "auto_update": config.auto_update,
- "last_update_check": config.last_update_check,
- "active_mode": config.active_mode,
- "active_provider": config.active_provider.cache_key(),
- "active_theme": config.active_theme,
- "bdix_enabled": config.bdix_enabled,
- "streaming_enabled": config.streaming_enabled,
- "tv_enabled": config.tv_enabled,
- "addons_enabled": config.addons_enabled,
- "default_player": config.default_player,
- "download_dir": config.download_dir
- });
- if let Err(error) = crate::cache::atomic_write_file(&path, json.to_string().as_bytes()) {
- log::warn!("failed to write config: {error}");
+ if let Ok(json) = serde_json::to_string_pretty(config) {
+ if let Err(error) = crate::cache::atomic_write_file(&path, json.as_bytes()) {
+ log::warn!("failed to write config: {error}");
+ }
}
}
diff --git a/src/history.rs b/src/history.rs
index 7f58243..a15cd0f 100644
--- a/src/history.rs
+++ b/src/history.rs
@@ -61,10 +61,10 @@ impl WatchHistoryItem {
}
pub fn formatted_progress(&self) -> String {
- let pos = format_time(self.progress_seconds);
+ let pos = crate::tui::text::format_duration(self.progress_seconds);
if let Some(dur) = self.duration_seconds {
if dur > 0 {
- return format!("{} / {}", pos, format_time(dur));
+ return format!("{} / {}", pos, crate::tui::text::format_duration(dur));
}
}
pos
@@ -116,17 +116,6 @@ impl WatchHistoryItem {
}
}
-fn format_time(secs: u64) -> String {
- let h = secs / 3600;
- let m = (secs % 3600) / 60;
- let s = secs % 60;
- if h > 0 {
- format!("{h}:{m:02}:{s:02}")
- } else {
- format!("{m}:{s:02}")
- }
-}
-
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingPlaybackState {
pub provider: String,
@@ -174,23 +163,11 @@ impl HistoryManager {
}
fn history_file_path() -> Option<PathBuf> {
- let mut path = dirs::data_dir()?;
- path.push(crate::config::APP_NAME);
- if !path.exists() {
- let _ = fs::create_dir_all(&path);
- }
- path.push("history.json");
- Some(path)
+ crate::config::data_dir().map(|dir| dir.join("history.json"))
}
pub fn playback_state_dir() -> Option<PathBuf> {
- let mut path = dirs::data_dir()?;
- path.push(crate::config::APP_NAME);
- path.push("playback");
- if !path.exists() {
- let _ = fs::create_dir_all(&path);
- }
- Some(path)
+ crate::config::playback_state_dir()
}
pub fn save(&self) {
diff --git a/src/logging.rs b/src/logging.rs
index bd43ca1..3bdb5d3 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -11,9 +11,7 @@ pub fn init() {
.filter(|value| !value.is_empty())
.unwrap_or_else(|| default_level.to_string());
- let log_dir = dirs::data_dir()
- .map(|dir| dir.join(crate::config::APP_NAME).join("logs"))
- .unwrap_or_else(std::env::temp_dir);
+ let log_dir = crate::config::logs_dir();
match Logger::try_with_str(&spec) {
Ok(logger) => {
@@ -53,13 +51,7 @@ pub fn init() {
}
pub fn log_file_path() -> std::path::PathBuf {
- dirs::data_dir()
- .map(|dir| {
- dir.join(crate::config::APP_NAME)
- .join("logs")
- .join(format!("{}_rCURRENT.log", crate::config::APP_NAME))
- })
- .unwrap_or_else(std::env::temp_dir)
+ crate::config::logs_dir().join(format!("{}_rCURRENT.log", crate::config::APP_NAME))
}
pub fn display_path() -> String {
diff --git a/src/player/tracker.rs b/src/player/tracker.rs
index a7757f7..7b7db36 100644
--- a/src/player/tracker.rs
+++ b/src/player/tracker.rs
@@ -69,13 +69,11 @@ end)
"#;
pub fn ensure_tracker_script() -> Option<PathBuf> {
- let mut path = dirs::data_dir()?;
- path.push(crate::config::APP_NAME);
- path.push("scripts");
- if !path.exists() {
- let _ = fs::create_dir_all(&path);
+ let dir = crate::config::scripts_dir()?;
+ if !dir.exists() {
+ let _ = fs::create_dir_all(&dir);
}
- path.push("moviebox_tracker.lua");
+ let path = dir.join("moviebox_tracker.lua");
if !path.exists()
|| fs::read_to_string(&path)
.map(|c| c != TRACKER_LUA_CONTENT)
@@ -92,14 +90,11 @@ pub fn state_file_path(
season: usize,
episode: usize,
) -> Option<PathBuf> {
- let mut path = dirs::data_dir()?;
- path.push(crate::config::APP_NAME);
- path.push("playback");
- if !path.exists() {
- let _ = fs::create_dir_all(&path);
+ let dir = crate::config::playback_state_dir()?;
+ if !dir.exists() {
+ let _ = fs::create_dir_all(&dir);
}
let sanitized_id = subject_id.replace(['/', '\\', ':', ' '], "_");
let filename = format!("{provider}_{sanitized_id}_{season}_{episode}.json");
- path.push(filename);
- Some(path)
+ Some(dir.join(filename))
}
diff --git a/src/providers/models.rs b/src/providers/models.rs
index 5fd163d..5520184 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -2,13 +2,17 @@ use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
-#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
#[default]
+ #[serde(rename = "moviebox", alias = "movie_box")]
MovieBox,
+ #[serde(rename = "fourkhdhub", alias = "four_k_hd_hub", alias = "4khdhub")]
FourKHdHub,
+ #[serde(rename = "bdix_circleftp", alias = "bdix_circle_ftp")]
BdixCircleFtp,
+ #[serde(rename = "bdix_dhakaflix", alias = "bdix_dhaka_flix")]
BdixDhakaFlix,
+ #[serde(rename = "addons", alias = "addon")]
Addons,
}
@@ -46,7 +50,7 @@ impl ProviderKind {
"4khdhub" | "fourkhdhub" => Some(Self::FourKHdHub),
"bdix_circleftp" | "circleftp (bdix)" => Some(Self::BdixCircleFtp),
"bdix_dhakaflix" | "dhakaflix (bdix)" => Some(Self::BdixDhakaFlix),
- "addons" | "addon" | "stremio" => Some(Self::Addons),
+ "addons" | "addon" => Some(Self::Addons),
_ => None,
}
}
diff --git a/src/providers/tv/parser.rs b/src/providers/tv/parser.rs
index 1e514cc..e352ab8 100644
--- a/src/providers/tv/parser.rs
+++ b/src/providers/tv/parser.rs
@@ -15,9 +15,7 @@ impl Default for M3UParser {
impl M3UParser {
pub fn new() -> Self {
- let mut cache_dir = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
- cache_dir.push(crate::config::APP_NAME);
- cache_dir.push("tv_playlists");
+ let cache_dir = crate::config::cache_dir().join("tv_playlists");
std::fs::create_dir_all(&cache_dir).ok();
let client = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(10))
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 7546d51..13675ab 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -132,7 +132,7 @@ impl App {
log::warn!(
"failed to build custom download client ({err}), falling back to default"
);
- self.client.http_client().clone()
+ self.service.http_client().clone()
});
tokio::spawn(async move {
@@ -316,7 +316,7 @@ impl App {
.ok();
return None;
} else {
- match self.fourk_client.clone() {
+ match self.service.fourk_client.clone() {
Some(client) => client,
None => {
self.state.is_resolving_playback = false;
@@ -382,7 +382,7 @@ impl App {
"Preparing download",
"Fetching subtitles.",
);
- let client = self.client.clone();
+ let client = self.service.client.clone();
let sender = self.action_sender.clone();
tokio::spawn(async move {
if let Ok(res) = client.get_ext_captions(&subject_id, &rid).await {
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 0f94550..a07a120 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -203,12 +203,20 @@ impl App {
.suggest_index
.and_then(|idx| self.state.search_suggestions.get(idx).cloned());
- let query = if let Some(sug) = selected_opt {
+ let mut query = if let Some(sug) = selected_opt {
sug
} else {
self.state.search_query.trim().to_string()
};
+ if query.starts_with('/') {
+ let suggestions =
+ crate::tui::commands::SlashCommand::suggest(&self.state, &query);
+ if suggestions.len() == 1 {
+ query = suggestions[0].name().to_string();
+ }
+ }
+
if !query.is_empty() {
if query.trim().eq_ignore_ascii_case("/history") {
self.state.search_query = "/history".to_string();
@@ -230,6 +238,17 @@ impl App {
.ok();
}
}
+ KeyCode::Tab => {
+ let trimmed = self.state.search_query.trim();
+ if trimmed.starts_with('/') {
+ let suggestions =
+ crate::tui::commands::SlashCommand::suggest(&self.state, trimmed);
+ if let Some(first) = suggestions.first() {
+ self.state.search_query = first.name().to_string();
+ self.state.last_search_edit = std::time::Instant::now();
+ }
+ }
+ }
KeyCode::Backspace => {
crate::tui::text::remove_last_grapheme(&mut self.state.search_query);
self.state.suggest_index = None;
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 99f9d49..6136d7b 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -1,8 +1,6 @@
use tokio::sync::mpsc;
-use crate::providers::{
- fourkhdhub::FourKHdHubClient, models::RequestContext, moviebox::client::MovieBoxClient,
-};
+use crate::providers::models::RequestContext;
use crate::tui::{action::Action, state::AppState, theme::Theme};
mod addons;
@@ -22,10 +20,6 @@ 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,
- dhakaflix_client: crate::providers::bdix::dhakaflix::client::DhakaFlixClient,
action_sender: mpsc::UnboundedSender<Action>,
action_receiver: mpsc::UnboundedReceiver<Action>,
}
@@ -98,21 +92,17 @@ impl App {
}
let service = std::sync::Arc::new(crate::service::MovieBoxService::new());
+ if service.fourk_client.is_none() {
+ log::warn!("4KHDHub client unavailable; provider will be disabled");
+ }
let mut app = Self {
theme,
state,
- 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,
};
- if app.fourk_client.is_none() {
- log::warn!("4KHDHub client unavailable; provider will be disabled");
- }
if app.state.is_tv_mode {
app.load_tv_playlists_from_config();
app.reload_tv_playlists();
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index 9e215dd..53869f2 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -1,4 +1,4 @@
-use super::{App, network};
+use super::App;
use crate::providers::models::{ProviderKind, Release};
use crate::tui::{action::Action, state::Screen};
@@ -61,7 +61,7 @@ impl App {
);
self.persist_config();
if provider == ProviderKind::MovieBox {
- let client = self.client.clone();
+ let client = self.service.client.clone();
tokio::spawn(async move {
let _ = client.init().await;
});
@@ -151,25 +151,13 @@ impl App {
.ok();
} else {
let query = self.state.search_query.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();
let sender = self.action_sender.clone();
let context = self.request_context();
let request_id = self.state.active_search_request;
self.state.is_loading = true;
tokio::spawn(async move {
- let result = network::provider_search(
- &client,
- fourk_client.as_ref(),
- &circleftp_client,
- &dhakaflix_client,
- context.provider,
- &query,
- next_page,
- )
- .await;
+ let result = service.search(context.provider, &query, next_page).await;
match result {
Ok(res) => {
sender
diff --git a/src/tui/app/network.rs b/src/tui/app/network.rs
index f5aa9a3..f96bc7f 100644
--- a/src/tui/app/network.rs
+++ b/src/tui/app/network.rs
@@ -1,7 +1,3 @@
-use crate::providers::{
- 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>> {
@@ -15,42 +11,3 @@ pub(super) async fn fetch_poster_bytes(client: &reqwest::Client, url: &str) -> O
.ok()?;
Some(response.bytes().await.ok()?.to_vec())
}
-
-pub(super) async fn provider_search(
- moviebox: &MovieBoxClient,
- fourk: Option<&FourKHdHubClient>,
- circleftp: &crate::providers::bdix::circleftp::CircleFtpClient,
- dhakaflix: &crate::providers::bdix::dhakaflix::client::DhakaFlixClient,
- provider: ProviderKind,
- query: &str,
- page: usize,
-) -> Result<serde_json::Value, String> {
- let service = crate::service::MovieBoxService {
- client: moviebox.clone(),
- fourk_client: fourk.cloned(),
- circleftp_client: circleftp.clone(),
- dhakaflix_client: dhakaflix.clone(),
- addon_client: crate::providers::addons::AddonClient::new(),
- http_client: moviebox.http_client().clone(),
- };
- service.search(provider, query, page).await
-}
-
-pub(super) async fn provider_details(
- moviebox: &MovieBoxClient,
- fourk: Option<&FourKHdHubClient>,
- circleftp: &crate::providers::bdix::circleftp::CircleFtpClient,
- dhakaflix: &crate::providers::bdix::dhakaflix::client::DhakaFlixClient,
- provider: ProviderKind,
- subject_id: &str,
-) -> Result<serde_json::Value, String> {
- let service = crate::service::MovieBoxService {
- client: moviebox.clone(),
- fourk_client: fourk.cloned(),
- circleftp_client: circleftp.clone(),
- dhakaflix_client: dhakaflix.clone(),
- addon_client: crate::providers::addons::AddonClient::new(),
- 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 86a15ce..d6b844c 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -406,7 +406,7 @@ impl App {
}
return None;
} else {
- match self.fourk_client.clone() {
+ match self.service.fourk_client.clone() {
Some(client) => client,
None => {
self.state.is_resolving_playback = false;
@@ -469,7 +469,7 @@ impl App {
"Preparing playback",
"Fetching subtitles.",
);
- let client = self.client.clone();
+ let client = self.service.client.clone();
let sender = self.action_sender.clone();
let link_clone = link.clone();
tokio::spawn(async move {
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 04e7943..5d85dac 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -642,7 +642,7 @@ impl App {
let cover_url = channel.logo.clone();
if !cover_url.is_empty() {
let tx = self.action_sender.clone();
- let client = self.client.http_client().clone();
+ let client = self.service.http_client().clone();
let id2 = id.clone();
tokio::spawn(async move {
if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
@@ -712,7 +712,7 @@ impl App {
let url = url.to_string();
let tx = self.action_sender.clone();
let id2 = id.clone();
- let client = self.client.http_client().clone();
+ let client = self.service.http_client().clone();
tokio::spawn(async move {
if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
let id_clone = id2.clone();
@@ -751,7 +751,7 @@ impl App {
}
self.state.preview_loading = true;
- let client = self.client.clone();
+ let client = self.service.client.clone();
let sender = self.action_sender.clone();
let id_clone = id.clone();
@@ -1053,7 +1053,7 @@ impl App {
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
- let http_client = self.client.http_client().clone();
+ let http_client = self.service.http_client().clone();
tokio::spawn(async move {
if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
let id_clone = id_clone.clone();
@@ -1297,7 +1297,7 @@ impl App {
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
- let http_client = self.client.http_client().clone();
+ let http_client = self.service.http_client().clone();
tokio::spawn(async move {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(5))
@@ -1532,9 +1532,9 @@ impl App {
if context.provider == ProviderKind::FourKHdHub || context.provider.is_bdix() {
let sender = self.action_sender.clone();
- let fourk_client = self.fourk_client.clone();
- let circleftp_client = self.circleftp_client.clone();
- let dhakaflix_client = self.dhakaflix_client.clone();
+ let fourk_client = self.service.fourk_client.clone();
+ let circleftp_client = self.service.circleftp_client.clone();
+ let dhakaflix_client = self.service.dhakaflix_client.clone();
let id = subject_id.clone();
tokio::spawn(async move {
let result = match context.provider {
@@ -1647,7 +1647,7 @@ impl App {
absolute_episode += episode.saturating_sub(1);
let estimated_page = (absolute_episode / 20) + 1;
- let client = self.client.clone();
+ let client = self.service.client.clone();
let sender = self.action_sender.clone();
let cancel_token = self.state.fetch_cancel.clone();
let id_clone = subject_id.clone();
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index dda7c8c..60e49d7 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -39,7 +39,7 @@ impl App {
let mut events = EventHandler::new(Duration::from_millis(100));
if self.state.active_provider == ProviderKind::MovieBox {
- let client = self.client.clone();
+ let client = self.service.client.clone();
tokio::spawn(async move {
let _ = client.init().await;
});
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index e0b03cb..8a6a788 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -187,20 +187,13 @@ impl App {
Some(true)
}
crate::tui::commands::ParsedCommand::History => {
- self.state.search_query.clear();
- self.state.input_mode = InputMode::Normal;
if current_mode == crate::tui::state::AppMode::Tv {
+ self.state.search_query.clear();
+ self.state.input_mode = InputMode::Normal;
self.state.notify(
NotificationKind::Info,
"TV Mode",
- format!("Command /history is only available in Streaming Mode. Switch with {ctrl_s}."),
- );
- Some(true)
- } else if current_mode == crate::tui::state::AppMode::Addon {
- self.state.notify(
- NotificationKind::Info,
- "Addon Mode",
- format!("Command /history is only available in Streaming Mode. Switch with {ctrl_s}."),
+ format!("Command /history is available in Streaming Mode ({ctrl_s}) or Addon Mode ({ctrl_a})."),
);
Some(true)
} else {
@@ -1076,22 +1069,14 @@ impl App {
}
let sender = self.action_sender.clone();
- let req_client = self.client.http_client().clone();
- let mb_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 {
let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(4));
for (id, cover_url, provider) in to_fetch {
let permit = sem.clone().acquire_owned().await.ok();
let tx = sender.clone();
- let client = req_client.clone();
- let mb_client = mb_client.clone();
- let fourk_client = fourk_client.clone();
- let circleftp_client = circleftp_client.clone();
- let dhakaflix_client = dhakaflix_client.clone();
+ let service = service.clone();
tokio::spawn(async move {
let _permit = permit;
@@ -1111,23 +1096,14 @@ impl App {
let mut resolved_url = cover_url;
if resolved_url.is_none() {
- if let Ok(details) = network::provider_details(
- &mb_client,
- fourk_client.as_ref(),
- &circleftp_client,
- &dhakaflix_client,
- provider,
- &id,
- )
- .await
- {
+ if let Ok(details) = service.details(provider, &id).await {
resolved_url = crate::tui::app::playback::extract_cover_url(&details);
}
}
if let Some(url) = resolved_url {
if !url.is_empty() {
- if let Some(bytes) = network::fetch_poster_bytes(&client, &url).await {
+ if let Some(bytes) = service.fetch_poster_bytes(&url).await {
let bytes_clone = bytes.clone();
let id_c = id.clone();
let _ = tokio::task::spawn_blocking(move || {
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index 63afb8c..4c4ad3e 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -124,7 +124,10 @@ impl SlashCommand {
(state.streaming_enabled && !state.is_tv_mode && !state.is_addon_mode)
|| (state.addons_enabled && state.is_addon_mode)
}
- Self::History => state.streaming_enabled && !state.is_tv_mode && !state.is_addon_mode,
+ Self::History => {
+ (state.streaming_enabled && !state.is_tv_mode && !state.is_addon_mode)
+ || (state.addons_enabled && state.is_addon_mode)
+ }
Self::List => state.tv_enabled && state.is_tv_mode,
Self::Config => {
(state.tv_enabled && state.is_tv_mode)
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 3749b7f..dda8fc6 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -830,36 +830,20 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.get("codecName")
.and_then(|c| c.as_str())
.unwrap_or("None");
- let size_str = file.get("size").and_then(|s| s.as_str());
let duration = file.get("duration").and_then(|d| d.as_u64()).unwrap_or(0);
let duration_str = if duration > 0 {
- let hours = duration / 3600;
- let mins = (duration % 3600) / 60;
- let secs = duration % 60;
- if hours > 0 {
- format!("{:02}:{:02}:{:02}", hours, mins, secs)
- } else {
- format!("{:02}:{:02}", mins, secs)
- }
+ crate::tui::text::format_duration(duration)
} else {
"--:--".to_string()
};
- let size_formatted = if let Some(s) = size_str {
- if let Ok(bytes) = s.parse::<f64>() {
- let mb = bytes / 1024.0 / 1024.0;
- if mb > 1024.0 {
- format!("{:.1}GB", mb / 1024.0)
- } else {
- format!("{:.0}MB", mb)
- }
- } else {
- "--".to_string()
- }
- } else {
- "--".to_string()
- };
+ let size_formatted = file
+ .get("size")
+ .and_then(|s| s.as_str())
+ .and_then(|s| s.parse::<f64>().ok())
+ .map(crate::tui::text::format_file_size)
+ .unwrap_or_else(|| "--".to_string());
let is_selected = Some(i) == selected_idx;
let pointer = if is_selected {
@@ -1285,14 +1269,7 @@ fn selected_stream_summary(state: &AppState) -> Option<String> {
.get("size")
.and_then(|value| value.as_str())
.and_then(|value| value.parse::<f64>().ok())
- .map(|bytes| {
- let megabytes = bytes / 1024.0 / 1024.0;
- if megabytes > 1024.0 {
- format!("{:.1} GB", megabytes / 1024.0)
- } else {
- format!("{megabytes:.0} MB")
- }
- });
+ .map(crate::tui::text::format_file_size);
let fields = [size, resolution, codec]
.into_iter()
.flatten()
diff --git a/src/tui/text.rs b/src/tui/text.rs
index 9045d74..ffccd57 100644
--- a/src/tui/text.rs
+++ b/src/tui/text.rs
@@ -222,3 +222,23 @@ pub fn is_http_url(source: &str) -> bool {
pub fn extract_4digit_year(raw: &str) -> String {
raw.chars().filter(|c| c.is_ascii_digit()).take(4).collect()
}
+
+pub fn format_duration(secs: u64) -> String {
+ let h = secs / 3600;
+ let m = (secs % 3600) / 60;
+ let s = secs % 60;
+ if h > 0 {
+ format!("{h}:{m:02}:{s:02}")
+ } else {
+ format!("{m}:{s:02}")
+ }
+}
+
+pub fn format_file_size(bytes: f64) -> String {
+ let mb = bytes / 1024.0 / 1024.0;
+ if mb >= 1024.0 {
+ format!("{:.1}GB", mb / 1024.0)
+ } else {
+ format!("{:.0}MB", mb)
+ }
+}