Skip to content

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

feat(download): support customizable download directory with write permission validation

Samir Hossains83eaf44d644f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4af1d31..341a5b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,11 @@
- **Contextual Downloads**:
- Pressing `d` or clicking `[Download]` while on the **Seasons** pane prompts to download the whole season (all episodes).
- Triggering download while on **Episodes** or **Streams** downloads that single episode.
+- **Custom Download Directory**:
+ - Added `/download-dir <path>` slash command with directory creation and active write-probe validation.
+ - Added `/download-dir reset` (contextually suggested only when custom path is configured) to revert to OS default.
+ - Safe automatic fallback to default OS Downloads folder if custom path becomes inaccessible.
+ - Configuration persistence across sessions in `config.json`.
- **Tree Branch Suggestions**:
- Redesigned search and slash command autocomplete into a minimal, transparent tree-branch layout (`├─ ` / `└─ `) anchored directly under the search prompt.
- Added aligned slash command descriptions (`browse`, `history`, `theme`, `config`, `update`, etc.) without duplicate leading slashes.
diff --git a/README.md b/README.md
index 3f81298..6f67738 100644
--- a/README.md
+++ b/README.md
@@ -217,6 +217,7 @@ moviebox-tui
| Command | Action |
| -------------------- | ----------------------------------------- |
| `/browse` | Browse curated, rated, and most-watched views |
+| `/download-dir` | View, change, or reset download directory |
| `/history` | Show watch history |
| `/list` | Show IPTV channels |
| `/config` | Configure IPTV playlists |
@@ -235,7 +236,7 @@ unless `MOVIEBOX_PLAYER` is set in the environment.
## Downloads
-Downloads are stored under the operating system Downloads directory:
+By default, downloads are stored under the operating system Downloads directory:
```text
MovieBox-TUI/
@@ -243,6 +244,7 @@ MovieBox-TUI/
└── Series/<title>/Season <number>/
```
+- **Custom download directory:** Use `/download-dir <path>` (e.g. `/download-dir ~/Videos` or `/download-dir /Volumes/Drive`) to change and persist your download folder. Use `/download-dir reset` to return to default.
- **Contextual triggers:** Pressing `d` or clicking `[Download]` while focused on the **Seasons** pane prompts to download the whole season; while on **Episodes** or **Streams**, it downloads that single episode.
- **Sequential downloads:** Entire seasons are downloaded one by one to limit disk and network pressure.
- **Smart subtitles:** Your subtitle language choice for the first episode is applied to the remaining episodes. Missing subtitles do not discard completed video files.
diff --git a/docs/downloads.md b/docs/downloads.md
index 65527e9..019d4d6 100644
--- a/docs/downloads.md
+++ b/docs/downloads.md
@@ -16,12 +16,14 @@ and optional segmentation. Orchestration lives in `app/download.rs`.
- **Cancel**: an `AtomicBool` cancel flag pauses/resumes cleanly, preserving the
partial file for a later resume.
-## File names
+## File names and directories
`safe_file_stem` sanitizes titles for all platforms: control/whitespace/illegal
characters are replaced, Windows reserved names (`CON`, `COM1`-`COM9`, …) are avoided,
-and length is capped. Files go to the user's download directory. On Android-family
-environments the code prefers shared `storage/downloads` when present.
+and length is capped.
+
+- **Default path:** Files go to the user's OS download directory (`~/Downloads/MovieBox-TUI`). On Android-family environments the code prefers shared `storage/downloads` when present.
+- **Custom path:** Users can set a custom download directory using `/download-dir <path>` or revert with `/download-dir reset`. Target directories are validated with active write probes before saving, and the engine automatically falls back to default if custom storage becomes unavailable at runtime.
## Contextual triggers & Seasons
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 9cd9ecd..bcb27b6 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -3,6 +3,36 @@ use crate::providers::models::ProviderKind;
use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
impl App {
+ pub(super) fn resolve_download_base_dir(&self) -> std::path::PathBuf {
+ if let Some(ref custom_dir) = self.state.download_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);
+ return custom_dir.clone();
+ }
+ }
+ 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
+ };
+
+ base_dir.join("MovieBox-TUI")
+ }
+
pub(super) fn start_resilient_download(
&mut self,
subtitle_url: Option<String>,
@@ -40,53 +70,36 @@ impl App {
.state
.selected_details
.as_ref()
- .map(crate::tui::state::stype)
+ .and_then(|details| details.get("type"))
+ .and_then(|t| t.as_i64())
.unwrap_or(1);
- let season = self.state.selected_season;
- let episode = self.state.selected_episode;
- let clean_title = crate::providers::moviebox::clean_moviebox_title(title);
- let safe_title = crate::download::safe_file_stem(&clean_title);
-
- let extension = self
- .state
- .selected_resources
- .as_ref()
- .and_then(|resources| resources.get("list"))
- .and_then(|list| list.as_array())
- .and_then(|list| list.get(self.state.resource_list_state.selected().unwrap_or(0)))
- .and_then(|resource| {
- resource
- .get("fileName")
- .or_else(|| resource.get("title"))
- .and_then(|name| name.as_str())
+ let season = self.state.selected_season.saturating_add(1);
+ let episode = self.state.selected_episode.saturating_add(1);
+ let safe_title = title
+ .chars()
+ .map(|c| {
+ if c.is_alphanumeric() || c == '-' || c == '_' || c == ' ' {
+ c
+ } else {
+ '_'
+ }
})
- .and_then(|name| std::path::Path::new(name).extension())
- .and_then(|extension| extension.to_str())
- .filter(|extension| {
- matches!(
- extension.to_ascii_lowercase().as_str(),
- "mp4" | "mkv" | "webm" | "avi" | "mov" | "m4v"
- )
+ .collect::<String>()
+ .trim()
+ .to_string();
+
+ let extension = link
+ .split('?')
+ .next()
+ .and_then(|path| path.rsplit('.').next())
+ .filter(|ext| {
+ let lower = ext.to_ascii_lowercase();
+ lower == "mp4" || lower == "mkv" || lower == "webm" || lower == "ts"
})
.unwrap_or("mp4")
.to_ascii_lowercase();
- 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
- };
-
- let base_dir = base_dir.join("MovieBox-TUI");
+ let base_dir = self.resolve_download_base_dir();
let (target_dir, base_name) = if media_type == 2 {
(
base_dir
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 3509340..1687b6a 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -51,6 +51,7 @@ impl App {
};
state.active_theme_kind = config.active_theme;
state.default_player = config.default_player;
+ state.download_dir = config.download_dir.map(std::path::PathBuf::from);
let mut theme = crate::tui::theme::Theme::new();
if let Ok(theme_env) = std::env::var("MOVIEBOX_THEME") {
@@ -101,6 +102,11 @@ impl App {
active_theme: self.state.active_theme_kind.clone(),
bdix_enabled: self.state.bdix_enabled,
default_player: self.state.default_player.clone(),
+ download_dir: self
+ .state
+ .download_dir
+ .as_ref()
+ .map(|p| p.to_string_lossy().to_string()),
};
crate::tui::config::save(&config);
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 7534d7c..f9c0213 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -21,6 +21,10 @@ impl App {
commands.push("/browse");
commands.push("/history");
}
+ commands.push("/download-dir");
+ if self.state.download_dir.is_some() {
+ commands.push("/download-dir reset");
+ }
commands.push("/theme");
commands.push("/update");
commands.push("/toggle-update");
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index 2ff663d..3325206 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -182,6 +182,101 @@ impl App {
self.action_sender.send(Action::ShowBrowseMenu).ok();
return Some(true);
}
+ if lower_query.starts_with("/download-dir") {
+ let raw_arg = query.strip_prefix("/download-dir").unwrap_or("").trim();
+ self.state.search_query.clear();
+ self.state.input_mode = InputMode::Normal;
+
+ if raw_arg.is_empty() {
+ let current = if let Some(ref custom) = self.state.download_dir {
+ custom.to_string_lossy().to_string()
+ } else {
+ let default_base = dirs::download_dir()
+ .or_else(|| dirs::home_dir().map(|h| h.join("Downloads")))
+ .unwrap_or_else(|| std::path::PathBuf::from("."));
+ default_base
+ .join("MovieBox-TUI")
+ .to_string_lossy()
+ .to_string()
+ };
+ self.state.notify(
+ NotificationKind::Info,
+ "Download Directory",
+ format!(
+ "{}\nSet: /download-dir <path> | Reset: /download-dir reset",
+ current
+ ),
+ );
+ return Some(true);
+ }
+
+ if raw_arg.eq_ignore_ascii_case("reset") || raw_arg.eq_ignore_ascii_case("default") {
+ if self.state.download_dir.is_none() {
+ self.state.notify(
+ NotificationKind::Info,
+ "Download Directory",
+ "Already using system default (Downloads/MovieBox-TUI)",
+ );
+ } else {
+ self.state.download_dir = None;
+ self.persist_config();
+ self.state.notify(
+ NotificationKind::Success,
+ "Download Directory",
+ "Reset to default (Downloads/MovieBox-TUI)",
+ );
+ }
+ return Some(true);
+ }
+
+ let expanded_path = if let Some(stripped) = raw_arg.strip_prefix("~/") {
+ if let Some(home) = dirs::home_dir() {
+ home.join(stripped)
+ } else {
+ std::path::PathBuf::from(raw_arg)
+ }
+ } else if raw_arg == "~" {
+ dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(raw_arg))
+ } else {
+ std::path::PathBuf::from(raw_arg)
+ };
+
+ match std::fs::create_dir_all(&expanded_path) {
+ Ok(_) => {
+ let test_file = expanded_path.join(format!(".mb_probe_{}", std::process::id()));
+ match std::fs::write(&test_file, b"ok") {
+ Ok(_) => {
+ let _ = std::fs::remove_file(&test_file);
+ let canonical =
+ std::fs::canonicalize(&expanded_path).unwrap_or(expanded_path);
+ self.state.download_dir = Some(canonical.clone());
+ self.persist_config();
+ self.state.notify(
+ NotificationKind::Success,
+ "Download Directory",
+ format!("Saved: {}", canonical.display()),
+ );
+ }
+ Err(err) => {
+ self.state.notify(
+ NotificationKind::Error,
+ "Permission Denied",
+ format!("Cannot write to '{}': {}", expanded_path.display(), err),
+ );
+ }
+ }
+ }
+ Err(err) => {
+ self.state.notify(
+ NotificationKind::Error,
+ "Invalid Directory",
+ format!("Cannot create '{}': {}", expanded_path.display(), err),
+ );
+ }
+ }
+
+ return Some(true);
+ }
if lower_query == "/toggle-update" {
self.state.auto_update = !self.state.auto_update;
self.persist_config();
diff --git a/src/tui/config.rs b/src/tui/config.rs
index 03962d3..dd663ca 100644
--- a/src/tui/config.rs
+++ b/src/tui/config.rs
@@ -8,6 +8,7 @@ pub struct Config {
pub active_theme: String,
pub bdix_enabled: bool,
pub default_player: Option<String>,
+ pub download_dir: Option<String>,
}
impl Default for Config {
@@ -19,6 +20,7 @@ impl Default for Config {
active_theme: String::new(),
bdix_enabled: false,
default_player: None,
+ download_dir: None,
}
}
}
@@ -57,6 +59,9 @@ pub fn load() -> Config {
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
}
@@ -75,7 +80,8 @@ pub fn save(config: &Config) {
"active_provider": config.active_provider.cache_key(),
"active_theme": config.active_theme,
"bdix_enabled": config.bdix_enabled,
- "default_player": config.default_player
+ "default_player": config.default_player,
+ "download_dir": config.download_dir
});
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 1634061..2272515 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -55,6 +55,8 @@ pub(crate) fn slash_command_description(cmd: &str) -> Option<&'static str> {
let name = cmd.strip_prefix('/').unwrap_or(cmd);
match name {
"browse" => Some("Curated, rated & most-watched views"),
+ "download-dir" => Some("Change or view download directory"),
+ "download-dir reset" => Some("Reset download directory to default"),
"history" => Some("Watch history"),
"theme" => Some("Theme picker"),
"list" => Some("IPTV channels"),
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 1fd96e1..428a79b 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -247,6 +247,7 @@ pub struct AppState {
pub download_progress: Option<f64>,
pub download_status: Option<String>,
pub cancel_download: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ pub download_dir: Option<std::path::PathBuf>,
pub download_queue: std::collections::VecDeque<(usize, usize)>,
pub download_queue_total: usize,
@@ -371,6 +372,7 @@ impl Default for AppState {
download_progress: None,
download_status: None,
cancel_download: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ download_dir: None,
download_queue: std::collections::VecDeque::new(),
download_queue_total: 0,
language_chosen: false,