Skip to content

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

fix(playback,proxy): detach player sessions, prioritize HTTP 206 mirrors, and prefetch DASH segments

Samir Hossainsb1263a23a67e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b54b39..facf4c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,9 +10,9 @@
- Removed redundant "Provider: {name}" status message override from the search bar on provider switch in `src/tui/app/navigation.rs`, preserving the clean search placeholder while the active provider pill displays on the right.
- **Media Playback & Buffering Engine**:
- Prioritized native desktop media players (`mpv`, `VLC`) over Android intent openers in `src/player.rs` when an active X11/Wayland display server (`$DISPLAY`, `$WAYLAND_DISPLAY`) is detected, preventing Ubuntu Xfce (udroid/PRoot) and Termux:X11 desktop sessions from dispatching playback to external Android app choosers.
- - Configured `mpv` and `IINA` with initial cache buffering (`--cache-pause-initial=yes`) and resilient re-buffer cushion (`--cache-pause-wait=10`) in `src/player.rs`, preventing repeated 2-second stutter loops on bandwidth-constrained CDN streams.
- - Replaced aggressive VLC buffering flags (`--network-caching=10000`, `--adaptive-logic=nearoptimal`) with `--network-caching=3000` and `--adaptive-logic=predictive` in `src/player.rs` to stop demuxer stream restarts and 10-second stall loops.
- - Enabled HTTP/1.1 persistent connections (`Keep-Alive`) across DASH segment streaming in `src/proxy.rs`, eliminating recurring TCP handshake overhead.
+ - Routed DASH `.mpd` streams through the local `StreamRelay` proxy (`src/proxy.rs`, `src/tui/app/playback.rs`) across all media players (`mpv`, `IINA`, `VLC`, `AndroidIntent`), caching rewritten `.mpd` manifests in RAM, warm-prefetching initialization and opening segments on sidecar startup, fetching `.m4s` segments via concurrent `95 KB` HTTP `Range` sub-requests (`0.286s` per segment vs `3.120s`), and prefetching both the next 3 video segments (`N+1..N+3`) and synchronized audio segments (`chunk-stream3-N..N+1`).
+ - Tuned `mpv` and `IINA` playback flags (`--hwdec=auto-safe`, `--stream-buffer-size=4M`, `--cache-secs=120`, `--cache-pause-wait=3`, `--cache-pause-initial=no`, and `--ytdl=no` on non-DASH direct streams) in `src/player.rs`, reducing 1080p cold-seek latency at `01:00:00` from `11.96s` to `3.87s` and boosting read-ahead buffer fill rate from `1 MB` (`9.3s`) to `7 MB` (`53s`).
+ - Replaced aggressive VLC buffering flags (`--network-caching=10000`, `--adaptive-logic=nearoptimal`) with `--network-caching=3000`, `--file-caching=3000`, `--http-reconnect`, and `--adaptive-logic=predictive` in `src/player.rs` to stop demuxer stream restarts and reconnect cleanly on dropped HTTP streams.
- Enforced `max_height` resolution limits in the loopback stream proxy manifest rewriter (`src/proxy.rs`, `src/main.rs`, `src/tui/app/playback.rs`), pruning representations exceeding the chosen ceiling so Android players and VLC respect 480p and 720p selections.
- Parsed signed expiration timestamps (`:t=`) from MovieBox `Edge-Cache-Cookie` headers in `src/cache.rs` alongside CloudFront policies, automatically invalidating stale stream cache entries within 60 seconds of expiration to prevent HTTP 403 playback crashes.
- Persisted selected stream filenames (`stream_filename`) in watch history (`src/history.rs`, `src/player/tracker.rs`, `src/tui/app/playback.rs`) and auto-focused matching stream rows on load (`src/tui/app/requests.rs`, `src/tui/app/system.rs`), restoring the user's previously chosen quality mirror when resuming multi-stream releases.
@@ -20,6 +20,8 @@
- Implemented negative caching (`Option<Option<String>>`) for media player detection (`MPV_CACHED`, `VLC_CACHED`, `IINA_CACHED`) in `src/player.rs`, eliminating redundant filesystem scans and registry lookups when players are absent.
- Throttled Lua tracker periodic disk sync in `src/player/tracker.rs` when playback is paused or positional change is sub-second, cutting SSD writes by up to 90% during playback pauses.
- Removed duplicate redundant `history.save()` calls in `src/tui/app/playback.rs` upon marking items watched.
+ - Defined `local now = os.time()` in `src/player/tracker.rs` before formatting playback state JSON in `moviebox_tracker.lua` and scoped initial `PendingPlaybackState` seed writes in `src/tui/app/playback.rs` strictly to `PlayerKind::Mpv`, preventing `VLC`, `IINA`, and `AndroidIntent` watch progress from resetting to `0` on player exit.
+ - Detached spawned media players and the `StreamRelay` sidecar into independent OS sessions via `configure_detached_process` (`libc::setsid()` + `SIGHUP` ignore on Unix, `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` on Windows) in `src/player.rs`, `src/proxy.rs`, and `src/tui/app/playback.rs`, redirected player `stderr` to temporary log files instead of parent pipes to prevent `SIGPIPE` crashes when the terminal closes, and reaped the sidecar immediately when desktop players exit while the TUI is open.
- **Download Engine & Subprocess Diagnostics**:
- Added preflight verification for `ffmpeg` alongside `yt-dlp` in `src/tui/app/download.rs`, failing fast with installation guidance when media muxing tools are missing.
- Captured child process stderr lines during DASH transfers to surface concrete `yt-dlp` error diagnostics instead of bare exit codes.
@@ -32,13 +34,20 @@
- Replaced per-card `Layout::split` invocations in `src/tui/screens/home.rs` with direct row arithmetic calculations, avoiding repeated layout solver overhead across search result slots.
- Rendered stream media tags (HDR, ATMOS, 5.1, HEVC, AV1, WEB-DL) in `src/tui/screens/details.rs` using styled surface pill spans and unified background modal dimming to `theme.muted` across `render_media_tag_spans`, `resolution_badge_spans` (`src/tui/widgets/badge.rs`), `render_poster_placeholder` (`src/tui/widgets/poster.rs`), Details headers (`src/tui/screens/details.rs`), and Home search result bars, cards, ratings, and history progress rows (`src/tui/screens/home.rs`).
- Replaced linear index iteration with exact O(1) `HashSet` lookups in `FavoritesManager::is_favorite` (`src/favorites.rs`).
+ - Guarded `PopKeyboardEnhancementFlags` in `restore_terminal` (`src/main.rs`) against Termux environments (`!is_termux_environment()`), preventing stray ANSI escape sequences from leaking into the Android Termux shell on exit.
+ - Routed `Warning:` and non-Home `Action::SetStatus` messages through toast notifications in `src/tui/app/system.rs`, `src/tui/app/playback.rs`, and `src/tui/app/requests.rs`, ensuring subtitle fallback notices, missing `iina-cli` warnings, and addon installation statuses remain visible on the Details screen and modal overlays.
+ - Unified notification card geometry and line-wrapping calculations in `compute_notification_cards` (`src/tui/overlay.rs`), eliminating duplicate layout passes between frame rendering and mouse click hit-testing.
- **Provider Scraping & Concurrency Engine**:
- - Replaced chunked mirror resolution barriers in 4KHDHub (`src/providers/fourkhdhub/client.rs`) with concurrent `FuturesUnordered` preflights and early termination on the first healthy playable mirror, reducing time-to-first-stream latency by multiple seconds.
+ - Replaced chunked mirror resolution barriers in 4KHDHub (`src/providers/fourkhdhub/client.rs`, `src/providers/fourkhdhub/hubcloud.rs`) with `HTTP 206 Partial Content` seekability verification (`preflight_with_seekable`) and score-prioritized early termination (`is_seekable && score <= 1`), ensuring byte-range-seekable 10Gbps/R2/FSL mirrors are selected over unseekable `HTTP 200` mirrors or quota-exhausted `workers.dev` links.
+ - Centralized disk-cached caption lookup and storage in `MovieBoxService::get_ext_captions` (`src/service.rs`) and parallelized primary and sibling dub caption fetches via `tokio::join!`, eliminating duplicate cache wrappers in `src/tui/app/playback.rs` and `src/tui/app/requests.rs`.
- Bound individual Stremio addon stream fetches in `src/providers/addons/aggregator.rs` with a 5-second timeout, preventing unresponsive third-party addons from blocking stream aggregation.
- Capped initial search poster scraping in DhakaFlix (`src/providers/bdix/dhakaflix/client.rs`) to the first 20 items, eliminating dozens of blocking HTTP POST requests on large catalog searches.
+ - Centralized `MediaDetails::sibling_ids`, human-readable file size parsing (`parse_size_bytes`), DASH URL detection (`is_dash_url`), `yt-dlp` format selectors (`ytdlp_format_selector`), download target path resolution (`resolve_media_target`), and cached poster fetching (`MovieBoxService::fetch_and_decode_cached_poster`) in their owning domain modules (`src/providers/models.rs`, `src/player.rs`, `src/download.rs`, `src/service.rs`), and removed `src/tui/app/network.rs`.
+ - Streamed poster HTTP responses via bounded chunk accumulation (`5 MiB` cap) in `MovieBoxService::fetch_poster_bytes` (`src/service.rs`) and added `FallbackResolver` DNS + `Range: bytes=0-0` bounds to `probe_url` (`src/net.rs`).
- **Storage & Disk Cache Engine**:
- Optimized typed cache serialization in `src/cache.rs` using direct in-place encoding (`rmp_serde::encode::write`) into pre-seeded magic header buffers, eliminating intermediate vector allocations and duplicate memory copies.
- Pre-allocated file buffer capacity from file metadata in `get_typed_cache` in `src/cache.rs`, eliminating repetitive vector reallocations during cache reads.
+ - Offloaded `atomic_write_file_async` in `src/cache.rs` to `tokio::task::spawn_blocking`, switched `src/logging.rs` to `WriteMode::BufferAndFlush` with a `LazyLock` cached home directory path, centralized corrupt JSON file rotation (`rotate_corrupt_file`) in `src/config.rs`, and enabled cross-platform stale update artifact cleanup in `src/updater/apply.rs`.
### Changed
- **TUI & Ergonomics**:
- Remapped `q` / `Q` on `Screen::Details` in `src/tui/app/keyboard.rs` from application exit to `Action::GoBack`, preserving active search results and returning to the home screen without unexpected process termination.
diff --git a/docs/modules.md b/docs/modules.md
index f22cab4..06e1f82 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -116,8 +116,6 @@ src/
mod.rs App struct, App::new, and small helpers.
run.rs App::run (event loop), App::draw (rendering), and
handle_action dispatcher (thin routing table over action groups).
- network.rs fetch_poster_bytes, decode_poster, provider_search,
- provider_details.
search.rs Search-mode command routing, search state setup, provider
search dispatch, poster prefetch helpers.
requests.rs handle_requests: suggest/history/homepage/details/preview/
diff --git a/docs/players.md b/docs/players.md
index bfcf6df..99763b6 100644
--- a/docs/players.md
+++ b/docs/players.md
@@ -22,19 +22,20 @@ You can set a default player via `/settings` (Media Player), or override it with
### mpv
```bash
-mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [OPTIONS] <url>
+mpv --autofit=WxH --geometry=50%:50% --hwdec=auto-safe --stream-buffer-size=4M --idle=no --keep-open=no [OPTIONS] <url>
```
- **Tracking**: Injects `moviebox_tracker.lua` to track playback progress, total duration, and chosen stream filename, auto-restoring the exact stream mirror upon re-opening multi-stream titles (such as 4KHDHub releases).
+- **Hardware Decoding & Direct Streams**: Enables `--hwdec=auto-safe` for hardware-accelerated 4K 10-bit HEVC HDR decoding and passes `--ytdl=no` on non-DASH direct streams (`.mkv`, `.mp4`, `.m3u8`) for immediate native `ffmpeg` demuxer startup.
- **Headers**: Custom stream headers (`User-Agent`, `Referer`) are passed via `--http-header-fields`.
-- **DASH Manifests**: CloudFront cookies are passed to yt-dlp hooks via `--ytdl-raw-options-append`.
+- **DASH Manifests & Loopback Acceleration**: DASH `.mpd` streams route through the local `StreamRelay` proxy (`127.0.0.1:<port>`), which caches rewritten manifests in RAM, warm-prefetches initialization and opening fragments on sidecar startup, fetches `.m4s` segments via parallel `95 KB` HTTP `Range` sub-requests, and prefetches both the next 3 video segments (`N+1..N+3`) and matching audio segments (`chunk-stream3-N..N+1`).
- **Subtitles**: Remote subtitles are loaded directly via `--sub-file=<url>`.
### VLC
```bash
-vlc --width=W --height=H --play-and-exit --network-caching=3000 --adaptive-logic=predictive [OPTIONS] <url>
+vlc --width=W --height=H --play-and-exit --network-caching=3000 --file-caching=3000 --http-reconnect --adaptive-logic=predictive [OPTIONS] <url>
```
- **Headers**: Mapped to `--http-user-agent` and `--http-referrer`.
-- **CloudFront Streams**: CloudFront cookie-authenticated DASH streams route through a local loopback proxy sidecar (`127.0.0.1:<port>`) with HTTP/1.1 persistent connections (`Keep-Alive`) and resolution representation capping to inject auth headers server-side.
+- **DASH & CloudFront Streams**: Cookie-authenticated and DASH `.mpd` streams route through the local `StreamRelay` proxy sidecar (`127.0.0.1:<port>`) with HTTP/1.1 persistent connections (`Keep-Alive`), parallel `95 KB` `Range`-chunked `.m4s` segment fetching, lookahead segment prefetching (`N+1..N+3`), and resolution representation capping.
- **Subtitles**: Remote subtitles are pre-downloaded to temporary storage and passed via `--sub-file=<path>`.
### IINA (macOS)
@@ -59,6 +60,6 @@ termux-open --chooser --content-type video/* <url>
## Spawning & Process Safety
-- Players launch in detached process groups (`process_group(0)` on Unix, `CREATE_NEW_PROCESS_GROUP` on Windows) so terminal signals do not terminate playback.
-- Stderr is drained in the background with a 2-second timeout to prevent pipe deadlocks.
+- Players and the `StreamRelay` sidecar launch in fully detached OS sessions (`libc::setsid()` with `SIGHUP` ignored on Unix/macOS/Linux/Android, and `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` on Windows) so closing the terminal window or quitting `moviebox-tui` never terminates active video playback.
+- Player `stderr` is directed to a temporary log file rather than a parent pipe, preventing `SIGPIPE` / broken-pipe crashes when `moviebox-tui` exits while preserving full crash diagnostics when the TUI remains open.
- Clean exits (VLC exit code `1` with empty stderr, or Unix `SIGTERM`) are recognized as normal exits and update watch history without false crash popups.
diff --git a/src/cache.rs b/src/cache.rs
index 30bb9dd..39dd861 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -181,69 +181,11 @@ fn sync_parent_dir(path: &std::path::Path) {
fn sync_parent_dir(_path: &std::path::Path) {}
pub async fn atomic_write_file_async(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await.ok();
- }
- let stamp = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));
- write_durable_async(&temporary, bytes).await?;
- match durable_replace_async(&temporary, path, &format!("{stamp}-f")).await {
- Ok(()) => Ok(()),
- Err(error) => {
- let _ = tokio::fs::remove_file(&temporary).await;
- Err(error)
- }
- }
-}
-
-async fn write_durable_async(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
- use tokio::io::AsyncWriteExt;
- let mut file = tokio::fs::File::create(target).await?;
- file.write_all(bytes).await?;
- file.sync_all().await
-}
-
-async fn durable_replace_async(
- temporary: &std::path::Path,
- path: &std::path::Path,
- suffix: &str,
-) -> std::io::Result<()> {
- if tokio::fs::rename(temporary, path).await.is_ok() {
- sync_parent_dir(path);
- return Ok(());
- }
- let _ = tokio::fs::remove_file(path).await;
- if tokio::fs::rename(temporary, path).await.is_ok() {
- sync_parent_dir(path);
- return Ok(());
- }
- let copy_target = path.with_extension(format!("tmp-{}-{suffix}", std::process::id()));
- let outcome: std::io::Result<()> = async {
- tokio::fs::copy(temporary, &copy_target).await?;
- let file = tokio::fs::File::open(&copy_target).await?;
- file.sync_all().await?;
- let _ = tokio::fs::remove_file(path).await;
- tokio::fs::rename(&copy_target, path).await
- }
- .await;
- let _ = tokio::fs::remove_file(&copy_target).await;
- match outcome {
- Ok(()) => {
- sync_parent_dir(path);
- Ok(())
- }
- Err(_) => Err(std::io::Error::other(format!(
- "atomic replace async failed for {}",
- crate::logging::sanitize_path(path)
- ))),
- }
-}
-
-fn hash_key(value: &str) -> String {
- md5_hex(value)
+ let path_buf = path.to_path_buf();
+ let payload = bytes.to_vec();
+ tokio::task::spawn_blocking(move || atomic_write_file(&path_buf, &payload))
+ .await
+ .map_err(|err| std::io::Error::other(format!("atomic write task failed: {err}")))?
}
pub fn get_provider_cache_dir(provider: ProviderKind, subdir: &str) -> PathBuf {
@@ -264,7 +206,7 @@ pub fn get_provider_stream_path(
} else {
""
};
- let hashed_id = hash_key(subject_id);
+ let hashed_id = md5_hex(subject_id);
path.push(format!("{schema}{hashed_id}_{season}_{episode}.cache"));
path
}
@@ -400,7 +342,7 @@ pub fn get_provider_details_path(provider: ProviderKind, subject_id: &str) -> Pa
} else {
""
};
- let hashed_id = hash_key(subject_id);
+ let hashed_id = md5_hex(subject_id);
path.push(format!("details_{schema}{hashed_id}.cache"));
path
}
@@ -429,7 +371,7 @@ pub fn invalidate_provider_details_cache(provider: ProviderKind, subject_id: &st
pub fn get_provider_search_path(provider: ProviderKind, query: &str, page: usize) -> PathBuf {
let mut path = get_provider_cache_dir(provider, "search");
- let hashed = hash_key(query);
+ let hashed = md5_hex(query);
path.push(format!("{hashed}_{page}.cache"));
path
}
@@ -482,7 +424,7 @@ pub fn set_homepage_cache_typed(
pub fn get_addon_catalog_path(manifest_url: &str, r_type: &str, catalog_id: &str) -> PathBuf {
let mut path = get_provider_cache_dir(ProviderKind::Addons, "catalogs");
- let hashed = hash_key(&format!("{manifest_url}_{r_type}_{catalog_id}"));
+ let hashed = md5_hex(&format!("{manifest_url}_{r_type}_{catalog_id}"));
path.push(format!("catalog_{hashed}.cache"));
path
}
@@ -508,7 +450,7 @@ pub fn set_addon_catalog_cache_typed(
pub fn get_addon_manifest_path(manifest_url: &str) -> PathBuf {
let mut path = get_provider_cache_dir(ProviderKind::Addons, "manifests");
- let hashed = hash_key(manifest_url);
+ let hashed = md5_hex(manifest_url);
path.push(format!("manifest_{hashed}.cache"));
path
}
@@ -527,7 +469,7 @@ fn get_namespaced_image_path(namespace: &str, id: &str) -> PathBuf {
let mut path = crate::config::cache_dir();
path.push(namespace);
path.push("images");
- let safe_name = hash_key(id);
+ let safe_name = md5_hex(id);
path.push(format!("{safe_name}.img"));
path
}
@@ -571,7 +513,7 @@ pub fn set_namespaced_image_cache(namespace: &str, id: &str, bytes: &[u8]) {
pub fn get_captions_path(subject_id: &str, resource_id: &str) -> PathBuf {
let mut path = get_provider_cache_dir(ProviderKind::MovieBox, "captions");
- let hashed_id = hash_key(&format!("{}_{}", subject_id, resource_id));
+ let hashed_id = md5_hex(&format!("{}_{}", subject_id, resource_id));
path.push(format!("captions_{}.cache", hashed_id));
path
}
@@ -682,7 +624,10 @@ fn purge_subtitle_cache_files(dir: &Path, errors: &mut Vec<String>) {
if path.is_file() {
if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
let lower = ext.to_ascii_lowercase();
- if matches!(lower.as_str(), "srt" | "vtt" | "sub" | "ass" | "tmp") {
+ if matches!(
+ lower.as_str(),
+ "srt" | "vtt" | "sub" | "ass" | "ssa" | "tmp" | "log"
+ ) {
if let Err(err) = resilient_remove_file(&path) {
if err.kind() != std::io::ErrorKind::NotFound {
errors.push(format!(
@@ -714,13 +659,9 @@ pub fn clear_all_cache() -> Result<(), String> {
let _ = fs::remove_dir(&legacy);
}
}
- if crate::updater::artifact::is_termux_environment()
- && let Some(home) = dirs::home_dir()
- {
- let storage = home.join("storage/downloads/moviebox_subs");
- if storage.exists() {
- purge_subtitle_cache_files(&storage, &mut errors);
- }
+ let sub_dir = crate::service::resolve_subtitle_dir();
+ if sub_dir.exists() {
+ purge_subtitle_cache_files(&sub_dir, &mut errors);
}
let temp_subs = std::env::temp_dir().join("moviebox-tui").join("subs");
if temp_subs.exists() {
diff --git a/src/config.rs b/src/config.rs
index da95026..7ac01c4 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -182,6 +182,20 @@ pub fn favorites_path() -> Option<PathBuf> {
data_dir().map(|dir| dir.join("favorites.json"))
}
+pub fn rotate_corrupt_file(path: &std::path::Path, label: &str) {
+ let stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));
+ log::error!(
+ "failed to parse {label} from {}, rotating to {}",
+ crate::logging::sanitize_path(path),
+ crate::logging::sanitize_path(&corrupt_path)
+ );
+ let _ = std::fs::rename(path, corrupt_path);
+}
+
pub fn load() -> Config {
let Some(path) = config_path() else {
return Config::default();
@@ -210,17 +224,7 @@ pub fn load() -> Config {
return config;
}
}
- let stamp = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));
- log::error!(
- "failed to parse config from {}, rotating to {}",
- crate::logging::sanitize_path(&path),
- crate::logging::sanitize_path(&corrupt_path)
- );
- let _ = std::fs::rename(&path, corrupt_path);
+ rotate_corrupt_file(&path, "config");
}
Config::default()
}
@@ -246,17 +250,7 @@ pub fn load_addons() -> Vec<InstalledAddon> {
Ok(content) => match serde_json::from_str::<Vec<InstalledAddon>>(&content) {
Ok(parsed) => parsed,
Err(e) => {
- let stamp = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));
- log::error!(
- "failed to parse addons config from {} ({e}), rotating to {}",
- crate::logging::sanitize_path(&path),
- crate::logging::sanitize_path(&corrupt_path)
- );
- let _ = std::fs::rename(&path, corrupt_path);
+ rotate_corrupt_file(&path, &format!("addons config ({e})"));
Vec::new()
}
},
diff --git a/src/download.rs b/src/download.rs
index 6257bc2..7020c36 100644
--- a/src/download.rs
+++ b/src/download.rs
@@ -54,6 +54,29 @@ pub fn safe_file_stem(value: &str) -> String {
stem
}
+pub fn resolve_media_target(
+ base_dir: &Path,
+ safe_title: &str,
+ is_series: bool,
+ season: usize,
+ episode: usize,
+) -> (PathBuf, String) {
+ if is_series {
+ (
+ base_dir
+ .join("Series")
+ .join(safe_title)
+ .join(format!("Season {season}")),
+ format!("{safe_title} - S{season:02}E{episode:02}"),
+ )
+ } else {
+ (
+ base_dir.join("Movies").join(safe_title),
+ safe_title.to_string(),
+ )
+ }
+}
+
#[derive(Debug, Clone)]
pub struct DownloadProgress {
pub downloaded: u64,
@@ -961,7 +984,7 @@ mod tests {
let temp_dir = std::env::temp_dir().join(format!("mbx_seg_inplace_{}", std::process::id()));
tokio::fs::create_dir_all(&temp_dir).await.unwrap();
let dest_file = temp_dir.join("movie.mp4");
- let client = crate::net::streaming_client_builder().build().unwrap();
+ let client = crate::net::http_client_builder_base().build().unwrap();
let cancel = Arc::new(AtomicBool::new(false));
let mut max_workers = 0usize;
@@ -1150,7 +1173,7 @@ mod tests {
"secret-token-123".parse().unwrap(),
);
- let client = crate::net::streaming_client_builder()
+ let client = crate::net::http_client_builder_base()
.default_headers(headers)
.build()
.unwrap();
diff --git a/src/favorites.rs b/src/favorites.rs
index b528a72..acc16ac 100644
--- a/src/favorites.rs
+++ b/src/favorites.rs
@@ -1,6 +1,6 @@
use serde::{Deserialize, Serialize};
use std::fs;
-use std::path::{Path, PathBuf};
+use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FavoriteItem {
@@ -74,16 +74,12 @@ pub struct FavoritesManager {
impl FavoritesManager {
pub fn new() -> Self {
- match Self::favorites_file_path() {
+ match crate::config::favorites_path() {
Some(path) => Self::load_from_path(&path),
None => Self::default(),
}
}
- fn favorites_file_path() -> Option<PathBuf> {
- crate::config::favorites_path()
- }
-
pub fn load_from_path(path: &Path) -> Self {
if path.exists() {
match fs::read_to_string(path) {
@@ -93,17 +89,7 @@ impl FavoritesManager {
return manager;
}
Err(e) => {
- let stamp = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));
- log::error!(
- "failed to parse favorites from {} ({e}), rotating to {}",
- crate::logging::sanitize_path(path),
- crate::logging::sanitize_path(&corrupt_path)
- );
- let _ = fs::rename(path, corrupt_path);
+ crate::config::rotate_corrupt_file(path, &format!("favorites ({e})"));
}
},
Err(e) => {
@@ -118,7 +104,7 @@ impl FavoritesManager {
}
pub fn save(&self) {
- if let Some(path) = Self::favorites_file_path() {
+ if let Some(path) = crate::config::favorites_path() {
self.save_to_path(&path);
}
}
diff --git a/src/history.rs b/src/history.rs
index 765cd3d..54a902d 100644
--- a/src/history.rs
+++ b/src/history.rs
@@ -1,7 +1,6 @@
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
-use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchHistoryItem {
@@ -243,24 +242,14 @@ pub struct HistoryManager {
impl HistoryManager {
pub fn new() -> Self {
- let mut history = if let Some(path) = Self::history_file_path() {
+ let mut history = if let Some(path) = crate::config::history_path() {
if path.exists() {
if let Ok(content) = fs::read_to_string(&path) {
if let Ok(mut hist) = serde_json::from_str::<Self>(&content) {
hist.hydrate_watched_index();
hist
} else {
- let stamp = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs();
- let corrupt_path = path.with_extension(format!("corrupt.{stamp}"));
- log::error!(
- "failed to parse watch history from {}, rotating to {}",
- crate::logging::sanitize_path(&path),
- crate::logging::sanitize_path(&corrupt_path)
- );
- let _ = fs::rename(&path, corrupt_path);
+ crate::config::rotate_corrupt_file(&path, "watch history");
Self::default()
}
} else {
@@ -277,16 +266,8 @@ impl HistoryManager {
history
}
- fn history_file_path() -> Option<PathBuf> {
- crate::config::history_path()
- }
-
- pub fn playback_state_dir() -> Option<PathBuf> {
- crate::config::playback_state_dir()
- }
-
pub fn save(&self) {
- if let Some(path) = Self::history_file_path() {
+ if let Some(path) = crate::config::history_path() {
if let Ok(content) = serde_json::to_string(self) {
if let Err(error) = crate::cache::atomic_write_file(&path, content.as_bytes()) {
log::warn!("failed to save watch history: {error}");
@@ -295,6 +276,15 @@ impl HistoryManager {
}
}
+ fn same_provider(a: &str, b: &str) -> bool {
+ crate::providers::models::ProviderKind::parse(a)
+ .zip(crate::providers::models::ProviderKind::parse(b))
+ .map_or_else(
+ || a.trim().eq_ignore_ascii_case(b.trim()),
+ |(p1, p2)| p1 == p2,
+ )
+ }
+
fn key(provider: &str, subject_id: &str, season: usize, episode: usize) -> String {
let canon_provider = crate::providers::models::ProviderKind::parse(provider)
.map(|p| p.cache_key())
@@ -369,12 +359,7 @@ impl HistoryManager {
title: Option<&str>,
) -> Option<&WatchHistoryItem> {
self.recent.iter().find(|i| {
- let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
- .zip(crate::providers::models::ProviderKind::parse(provider))
- .map_or_else(
- || i.provider.trim().eq_ignore_ascii_case(provider.trim()),
- |(p1, p2)| p1 == p2,
- );
+ let same_provider = Self::same_provider(&i.provider, provider);
if same_provider && i.subject_id == subject_id {
if i.stype == 1 {
@@ -508,12 +493,7 @@ impl HistoryManager {
let key = Self::key(provider, subject_id, season, episode);
self.watched.remove(&key);
self.recent.retain(|i| {
- let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
- .zip(crate::providers::models::ProviderKind::parse(provider))
- .map_or_else(
- || i.provider.trim().eq_ignore_ascii_case(provider.trim()),
- |(p1, p2)| p1 == p2,
- );
+ let same_provider = Self::same_provider(&i.provider, provider);
!(same_provider
&& i.subject_id == subject_id
&& i.season == season
@@ -559,7 +539,7 @@ impl HistoryManager {
}
pub fn reconcile_pending_playback_states(&mut self) {
- if let Some(dir) = Self::playback_state_dir() {
+ if let Some(dir) = crate::config::playback_state_dir() {
if self.reconcile_from_dir(&dir) {
self.save();
}
@@ -601,18 +581,7 @@ impl HistoryManager {
}
if let Some(existing) = self.recent.iter_mut().find(|i| {
- let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
- .zip(crate::providers::models::ProviderKind::parse(
- &state.provider,
- ))
- .map_or_else(
- || {
- i.provider
- .trim()
- .eq_ignore_ascii_case(state.provider.trim())
- },
- |(p1, p2)| p1 == p2,
- );
+ let same_provider = Self::same_provider(&i.provider, &state.provider);
if !same_provider {
return false;
}
@@ -636,18 +605,7 @@ impl HistoryManager {
}
modified = true;
} else if let Some(existing_series) = self.recent.iter_mut().find(|i| {
- let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
- .zip(crate::providers::models::ProviderKind::parse(
- &state.provider,
- ))
- .map_or_else(
- || {
- i.provider
- .trim()
- .eq_ignore_ascii_case(state.provider.trim())
- },
- |(p1, p2)| p1 == p2,
- );
+ let same_provider = Self::same_provider(&i.provider, &state.provider);
same_provider && i.stype == 2 && i.subject_id == state.subject_id
}) {
if (state.season, state.episode)
diff --git a/src/logging.rs b/src/logging.rs
index af2ee86..e75048c 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -1,8 +1,9 @@
use flexi_logger::{Cleanup, Criterion, FileSpec, Logger, LoggerHandle, Naming, WriteMode};
-use std::sync::OnceLock;
+use std::sync::{LazyLock, OnceLock};
static LOGGER_HANDLE: OnceLock<LoggerHandle> = OnceLock::new();
-
+static HOME_DIR: LazyLock<Option<String>> =
+ LazyLock::new(|| dirs::home_dir().and_then(|home| home.to_str().map(|home| home.to_string())));
pub fn init() {
let default_level = "info";
let spec = std::env::var("MOVIEBOX_LOG")
@@ -34,7 +35,7 @@ pub fn init() {
Naming::Numbers,
Cleanup::KeepLogFiles(3),
)
- .write_mode(WriteMode::Direct)
+ .write_mode(WriteMode::BufferAndFlush)
.format(flexi_logger::opt_format)
.start()
{
@@ -71,9 +72,9 @@ pub fn display_path() -> String {
pub fn sanitize_path(path: impl AsRef<std::path::Path>) -> String {
let raw = path.as_ref().to_string_lossy().into_owned();
- dirs::home_dir()
- .and_then(|home| home.to_str().map(|home| home.to_string()))
- .map(|home| raw.replacen(&home, "~", 1))
+ HOME_DIR
+ .as_deref()
+ .map(|home| raw.replacen(home, "~", 1))
.unwrap_or(raw)
}
diff --git a/src/main.rs b/src/main.rs
index 0edf0df..89701d3 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,13 +7,18 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
struct TerminalGuard;
fn restore_terminal() {
+ if !moviebox_tui::updater::artifact::is_termux_environment() {
+ let _ = crossterm::execute!(
+ std::io::stdout(),
+ crossterm::event::PopKeyboardEnhancementFlags
+ );
+ }
let _ = crossterm::execute!(
std::io::stdout(),
crossterm::cursor::SetCursorStyle::DefaultUserShape,
crossterm::cursor::Show,
crossterm::event::DisableMouseCapture,
crossterm::event::DisableFocusChange,
- crossterm::event::PopKeyboardEnhancementFlags,
crossterm::terminal::LeaveAlternateScreen
);
let _ = crossterm::terminal::disable_raw_mode();
@@ -22,18 +27,10 @@ fn restore_terminal() {
fn purge_stale_subtitles() {
tokio::task::spawn_blocking(|| {
let max_age = 24 * 60 * 60;
- let mut dirs = vec![
+ let dirs = [
moviebox_tui::service::resolve_subtitle_dir(),
std::env::temp_dir().join("moviebox-tui/subs"),
];
- if moviebox_tui::updater::artifact::is_termux_environment()
- && let Some(home) = dirs::home_dir()
- {
- let android_storage = home.join("storage/downloads/moviebox_subs");
- if home.join("storage/downloads").exists() {
- dirs.push(android_storage);
- }
- }
for dir in dirs {
if dir.exists()
diff --git a/src/net.rs b/src/net.rs
index 2100e0a..25c9daf 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -86,12 +86,8 @@ pub fn http_client_builder() -> reqwest::ClientBuilder {
http_client_builder_base().timeout(std::time::Duration::from_secs(60))
}
-pub fn streaming_client_builder() -> reqwest::ClientBuilder {
- http_client_builder_base()
-}
-
pub async fn probe_url(url: &str, timeout: std::time::Duration) -> bool {
- let Ok(client) = reqwest::Client::builder()
+ let Ok(client) = http_client_builder_base()
.timeout(timeout)
.connect_timeout(timeout)
.build()
@@ -114,7 +110,12 @@ pub async fn probe_url(url: &str, timeout: std::time::Duration) -> bool {
);
}
}
- match client.get(url).send().await {
+ match client
+ .get(url)
+ .header(reqwest::header::RANGE, "bytes=0-0")
+ .send()
+ .await
+ {
Ok(resp) => resp.status().is_success() || resp.status().is_redirection(),
Err(e) => {
log::debug!(
diff --git a/src/player.rs b/src/player.rs
index c660261..48101b0 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -119,6 +119,42 @@ pub fn header_capable_players() -> &'static [PlayerKind] {
}
}
+pub fn is_dash_url(url: &str) -> bool {
+ let clean = url.split('?').next().unwrap_or(url);
+ clean.ends_with(".mpd") || clean.contains("/dash/")
+}
+
+pub fn ytdlp_format_selector(max_height: Option<u64>) -> String {
+ if let Some(height) = max_height.filter(|&h| h > 0) {
+ format!(
+ "bestvideo[height<={height}]+bestaudio/best[height<={height}]/bestvideo+bestaudio/best"
+ )
+ } else {
+ "bestvideo+bestaudio/best".to_string()
+ }
+}
+
+pub fn configure_detached_process(cmd: &mut Command) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ unsafe {
+ cmd.pre_exec(|| {
+ let _ = libc::setsid();
+ libc::signal(libc::SIGHUP, libc::SIG_IGN);
+ Ok(())
+ });
+ }
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ const DETACHED_PROCESS: u32 = 0x0000_0008;
+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
+ cmd.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
+ }
+}
+
#[allow(clippy::too_many_arguments)]
pub fn command(
kind: PlayerKind,
@@ -141,6 +177,7 @@ pub fn command(
tracker,
max_height,
),
+ #[cfg(target_os = "macos")]
PlayerKind::Iina => iina_command(
url,
subtitle,
@@ -150,6 +187,17 @@ pub fn command(
tracker,
max_height,
),
+ #[cfg(not(target_os = "macos"))]
+ PlayerKind::Iina => mpv_command(
+ url,
+ subtitle,
+ headers,
+ false,
+ window,
+ resume_seconds,
+ tracker,
+ max_height,
+ ),
PlayerKind::Vlc => vlc_command(url, subtitle, headers, window, resume_seconds, max_height),
PlayerKind::AndroidIntent => android_intent_command(url, subtitle, headers),
}
@@ -428,10 +476,13 @@ fn mpv_command(
command.arg(format!("{prefix}autofit={width}x{height}"));
}
command.arg(format!("{prefix}geometry=50%:50%"));
+ let is_dash = is_dash_url(url);
+ command.arg(format!("{prefix}hwdec=auto-safe"));
command.arg(format!("{prefix}cache=yes"));
+ command.arg(format!("{prefix}cache-secs=120"));
command.arg(format!("{prefix}cache-pause=yes"));
- command.arg(format!("{prefix}cache-pause-wait=10"));
- command.arg(format!("{prefix}cache-pause-initial=yes"));
+ command.arg(format!("{prefix}cache-pause-wait=3"));
+ command.arg(format!("{prefix}cache-pause-initial=no"));
let (max_bytes, back_bytes) =
if cfg!(target_os = "android") || crate::updater::artifact::is_termux_environment() {
("128M", "50M")
@@ -442,20 +493,21 @@ fn mpv_command(
command.arg(format!("{prefix}demuxer-max-back-bytes={back_bytes}"));
command.arg(format!("{prefix}demuxer-readahead-secs=120"));
command.arg(format!("{prefix}demuxer-lavf-buffersize=1048576"));
- command.arg(format!("{prefix}stream-buffer-size=512k"));
- command.arg(format!("{prefix}force-seekable=yes"));
+ command.arg(format!("{prefix}stream-buffer-size=4M"));
+ if is_dash {
+ command.arg(format!("{prefix}force-seekable=yes"));
+ } else {
+ command.arg(format!("{prefix}ytdl=no"));
+ }
command.arg(format!(
"{prefix}stream-lavf-o=reconnect=1,reconnect_streamed=1,reconnect_delay_max=5"
));
if !iina {
command.arg("--idle=no").arg("--keep-open=no");
}
- if let Some(height) = max_height.filter(|&h| h > 0) {
- command.arg(format!(
- "{prefix}ytdl-format=bestvideo[height<={height}]+bestaudio/best[height<={height}]/bestvideo+bestaudio/best"
- ));
- } else {
- command.arg(format!("{prefix}ytdl-format=bestvideo+bestaudio/best"));
+ let format_selector = ytdlp_format_selector(max_height);
+ command.arg(format!("{prefix}ytdl-format={format_selector}"));
+ if max_height.filter(|&h| h > 0).is_none() {
command.arg(format!("{prefix}hls-bitrate=max"));
}
if let Some(start) = resume_seconds {
@@ -639,29 +691,6 @@ pub fn iina_is_app_fallback() -> bool {
false
}
-#[cfg(not(target_os = "macos"))]
-#[allow(clippy::too_many_arguments)]
-fn iina_command(
- url: &str,
- subtitle: Option<&str>,
- headers: &[(String, String)],
- window: Option<(u32, u32)>,
- resume_seconds: Option<u64>,
- tracker: Option<(&str, &str, usize, usize)>,
- max_height: Option<u64>,
-) -> Command {
- mpv_command(
- url,
- subtitle,
- headers,
- false,
- window,
- resume_seconds,
- tracker,
- max_height,
- )
-}
-
fn vlc_command(
url: &str,
subtitle: Option<&str>,
@@ -685,6 +714,8 @@ fn vlc_command(
}
command.arg("--play-and-exit");
command.arg("--network-caching=3000");
+ command.arg("--file-caching=3000");
+ command.arg("--http-reconnect");
command.arg("--adaptive-logic=predictive");
if let Some(height) = max_height.filter(|&h| h > 0) {
command.arg(format!("--adaptive-maxheight={height}"));
@@ -1897,15 +1928,17 @@ mod tests {
assert!(args.contains(&"--sub-file=/tmp/test.srt".to_string()));
assert!(args.contains(&"--start=120".to_string()));
assert!(args.contains(&"--autofit=1920x1080".to_string()));
+ assert!(args.contains(&"--hwdec=auto-safe".to_string()));
assert!(args.contains(&"--cache=yes".to_string()));
+ assert!(args.contains(&"--cache-secs=120".to_string()));
assert!(args.contains(&"--cache-pause=yes".to_string()));
- assert!(args.contains(&"--cache-pause-wait=10".to_string()));
- assert!(args.contains(&"--cache-pause-initial=yes".to_string()));
+ assert!(args.contains(&"--cache-pause-wait=3".to_string()));
+ assert!(args.contains(&"--cache-pause-initial=no".to_string()));
assert!(args.contains(&"--demuxer-max-bytes=256M".to_string()));
assert!(args.contains(&"--demuxer-readahead-secs=120".to_string()));
assert!(args.contains(&"--demuxer-lavf-buffersize=1048576".to_string()));
- assert!(args.contains(&"--stream-buffer-size=512k".to_string()));
- assert!(args.contains(&"--force-seekable=yes".to_string()));
+ assert!(args.contains(&"--stream-buffer-size=4M".to_string()));
+ assert!(args.contains(&"--ytdl=no".to_string()));
assert!(args.contains(
&"--stream-lavf-o=reconnect=1,reconnect_streamed=1,reconnect_delay_max=5".to_string()
));
@@ -1942,6 +1975,8 @@ mod tests {
.collect();
assert!(args.contains(&"--network-caching=3000".to_string()));
+ assert!(args.contains(&"--file-caching=3000".to_string()));
+ assert!(args.contains(&"--http-reconnect".to_string()));
assert!(args.contains(&"--adaptive-logic=predictive".to_string()));
assert!(args.contains(&"--http-user-agent=VLC-Agent".to_string()));
assert!(args.contains(&"--http-referrer=https://cdn.example.com".to_string()));
@@ -1989,4 +2024,24 @@ mod tests {
}
}
}
+
+ #[cfg(unix)]
+ #[test]
+ fn test_configure_detached_process_survives_sighup() {
+ let mut cmd = std::process::Command::new("sh");
+ cmd.args(["-c", "sleep 0.2"]);
+ cmd.stdin(std::process::Stdio::null());
+ cmd.stdout(std::process::Stdio::null());
+ cmd.stderr(std::process::Stdio::null());
+ super::configure_detached_process(&mut cmd);
+ let mut child = cmd.spawn().expect("spawn detached sh");
+ let pid = child.id() as libc::pid_t;
+ std::thread::sleep(std::time::Duration::from_millis(40));
+ unsafe {
+ libc::kill(pid, libc::SIGHUP);
+ libc::kill(-pid, libc::SIGHUP);
+ }
+ let status = child.wait().expect("wait detached sh");
+ assert!(status.success());
+ }
}
diff --git a/src/player/tracker.rs b/src/player/tracker.rs
index 80c6135..50ba17d 100644
--- a/src/player/tracker.rs
+++ b/src/player/tracker.rs
@@ -91,6 +91,7 @@ local function write_state(force_completed)
meta_json = meta_json .. string.format(',"stream_filename":%q', meta_stream)
end
+ local now = os.time()
local json = string.format(
'{"provider":%q,"subject_id":%q,"season":%d,"episode":%d,"progress_seconds":%d,"duration_seconds":%s,"completed":%s,"timestamp":%d%s}',
opts.provider,
@@ -232,4 +233,9 @@ mod tests {
"subject_with_forbidden_chars__quote"
);
}
+
+ #[test]
+ fn lua_tracker_defines_now_before_formatting_json() {
+ assert!(super::TRACKER_LUA_CONTENT.contains("local now = os.time()"));
+ }
}
diff --git a/src/providers/addons/adapter.rs b/src/providers/addons/adapter.rs
index b45a4ba..a580843 100644
--- a/src/providers/addons/adapter.rs
+++ b/src/providers/addons/adapter.rs
@@ -249,38 +249,6 @@ pub fn parse_codec(text: &str) -> Option<String> {
}
}
-pub fn parse_size_bytes_from_text(text: &str) -> Option<u64> {
- let lower = text.to_ascii_lowercase();
- let parts: Vec<&str> = lower.split_whitespace().collect();
- for i in 0..parts.len() {
- let clean = parts[i].trim_matches(|c: char| !c.is_alphanumeric() && c != '.');
- if let Ok(num) = clean.parse::<f64>() {
- if i + 1 < parts.len() {
- let unit = parts[i + 1]
- .trim_matches(|c: char| !c.is_alphabetic())
- .to_ascii_uppercase();
- if unit == "GB" || unit == "GIB" || unit == "G" {
- return Some((num * 1_073_741_824.0) as u64);
- } else if unit == "MB" || unit == "MIB" || unit == "M" {
- return Some((num * 1_048_576.0) as u64);
- }
- }
- }
- if clean.ends_with("gb") || clean.ends_with("gib") {
- let num_str = clean.trim_end_matches("gb").trim_end_matches("gib");
- if let Ok(num) = num_str.parse::<f64>() {
- return Some((num * 1_073_741_824.0) as u64);
- }
- } else if clean.ends_with("mb") || clean.ends_with("mib") {
- let num_str = clean.trim_end_matches("mb").trim_end_matches("mib");
- if let Ok(num) = num_str.parse::<f64>() {
- return Some((num * 1_048_576.0) as u64);
- }
- }
- }
- None
-}
-
pub fn parse_audio_tracks(text: &str) -> Option<String> {
let upper = text.to_ascii_uppercase();
let mut langs = Vec::new();
@@ -558,7 +526,7 @@ pub fn stream_item_to_release(
.behavior_hints
.as_ref()
.and_then(|h| h.video_size)
- .or_else(|| parse_size_bytes_from_text(&combined_text));
+ .or_else(|| crate::providers::models::parse_size_bytes(&combined_text));
let raw_filename = stream
.title
diff --git a/src/providers/dramachi/client.rs b/src/providers/dramachi/client.rs
index 69d30bc..d715cc1 100644
--- a/src/providers/dramachi/client.rs
+++ b/src/providers/dramachi/client.rs
@@ -502,8 +502,9 @@ impl DramachiClient {
match self.fetch_file_stream(&ep_fid, &ep_disk).await {
Ok((stream_url, filename)) => {
let quality = ep_quality.filter(|q| !q.is_empty());
- let size_bytes =
- parse_size_to_bytes(ep_size.as_deref().unwrap_or_default());
+ let size_bytes = crate::providers::models::parse_size_bytes(
+ ep_size.as_deref().unwrap_or_default(),
+ );
Some(Release {
provider: ProviderKind::Dramachi,
@@ -590,30 +591,6 @@ fn clean_episode_title(f_title: &str) -> String {
}
title.to_string()
}
-fn parse_size_to_bytes(size_str: &str) -> Option<u64> {
- let trimmed = size_str.trim();
- if trimmed.is_empty() {
- return None;
- }
- let parts: Vec<&str> = trimmed.split_whitespace().collect();
- if parts.is_empty() {
- return None;
- }
- let number = parts[0].parse::<f64>().ok()?;
- let unit = parts
- .get(1)
- .map(|s| s.to_ascii_uppercase())
- .unwrap_or_else(|| "MB".to_string());
-
- let bytes = match unit.as_str() {
- "GB" | "GIB" => number * 1024.0 * 1024.0 * 1024.0,
- "MB" | "MIB" => number * 1024.0 * 1024.0,
- "KB" | "KIB" => number * 1024.0,
- _ => number,
- };
-
- Some(bytes as u64)
-}
#[cfg(test)]
mod tests {
@@ -638,8 +615,14 @@ mod tests {
#[test]
fn test_parse_size_to_bytes() {
- assert_eq!(parse_size_to_bytes("218.32 MB"), Some(228925112));
- assert_eq!(parse_size_to_bytes("1.5 GB"), Some(1610612736));
- assert_eq!(parse_size_to_bytes(""), None);
+ assert_eq!(
+ crate::providers::models::parse_size_bytes("218.32 MB"),
+ Some(228925112)
+ );
+ assert_eq!(
+ crate::providers::models::parse_size_bytes("1.5 GB"),
+ Some(1610612736)
+ );
+ assert_eq!(crate::providers::models::parse_size_bytes(""), None);
}
}
diff --git a/src/providers/fourkhdhub/client.rs b/src/providers/fourkhdhub/client.rs
index a076c56..388063d 100644
--- a/src/providers/fourkhdhub/client.rs
+++ b/src/providers/fourkhdhub/client.rs
@@ -140,9 +140,9 @@ impl FourKHdHubClient {
candidates.sort_by_key(|cand| cand.0);
let mut unique_candidates = Vec::new();
let mut seen = std::collections::HashSet::new();
- for (_, url, label, headers) in candidates {
+ for (cand_score, url, label, headers) in candidates {
if seen.insert(url.clone()) {
- unique_candidates.push((url, label, headers));
+ unique_candidates.push((cand_score, url, label, headers));
}
}
@@ -154,7 +154,7 @@ impl FourKHdHubClient {
use futures::StreamExt;
let mut preflight_tasks = futures::stream::FuturesUnordered::new();
- for (url, label, headers) in unique_candidates.into_iter().take(6) {
+ for (cand_score, url, label, headers) in unique_candidates.into_iter().take(6) {
let this = self.clone();
let mut merged = headers;
if !merged
@@ -170,28 +170,50 @@ impl FourKHdHubClient {
merged.push(("User-Agent".to_string(), BROWSER_UA.to_string()));
}
preflight_tasks.push(async move {
- let playable_url = this.preflight(&url, &merged).await?;
- Ok::<_, FourKHdHubError>((playable_url, label, merged))
+ let (playable_url, is_seekable) =
+ this.preflight_with_seekable(&url, &merged).await?;
+ let resolved_score = cand_score.min(hubcloud::score(&playable_url, &label, intent));
+ Ok::<_, FourKHdHubError>((is_seekable, resolved_score, playable_url, label, merged))
});
}
+ let mut fallbacks = Vec::new();
while let Some(res) = preflight_tasks.next().await {
- if let Ok((playable_url, label, headers)) = res {
- log::info!(
- "4KHDHub mirror playable: {label} ({})",
- crate::logging::sanitize_url(&playable_url)
- );
- return Ok(PlaybackSource {
- provider: ProviderKind::FourKHdHub,
- url: playable_url,
- headers,
- subtitle: None,
- source_label: label,
- max_height: None,
- });
+ if let Ok((is_seekable, resolved_score, playable_url, label, headers)) = res {
+ if is_seekable && resolved_score <= 1 {
+ log::info!(
+ "4KHDHub seekable mirror playable: {label} ({})",
+ crate::logging::sanitize_url(&playable_url)
+ );
+ return Ok(PlaybackSource {
+ provider: ProviderKind::FourKHdHub,
+ url: playable_url,
+ headers,
+ subtitle: None,
+ source_label: label,
+ max_height: None,
+ });
+ }
+ fallbacks.push((is_seekable, resolved_score, playable_url, label, headers));
}
}
+ fallbacks
+ .sort_by_key(|(is_seekable, resolved_score, _, _, _)| (!*is_seekable, *resolved_score));
+ if let Some((_, _, playable_url, label, headers)) = fallbacks.into_iter().next() {
+ log::info!(
+ "4KHDHub fallback mirror playable: {label} ({})",
+ crate::logging::sanitize_url(&playable_url)
+ );
+ return Ok(PlaybackSource {
+ provider: ProviderKind::FourKHdHub,
+ url: playable_url,
+ headers,
+ subtitle: None,
+ source_label: label,
+ max_height: None,
+ });
+ }
log::error!(
"4KHDHub: no playable mirror for release {:?}",
release.filename
@@ -206,6 +228,16 @@ impl FourKHdHubClient {
url: &str,
headers: &[(String, String)],
) -> Result<String, FourKHdHubError> {
+ self.preflight_with_seekable(url, headers)
+ .await
+ .map(|(u, _)| u)
+ }
+
+ async fn preflight_with_seekable(
+ &self,
+ url: &str,
+ headers: &[(String, String)],
+ ) -> Result<(String, bool), FourKHdHubError> {
let probe = async {
hubcloud::validate_playback_url(url)?;
let mut request = self
@@ -216,6 +248,7 @@ impl FourKHdHubClient {
request = request.header(name, value);
}
let response = request.send().await?.error_for_status()?;
+ let mut is_seekable = response.status() == reqwest::StatusCode::PARTIAL_CONTENT;
let mut final_url = response.url().clone();
hubcloud::validate_playback_url(final_url.as_str())?;
let content_type = response
@@ -264,6 +297,7 @@ impl FourKHdHubClient {
wrapped_request = wrapped_request.header(name, value);
}
let wrapped_response = wrapped_request.send().await?.error_for_status()?;
+ is_seekable = wrapped_response.status() == reqwest::StatusCode::PARTIAL_CONTENT;
final_url = wrapped_response.url().clone();
hubcloud::validate_playback_url(final_url.as_str())?;
let wrapped_type = wrapped_response
@@ -297,7 +331,7 @@ impl FourKHdHubClient {
)));
}
}
- Ok(final_url.to_string())
+ Ok((final_url.to_string(), is_seekable))
};
tokio::time::timeout(std::time::Duration::from_millis(3500), probe)
diff --git a/src/providers/fourkhdhub/hubcloud.rs b/src/providers/fourkhdhub/hubcloud.rs
index a6b22db..3a8a769 100644
--- a/src/providers/fourkhdhub/hubcloud.rs
+++ b/src/providers/fourkhdhub/hubcloud.rs
@@ -409,6 +409,7 @@ pub fn score(url: &str, label: &str, intent: ResolutionIntent) -> u8 {
|| value.contains("cloudflarestorage.com")
|| value.contains("r2.cloudflarestorage.com")
|| value.contains("fsl server")
+ || value.contains("10gbps")
|| value.contains("r2.dev")
|| value.contains("watch online")
{
diff --git a/src/providers/fourkhdhub/parser.rs b/src/providers/fourkhdhub/parser.rs
index 7b2b0b2..d7b3f3c 100644
--- a/src/providers/fourkhdhub/parser.rs
+++ b/src/providers/fourkhdhub/parser.rs
@@ -200,14 +200,16 @@ pub fn parse_releases(
let size_text = item
.select(size_selector)
.filter_map(|node| text_of(Some(node)))
- .find(|text| parse_size_bytes(text).is_some());
+ .find(|text| crate::providers::models::parse_size_bytes(text).is_some());
let key = normalize_filename(&filename);
let release = grouped.entry(key).or_insert_with(|| Release {
provider: ProviderKind::FourKHdHub,
quality: detect_quality(&filename),
codec: detect_codec(&filename),
language: detect_language(&filename).or_else(|| page_language.clone()),
- size_bytes: size_text.as_deref().and_then(parse_size_bytes),
+ size_bytes: size_text
+ .as_deref()
+ .and_then(crate::providers::models::parse_size_bytes),
season: parsed_episode.map(|value| value.0),
episode: parsed_episode.map(|value| value.1),
filename: filename.clone(),
@@ -378,22 +380,6 @@ fn parse_season_episode(value: &str) -> Option<(usize, usize)> {
None
}
-fn parse_size_bytes(value: &str) -> Option<u64> {
- let normalized = value.replace(' ', "").to_ascii_uppercase();
- for (suffix, multiplier) in [
- ("GB", 1024_u64.pow(3)),
- ("MB", 1024_u64.pow(2)),
- ("KB", 1024_u64),
- ] {
- if let Some(number) = normalized.strip_suffix(suffix)
- && let Ok(number) = number.parse::<f64>()
- {
- return Some((number * multiplier as f64) as u64);
- }
- }
- None
-}
-
fn detect_quality(value: &str) -> Option<String> {
let lower = value.to_ascii_lowercase();
if lower.contains("2160p")
diff --git a/src/providers/models.rs b/src/providers/models.rs
index b4988fb..4091072 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -155,6 +155,15 @@ impl MediaDetails {
self.poster_url.as_deref()
}
+ pub fn sibling_ids(&self) -> Vec<String> {
+ let mut ids = vec![self.id.value.clone()];
+ ids.extend(self.dubs.iter().map(|dub| dub.subject_id.clone()));
+ ids.retain(|s| !s.is_empty());
+ ids.sort();
+ ids.dedup();
+ ids
+ }
+
pub fn from_search_result(
item: &crate::models::SearchResult,
preview: Option<&MediaDetails>,
@@ -417,6 +426,45 @@ pub fn extract_4digit_year(raw: &str) -> String {
.unwrap_or_default()
}
+pub fn parse_size_bytes(text: &str) -> Option<u64> {
+ let parts: Vec<&str> = text.split_whitespace().collect();
+ for i in 0..parts.len() {
+ let clean = parts[i].trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '.');
+ if let Ok(num) = clean.parse::<f64>()
+ && i + 1 < parts.len()
+ {
+ let unit = parts[i + 1]
+ .trim_matches(|c: char| !c.is_ascii_alphabetic())
+ .to_ascii_uppercase();
+ match unit.as_str() {
+ "TB" | "TIB" | "T" => return Some((num * 1_099_511_627_776.0) as u64),
+ "GB" | "GIB" | "G" => return Some((num * 1_073_741_824.0) as u64),
+ "MB" | "MIB" | "M" => return Some((num * 1_048_576.0) as u64),
+ "KB" | "KIB" | "K" => return Some((num * 1_024.0) as u64),
+ _ => {}
+ }
+ }
+ let upper = clean.to_ascii_uppercase();
+ for (suffix, multiplier) in [
+ ("TIB", 1_099_511_627_776.0),
+ ("TB", 1_099_511_627_776.0),
+ ("GIB", 1_073_741_824.0),
+ ("GB", 1_073_741_824.0),
+ ("MIB", 1_048_576.0),
+ ("MB", 1_048_576.0),
+ ("KIB", 1_024.0),
+ ("KB", 1_024.0),
+ ] {
+ if let Some(num_str) = upper.strip_suffix(suffix)
+ && let Ok(num) = num_str.parse::<f64>()
+ {
+ return Some((num * multiplier) as u64);
+ }
+ }
+ }
+ None
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/proxy.rs b/src/proxy.rs
index 71f8a45..1b30b2b 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -13,7 +13,81 @@ const MAX_HEADERS: usize = 64;
const MAX_MANIFEST_BYTES: usize = 10 * 1024 * 1024;
const CHUNK_IDLE_TIMEOUT_SECS: u64 = 60;
const WATCHDOG_IDLE_SECS: u64 = 600;
+const DASH_RANGE_CHUNK_BYTES: usize = 95 * 1024;
+const MAX_CACHED_SEGMENTS: usize = 24;
+const MAX_SEGMENT_BYTES: usize = 16 * 1024 * 1024;
+const PREFETCH_LOOKAHEAD: u32 = 3;
+
+type CachedSegment = (String, String, Arc<[u8]>);
+type CachedManifest = (String, Arc<[u8]>);
+
+#[derive(Default)]
+struct SegmentCache {
+ completed: Mutex<std::collections::VecDeque<CachedSegment>>,
+ in_flight: Mutex<std::collections::HashMap<String, Arc<tokio::sync::Notify>>>,
+}
+
+impl SegmentCache {
+ fn get(&self, url: &str) -> Option<(String, Arc<[u8]>)> {
+ let lock = self.completed.lock().ok()?;
+ lock.iter()
+ .find(|(u, _, _)| u == url)
+ .map(|(_, ct, b)| (ct.clone(), b.clone()))
+ }
+
+ fn contains_or_in_flight(&self, url: &str) -> bool {
+ if let Ok(lock) = self.completed.lock() {
+ if lock.iter().any(|(u, _, _)| u == url) {
+ return true;
+ }
+ }
+ if let Ok(lock) = self.in_flight.lock() {
+ if lock.contains_key(url) {
+ return true;
+ }
+ }
+ false
+ }
+
+ fn insert(&self, url: String, content_type: String, data: Arc<[u8]>) {
+ if let Ok(mut lock) = self.completed.lock() {
+ if lock.iter().any(|(u, _, _)| u == &url) {
+ return;
+ }
+ if lock.len() >= MAX_CACHED_SEGMENTS {
+ lock.pop_front();
+ }
+ lock.push_back((url, content_type, data));
+ }
+ }
+}
+
+struct InFlightGuard {
+ cache: Arc<SegmentCache>,
+ url: String,
+ notify: Arc<tokio::sync::Notify>,
+}
+
+impl Drop for InFlightGuard {
+ fn drop(&mut self) {
+ if let Ok(mut lock) = self.cache.in_flight.lock() {
+ lock.remove(&self.url);
+ }
+ self.notify.notify_waiters();
+ }
+}
+#[derive(Clone)]
+struct ProxyContext {
+ proxy_port: u16,
+ client: reqwest::Client,
+ auth_headers: Arc<Vec<(String, String)>>,
+ target_host: Option<String>,
+ subtitle_url: Option<String>,
+ max_height: Option<u64>,
+ segment_cache: Arc<SegmentCache>,
+ manifest_cache: Arc<Mutex<Option<CachedManifest>>>,
+}
struct ConnectionGuard {
conns: Arc<AtomicUsize>,
activity: Arc<Mutex<Instant>>,
@@ -33,7 +107,7 @@ pub fn spawn_sidecar(
headers: &[(String, String)],
subtitle_url: Option<&str>,
max_height: Option<u64>,
-) -> Result<String, String> {
+) -> Result<(String, std::process::Child), String> {
let exe = std::env::current_exe()
.ok()
.or_else(|| std::env::args().next().map(PathBuf::from))
@@ -54,19 +128,7 @@ pub fn spawn_sidecar(
cmd.stdin(Stdio::null());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::null());
- #[cfg(unix)]
- {
- use std::os::unix::process::CommandExt;
- cmd.process_group(0);
- }
-
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- const DETACHED_PROCESS: u32 = 0x0000_0008;
- const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
- cmd.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
- }
+ crate::player::configure_detached_process(&mut cmd);
let mut child = cmd
.spawn()
@@ -100,7 +162,6 @@ pub fn spawn_sidecar(
let _ = child.wait();
format!("proxy sidecar returned unexpected output: {line:?}")
})?;
- std::mem::forget(child);
let proxy_path = if let Some(rest) = target_url.strip_prefix("https://") {
format!("/https/{rest}")
@@ -110,7 +171,7 @@ pub fn spawn_sidecar(
format!("/https/{target_url}")
};
- Ok(format!("http://127.0.0.1:{port}{proxy_path}"))
+ Ok((format!("http://127.0.0.1:{port}{proxy_path}"), child))
}
pub async fn run_sidecar(
@@ -119,7 +180,9 @@ pub async fn run_sidecar(
subtitle_url: Option<String>,
max_height: Option<u64>,
) {
- let client = crate::net::streaming_client_builder()
+ let client = crate::net::http_client_builder_base()
+ .http1_only()
+ .pool_max_idle_per_host(16)
.connect_timeout(Duration::from_secs(15))
.build()
.unwrap_or_default();
@@ -157,8 +220,24 @@ pub async fn run_sidecar(
}
});
- let target_host = extract_host_authority(&target_url);
+ let ctx = ProxyContext {
+ proxy_port: port,
+ client,
+ auth_headers: Arc::new(headers),
+ target_host: extract_host_authority(&target_url),
+ subtitle_url,
+ max_height,
+ segment_cache: Arc::new(SegmentCache::default()),
+ manifest_cache: Arc::new(Mutex::new(None)),
+ };
+ if crate::player::is_dash_url(&target_url) {
+ let warm_ctx = ctx.clone();
+ let warm_url = target_url.clone();
+ tokio::spawn(async move {
+ warmup_dash_sidecar(&warm_ctx, &warm_url).await;
+ });
+ }
loop {
let (stream, _) = match listener.accept().await {
Ok(conn) => {
@@ -171,9 +250,7 @@ pub async fn run_sidecar(
continue;
}
};
- let client = client.clone();
- let headers = headers.clone();
- let target_host = target_host.clone();
+ let conn_ctx = ctx.clone();
let active_conns = Arc::clone(&active_connections);
let activity = Arc::clone(&last_activity);
@@ -184,22 +261,12 @@ pub async fn run_sidecar(
}
}
- 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(),
- sub_opt.as_deref(),
- max_height,
- )
- .await;
+ let _ = handle_connection(stream, &conn_ctx).await;
});
}
}
@@ -218,13 +285,14 @@ fn extract_host_authority(url: &str) -> Option<String> {
async fn handle_connection(
stream: TcpStream,
- proxy_port: u16,
- client: &reqwest::Client,
- auth_headers: &[(String, String)],
- target_host: Option<&str>,
- subtitle_url: Option<&str>,
- max_height: Option<u64>,
+ ctx: &ProxyContext,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
+ let proxy_port = ctx.proxy_port;
+ let client = &ctx.client;
+ let auth_headers = ctx.auth_headers.as_slice();
+ let target_host = ctx.target_host.as_deref();
+ let subtitle_url = ctx.subtitle_url.as_deref();
+ let max_height = ctx.max_height;
let (reader, writer) = stream.into_split();
let mut buf_reader = BufReader::new(reader);
let mut writer = tokio::io::BufWriter::with_capacity(128 * 1024, writer);
@@ -303,12 +371,111 @@ async fn handle_connection(
return Ok(());
}
+ let forward_all_headers = extracted_host.as_deref() == target_host;
+
+ if method == "GET" && crate::player::is_dash_url(&target_url) {
+ let cached_mpd = ctx.manifest_cache.lock().ok().and_then(|g| {
+ g.as_ref()
+ .filter(|(u, _)| u == &target_url)
+ .map(|(_, b)| Arc::clone(b))
+ });
+ if let Some(rewritten_bytes) = cached_mpd {
+ let conn_header = if client_close {
+ "Connection: close\r\n"
+ } else {
+ "Connection: keep-alive\r\n"
+ };
+ let headers_out = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/dash+xml\r\nContent-Length: {}\r\n{conn_header}\r\n",
+ rewritten_bytes.len()
+ );
+ writer.write_all(headers_out.as_bytes()).await?;
+ writer.write_all(&rewritten_bytes).await?;
+ writer.flush().await?;
+ if client_close {
+ return Ok(());
+ }
+ continue;
+ }
+ }
+
+ if method == "GET" && is_m4s_segment(&target_url) {
+ for next_url in next_dash_segment_urls(&target_url, PREFETCH_LOOKAHEAD) {
+ if !ctx.segment_cache.contains_or_in_flight(&next_url) {
+ let cache_clone = Arc::clone(&ctx.segment_cache);
+ let client_clone = client.clone();
+ let headers_clone = Arc::clone(&ctx.auth_headers);
+ tokio::spawn(async move {
+ let _ = fetch_or_get_segment(
+ &cache_clone,
+ &client_clone,
+ &next_url,
+ &headers_clone,
+ forward_all_headers,
+ )
+ .await;
+ });
+ }
+ }
+
+ match fetch_or_get_segment(
+ &ctx.segment_cache,
+ client,
+ &target_url,
+ auth_headers,
+ forward_all_headers,
+ )
+ .await
+ {
+ Ok((seg_status, content_type, seg_bytes)) => {
+ let conn_hdr = if client_close { "close" } else { "keep-alive" };
+ let total = seg_bytes.len();
+ let parsed_range = range_header
+ .as_deref()
+ .and_then(|r| parse_byte_range_request(r, total));
+ let (out_status, content_range_hdr, body_slice) = if seg_status.is_success()
+ && let Some((start, end)) = parsed_range
+ {
+ (
+ reqwest::StatusCode::PARTIAL_CONTENT,
+ format!("Content-Range: bytes {start}-{end}/{total}\r\n"),
+ &seg_bytes[start..=end],
+ )
+ } else {
+ (seg_status, String::new(), seg_bytes.as_ref())
+ };
+ let response_hdr = format!(
+ "HTTP/1.1 {} {}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\n{content_range_hdr}Accept-Ranges: bytes\r\nAccess-Control-Allow-Origin: *\r\nConnection: {conn_hdr}\r\n\r\n",
+ out_status.as_u16(),
+ out_status.canonical_reason().unwrap_or("OK"),
+ body_slice.len()
+ );
+ writer.write_all(response_hdr.as_bytes()).await?;
+ writer.write_all(body_slice).await?;
+ writer.flush().await?;
+ if client_close {
+ return Ok(());
+ }
+ continue;
+ }
+ Err(e) => {
+ let body = format!("Gateway Error: {e}");
+ let response = format!(
+ "HTTP/1.1 502 Bad Gateway\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ writer.write_all(response.as_bytes()).await?;
+ writer.flush().await?;
+ return Ok(());
+ }
+ }
+ }
+
let mut req = match method {
"HEAD" => client.head(&target_url),
_ => client.get(&target_url),
};
- let forward_all_headers = extracted_host.as_deref() == target_host;
for (name, val) in auth_headers {
if forward_all_headers || name.eq_ignore_ascii_case("user-agent") {
req = req.header(name.as_str(), val.as_str());
@@ -317,7 +484,6 @@ async fn handle_connection(
if let Some(range) = range_header {
req = req.header("Range", range);
}
-
let upstream_res = match req.send().await {
Ok(res) => res,
Err(e) => {
@@ -340,7 +506,7 @@ async fn handle_connection(
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<usize>().ok());
- let is_dash_manifest = target_url.ends_with(".mpd")
+ let is_dash_manifest = crate::player::is_dash_url(&target_url)
|| upstream_res
.headers()
.get(reqwest::header::CONTENT_TYPE)
@@ -375,6 +541,9 @@ async fn handle_connection(
max_height,
);
let rewritten_bytes = rewritten.as_bytes();
+ if let Ok(mut lock) = ctx.manifest_cache.lock() {
+ *lock = Some((target_url.clone(), Arc::from(rewritten_bytes)));
+ }
let conn_header = if client_close {
"Connection: close\r\n"
@@ -426,6 +595,299 @@ async fn handle_connection(
}
}
}
+
+fn is_m4s_segment(url: &str) -> bool {
+ let clean = url
+ .split('?')
+ .next()
+ .unwrap_or("")
+ .split('#')
+ .next()
+ .unwrap_or("");
+ clean.to_ascii_lowercase().ends_with(".m4s")
+}
+
+async fn warmup_dash_sidecar(ctx: &ProxyContext, mpd_url: &str) {
+ let mut req = ctx.client.get(mpd_url);
+ for (name, val) in ctx.auth_headers.iter() {
+ req = req.header(name.as_str(), val.as_str());
+ }
+ let Ok(res) = req.send().await else {
+ return;
+ };
+ if !res.status().is_success() {
+ return;
+ }
+ let Ok(manifest_bytes) = res.bytes().await else {
+ return;
+ };
+ if manifest_bytes.len() > MAX_MANIFEST_BYTES {
+ return;
+ }
+ let manifest_str = String::from_utf8_lossy(&manifest_bytes);
+ let rewritten = rewrite_dash_manifest(
+ &manifest_str,
+ ctx.proxy_port,
+ ctx.target_host.as_deref(),
+ ctx.subtitle_url.as_deref(),
+ ctx.max_height,
+ );
+ if let Ok(mut lock) = ctx.manifest_cache.lock() {
+ *lock = Some((mpd_url.to_string(), Arc::from(rewritten.as_bytes())));
+ }
+ let Some((base_dir, _)) = mpd_url.rsplit_once('/') else {
+ return;
+ };
+ let vid_id = if rewritten.contains("id=\"0\"") {
+ "0"
+ } else if rewritten.contains("id=\"1\"") {
+ "1"
+ } else {
+ "2"
+ };
+ for rel in [
+ format!("init-stream{vid_id}.m4s"),
+ "init-stream3.m4s".to_string(),
+ format!("chunk-stream{vid_id}-00001.m4s"),
+ "chunk-stream3-00001.m4s".to_string(),
+ ] {
+ let seg_url = format!("{base_dir}/{rel}");
+ if !ctx.segment_cache.contains_or_in_flight(&seg_url) {
+ let cache_clone = Arc::clone(&ctx.segment_cache);
+ let client_clone = ctx.client.clone();
+ let headers_clone = Arc::clone(&ctx.auth_headers);
+ tokio::spawn(async move {
+ let _ = fetch_or_get_segment(
+ &cache_clone,
+ &client_clone,
+ &seg_url,
+ &headers_clone,
+ true,
+ )
+ .await;
+ });
+ }
+ }
+}
+
+fn next_dash_segment_urls(url: &str, count: u32) -> Vec<String> {
+ let (base, query_suffix) = match url.find('?') {
+ Some(idx) => (&url[..idx], &url[idx..]),
+ None => (url, ""),
+ };
+ if !base.to_ascii_lowercase().ends_with(".m4s") {
+ return Vec::new();
+ }
+ let without_ext = &base[..base.len() - 4];
+ let file_stem = without_ext.rsplit('/').next().unwrap_or(without_ext);
+ if let Some(init_id) = file_stem.strip_prefix("init-stream") {
+ let dir_prefix = &without_ext[..without_ext.len() - file_stem.len()];
+ return if init_id == "3" {
+ vec![format!("{dir_prefix}init-stream0.m4s{query_suffix}")]
+ } else {
+ vec![format!("{dir_prefix}init-stream3.m4s{query_suffix}")]
+ };
+ }
+ if file_stem.to_ascii_lowercase().starts_with("init") {
+ return Vec::new();
+ }
+ let digit_count = without_ext
+ .bytes()
+ .rev()
+ .take_while(|b| b.is_ascii_digit())
+ .count();
+ if digit_count == 0 || digit_count > 9 {
+ return Vec::new();
+ }
+ let split_pos = without_ext.len() - digit_count;
+ let prefix = &without_ext[..split_pos];
+ if !prefix.ends_with(['-', '_', '/']) {
+ return Vec::new();
+ }
+ let digits = &without_ext[split_pos..];
+ let Ok(num) = digits.parse::<u64>() else {
+ return Vec::new();
+ };
+ let mut out: Vec<String> = (1..=u64::from(count))
+ .map(|step| {
+ let next_num = num + step;
+ format!("{prefix}{next_num:0digit_count$}.m4s{query_suffix}")
+ })
+ .collect();
+
+ for vid_tag in ["chunk-stream0-", "chunk-stream1-", "chunk-stream2-"] {
+ if let Some(dir_prefix) = prefix.strip_suffix(vid_tag) {
+ out.push(format!(
+ "{dir_prefix}chunk-stream3-{num:0digit_count$}.m4s{query_suffix}"
+ ));
+ let next_num = num + 1;
+ out.push(format!(
+ "{dir_prefix}chunk-stream3-{next_num:0digit_count$}.m4s{query_suffix}"
+ ));
+ break;
+ }
+ }
+ out
+}
+
+fn parse_content_range_total(header_val: &str) -> Option<usize> {
+ let (_, total_str) = header_val.trim().split_once('/')?;
+ total_str.trim().parse::<usize>().ok()
+}
+
+fn parse_byte_range_request(header_val: &str, total: usize) -> Option<(usize, usize)> {
+ if total == 0 {
+ return None;
+ }
+ let spec = header_val.trim().strip_prefix("bytes=")?;
+ let (start_str, end_str) = spec.split_once('-')?;
+ let start = start_str.trim().parse::<usize>().ok()?;
+ if start >= total {
+ return None;
+ }
+ let end = if end_str.trim().is_empty() {
+ total - 1
+ } else {
+ end_str.trim().parse::<usize>().ok()?.min(total - 1)
+ };
+ if start <= end {
+ Some((start, end))
+ } else {
+ None
+ }
+}
+
+async fn fetch_or_get_segment(
+ cache: &Arc<SegmentCache>,
+ client: &reqwest::Client,
+ url: &str,
+ auth_headers: &[(String, String)],
+ forward_all_headers: bool,
+) -> Result<(reqwest::StatusCode, String, Arc<[u8]>), reqwest::Error> {
+ if let Some((ct, data)) = cache.get(url) {
+ return Ok((reqwest::StatusCode::OK, ct, data));
+ }
+
+ let (is_owner, notify) = {
+ let mut lock = cache.in_flight.lock().unwrap();
+ if let Some(existing) = lock.get(url) {
+ (false, Arc::clone(existing))
+ } else {
+ let n = Arc::new(tokio::sync::Notify::new());
+ lock.insert(url.to_string(), Arc::clone(&n));
+ (true, n)
+ }
+ };
+
+ if !is_owner {
+ let _ = tokio::time::timeout(Duration::from_secs(15), notify.notified()).await;
+ if let Some((ct, data)) = cache.get(url) {
+ return Ok((reqwest::StatusCode::OK, ct, data));
+ }
+ }
+
+ let _guard = if is_owner {
+ Some(InFlightGuard {
+ cache: Arc::clone(cache),
+ url: url.to_string(),
+ notify,
+ })
+ } else {
+ None
+ };
+
+ let (status, content_type, data) =
+ fetch_m4s_chunked(client, url, auth_headers, forward_all_headers).await?;
+ if status.is_success() && !data.is_empty() && data.len() <= MAX_SEGMENT_BYTES {
+ cache.insert(url.to_string(), content_type.clone(), Arc::clone(&data));
+ }
+ Ok((status, content_type, data))
+}
+
+async fn fetch_m4s_chunked(
+ client: &reqwest::Client,
+ url: &str,
+ auth_headers: &[(String, String)],
+ forward_all_headers: bool,
+) -> Result<(reqwest::StatusCode, String, Arc<[u8]>), reqwest::Error> {
+ let first_end = DASH_RANGE_CHUNK_BYTES - 1;
+ let mut req = client
+ .get(url)
+ .header("Range", format!("bytes=0-{first_end}"));
+ for (name, val) in auth_headers {
+ if forward_all_headers || name.eq_ignore_ascii_case("user-agent") {
+ req = req.header(name.as_str(), val.as_str());
+ }
+ }
+
+ let res = req.send().await?;
+ let status = res.status();
+ let content_type = res
+ .headers()
+ .get(reqwest::header::CONTENT_TYPE)
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or("application/octet-stream")
+ .to_string();
+
+ if !status.is_success() {
+ let body = res.bytes().await.unwrap_or_default();
+ return Ok((status, content_type, Arc::from(body.as_ref())));
+ }
+
+ if status == reqwest::StatusCode::OK {
+ let body = res.bytes().await?;
+ return Ok((
+ reqwest::StatusCode::OK,
+ content_type,
+ Arc::from(body.as_ref()),
+ ));
+ }
+
+ let total_opt = res
+ .headers()
+ .get(reqwest::header::CONTENT_RANGE)
+ .and_then(|v| v.to_str().ok())
+ .and_then(parse_content_range_total);
+ let first_chunk = res.bytes().await?;
+
+ let Some(total) = total_opt.filter(|&t| t > first_chunk.len() && t <= MAX_SEGMENT_BYTES) else {
+ return Ok((
+ reqwest::StatusCode::OK,
+ content_type,
+ Arc::from(first_chunk.as_ref()),
+ ));
+ };
+
+ let mut ranges = Vec::new();
+ let mut pos = first_chunk.len();
+ while pos < total {
+ let end = (pos + DASH_RANGE_CHUNK_BYTES - 1).min(total - 1);
+ ranges.push((pos, end));
+ pos = end + 1;
+ }
+
+ let chunk_futs = ranges.into_iter().map(|(start, end)| async move {
+ let mut sub_req = client
+ .get(url)
+ .header("Range", format!("bytes={start}-{end}"));
+ for (name, val) in auth_headers {
+ if forward_all_headers || name.eq_ignore_ascii_case("user-agent") {
+ sub_req = sub_req.header(name.as_str(), val.as_str());
+ }
+ }
+ let sub_res = sub_req.send().await?.error_for_status()?;
+ sub_res.bytes().await
+ });
+
+ let remaining_chunks = futures::future::try_join_all(chunk_futs).await?;
+ let mut assembled = Vec::with_capacity(total);
+ assembled.extend_from_slice(&first_chunk);
+ for chunk in remaining_chunks {
+ assembled.extend_from_slice(&chunk);
+ }
+
+ Ok((reqwest::StatusCode::OK, content_type, Arc::from(assembled)))
+}
fn format_proxy_response_headers(
headers: &reqwest::header::HeaderMap,
target_url: &str,
@@ -844,4 +1306,109 @@ mod tests {
assert!(!filtered_480.contains("height=\"720\""));
assert!(filtered_480.contains("height=\"480\""));
}
+
+ #[test]
+ fn test_next_dash_segment_urls_preserves_zero_padding_and_prefetches_audio() {
+ let next = next_dash_segment_urls(
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream0-00721.m4s?token=abc",
+ 3,
+ );
+ assert_eq!(
+ next,
+ vec![
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream0-00722.m4s?token=abc",
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream0-00723.m4s?token=abc",
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream0-00724.m4s?token=abc",
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream3-00721.m4s?token=abc",
+ "https://sbcdn3.hakunaymatata.com/dash/123/chunk-stream3-00722.m4s?token=abc",
+ ]
+ );
+ assert_eq!(
+ next_dash_segment_urls(
+ "https://sbcdn3.hakunaymatata.com/dash/123/init-stream0.m4s",
+ 3
+ ),
+ vec!["https://sbcdn3.hakunaymatata.com/dash/123/init-stream3.m4s"]
+ );
+ assert!(
+ next_dash_segment_urls("https://sbcdn3.hakunaymatata.com/dash/123/init.m4s", 3)
+ .is_empty()
+ );
+ }
+
+ #[tokio::test]
+ async fn test_fetch_m4s_chunked_splits_ranges_and_caches() {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+ let total_size = 240 * 1024;
+ let payload: Arc<Vec<u8>> = Arc::new((0..total_size).map(|i| (i % 253) as u8).collect());
+ let request_count = Arc::new(AtomicUsize::new(0));
+
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let url = format!("http://127.0.0.1:{port}/dash/chunk-stream0-00001.m4s");
+
+ let srv_payload = Arc::clone(&payload);
+ let srv_reqs = Arc::clone(&request_count);
+ let server = tokio::spawn(async move {
+ loop {
+ let Ok((mut socket, _)) = listener.accept().await else {
+ break;
+ };
+ let data = Arc::clone(&srv_payload);
+ let reqs = Arc::clone(&srv_reqs);
+ tokio::spawn(async move {
+ let mut buf = [0u8; 2048];
+ let Ok(n) = socket.read(&mut buf).await else {
+ return;
+ };
+ reqs.fetch_add(1, Ordering::Relaxed);
+ let req = String::from_utf8_lossy(&buf[..n]);
+ let mut range_val = None;
+ for line in req.lines() {
+ if let Some(v) = line
+ .strip_prefix("Range: bytes=")
+ .or_else(|| line.strip_prefix("range: bytes="))
+ {
+ range_val = Some(v.trim().to_string());
+ }
+ }
+ let total = data.len();
+ let (start, end) = range_val
+ .and_then(|r| {
+ let (s, e) = r.split_once('-')?;
+ Some((
+ s.parse::<usize>().ok()?,
+ e.parse::<usize>().ok()?.min(total - 1),
+ ))
+ })
+ .unwrap_or((0, total - 1));
+ let slice = &data[start..=end];
+ let hdr = format!(
+ "HTTP/1.1 206 Partial Content\r\nContent-Type: video/iso.segment\r\nContent-Range: bytes {start}-{end}/{total}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ slice.len()
+ );
+ let _ = socket.write_all(hdr.as_bytes()).await;
+ let _ = socket.write_all(slice).await;
+ });
+ }
+ });
+
+ let client = crate::net::http_client_builder_base().build().unwrap();
+ let cache = Arc::new(SegmentCache::default());
+ let (status, ct, assembled) = fetch_or_get_segment(&cache, &client, &url, &[], true)
+ .await
+ .unwrap();
+ assert_eq!(status, reqwest::StatusCode::OK);
+ assert_eq!(ct, "video/iso.segment");
+ assert_eq!(assembled.as_ref(), payload.as_slice());
+ assert_eq!(request_count.load(Ordering::Relaxed), 3);
+
+ let (_, _, cached) = fetch_or_get_segment(&cache, &client, &url, &[], true)
+ .await
+ .unwrap();
+ assert_eq!(cached.as_ref(), payload.as_slice());
+ assert_eq!(request_count.load(Ordering::Relaxed), 3);
+ server.abort();
+ }
}
diff --git a/src/service.rs b/src/service.rs
index e3e8615..d23f68e 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -44,10 +44,6 @@ impl MovieBoxService {
}
}
- pub fn http_client(&self) -> &reqwest::Client {
- &self.http_client
- }
-
pub fn capabilities(&self, provider: ProviderKind) -> crate::providers::ProviderCapabilities {
match provider {
ProviderKind::MovieBox => Provider::capabilities(&self.client),
@@ -199,63 +195,77 @@ impl MovieBoxService {
season: usize,
episode: usize,
) -> Result<Vec<crate::providers::models::SubtitleOption>, String> {
+ if !subject_id.is_empty() && !resource_id.is_empty() {
+ let sid = subject_id.to_string();
+ let rid = resource_id.to_string();
+ if let Ok(Some(cached)) = tokio::task::spawn_blocking(move || {
+ crate::cache::get_captions_cache_typed(&sid, &rid)
+ })
+ .await
+ {
+ if !cached.is_empty() || sibling_ids.is_empty() {
+ return Ok(cached);
+ }
+ }
+ }
+
let mut all_captions = Vec::new();
let mut seen_urls = std::collections::HashSet::new();
- if let Ok(payload) = self.client.get_ext_captions(subject_id, resource_id).await {
- Self::append_unique_captions(
- &mut all_captions,
- &mut seen_urls,
- crate::providers::moviebox::adapt::captions_json_to_options(&payload),
- );
- }
-
- if all_captions.len() < 5 && !sibling_ids.is_empty() {
- let mut sibling_futs = Vec::new();
- for sib in sibling_ids.iter().take(3) {
- if !sib.is_empty() && sib != subject_id {
- let client = &self.client;
- sibling_futs.push(async move {
- tokio::time::timeout(std::time::Duration::from_secs(8), async move {
- let page = if episode > 0 { (episode - 1) / 20 + 1 } else { 1 };
- if let Ok((items, _)) = client.fetch_resource_page(sib, season, episode, 0, page).await {
- let matched_item = find_matching_resource_item(&items, season, episode);
- if let Some(item) = matched_item {
- let item_rid = item
- .get("resourceId")
- .or_else(|| item.get("id"))
- .and_then(|v| {
- if let Some(n) = v.as_i64() {
- Some(n.to_string())
- } else if let Some(n) = v.as_u64() {
- Some(n.to_string())
- } else {
- v.as_str().map(|s| s.to_string())
- }
- });
- if let Some(rid) = item_rid {
- if let Ok(res_payload) = client.get_ext_captions(sib, &rid).await {
- return crate::providers::moviebox::adapt::captions_json_to_options(
- &res_payload,
- );
+ let primary_fut = self.client.get_ext_captions(subject_id, resource_id);
+ let mut sibling_futs = Vec::new();
+ for sib in sibling_ids.iter().take(3) {
+ if !sib.is_empty() && sib != subject_id {
+ let client = &self.client;
+ sibling_futs.push(async move {
+ tokio::time::timeout(std::time::Duration::from_secs(6), async move {
+ let page = if episode > 0 { (episode - 1) / 20 + 1 } else { 1 };
+ if let Ok((items, _)) =
+ client.fetch_resource_page(sib, season, episode, 0, page).await
+ {
+ let matched_item = find_matching_resource_item(&items, season, episode);
+ if let Some(item) = matched_item {
+ let item_rid = item
+ .get("resourceId")
+ .or_else(|| item.get("id"))
+ .and_then(|v| {
+ if let Some(n) = v.as_i64() {
+ Some(n.to_string())
+ } else if let Some(n) = v.as_u64() {
+ Some(n.to_string())
+ } else {
+ v.as_str().map(|s| s.to_string())
}
+ });
+ if let Some(rid) = item_rid {
+ if let Ok(res_payload) = client.get_ext_captions(sib, &rid).await
+ {
+ return crate::providers::moviebox::adapt::captions_json_to_options(
+ &res_payload,
+ );
}
}
}
- Vec::new()
- })
- .await
- .unwrap_or_default()
- });
- }
+ }
+ Vec::new()
+ })
+ .await
+ .unwrap_or_default()
+ });
}
+ }
- if !sibling_futs.is_empty() {
- let sibling_results = futures::future::join_all(sibling_futs).await;
- for res in sibling_results {
- Self::append_unique_captions(&mut all_captions, &mut seen_urls, res);
- }
- }
+ let (primary_res, sibling_results) =
+ tokio::join!(primary_fut, futures::future::join_all(sibling_futs));
+ if let Ok(payload) = primary_res {
+ Self::append_unique_captions(
+ &mut all_captions,
+ &mut seen_urls,
+ crate::providers::moviebox::adapt::captions_json_to_options(&payload),
+ );
+ }
+ for res in sibling_results {
+ Self::append_unique_captions(&mut all_captions, &mut seen_urls, res);
}
let mut deduplicated: Vec<crate::providers::models::SubtitleOption> = Vec::new();
let mut seen_languages = std::collections::HashSet::new();
@@ -277,6 +287,14 @@ impl MovieBoxService {
clean_a.cmp(&clean_b)
}
});
+ if !subject_id.is_empty() && !resource_id.is_empty() && !deduplicated.is_empty() {
+ let sid = subject_id.to_string();
+ let rid = resource_id.to_string();
+ let to_cache = deduplicated.clone();
+ tokio::task::spawn_blocking(move || {
+ crate::cache::set_captions_cache_typed(&sid, &rid, &to_cache);
+ });
+ }
Ok(deduplicated)
}
@@ -293,8 +311,8 @@ impl MovieBoxService {
}
}
pub async fn fetch_poster_bytes(&self, url: &str) -> Option<Vec<u8>> {
- const MAX_POSTER_BYTES: u64 = 5 * 1024 * 1024;
- let response = self
+ const MAX_POSTER_BYTES: usize = 5 * 1024 * 1024;
+ let mut response = self
.http_client
.get(url)
.header("User-Agent", crate::net::APP_HTTP_USER_AGENT)
@@ -303,22 +321,54 @@ impl MovieBoxService {
.ok()?
.error_for_status()
.ok()?;
- if response
- .content_length()
- .is_some_and(|len| len > MAX_POSTER_BYTES)
- {
+ let content_len = response.content_length();
+ if content_len.is_some_and(|len| len > MAX_POSTER_BYTES as u64) {
log::warn!(
"poster at {} exceeds size limit ({} bytes), skipping",
crate::logging::sanitize_url(url),
- response.content_length().unwrap_or(0)
+ content_len.unwrap_or(0)
);
return None;
}
- let bytes = response.bytes().await.ok()?;
- if bytes.len() as u64 > MAX_POSTER_BYTES {
- return None;
+ let mut buf = Vec::with_capacity(
+ content_len
+ .map(|l| (l as usize).min(MAX_POSTER_BYTES))
+ .unwrap_or(64 * 1024),
+ );
+ while let Ok(Some(chunk)) = response.chunk().await {
+ if buf.len().saturating_add(chunk.len()) > MAX_POSTER_BYTES {
+ return None;
+ }
+ buf.extend_from_slice(&chunk);
+ }
+ if buf.is_empty() { None } else { Some(buf) }
+ }
+
+ pub async fn fetch_and_decode_cached_poster(
+ &self,
+ namespace: &str,
+ id: &str,
+ url: &str,
+ ) -> Option<Arc<image::DynamicImage>> {
+ let ns = namespace.to_string();
+ let id_owned = id.to_string();
+ if let Ok(Some(bytes)) = tokio::task::spawn_blocking(move || {
+ crate::cache::get_namespaced_image_cache(&ns, &id_owned)
+ })
+ .await
+ && let Some(img) = decode_poster(bytes).await
+ {
+ return Some(img);
}
- Some(bytes.to_vec())
+ let bytes = self.fetch_poster_bytes(url).await?;
+ let ns = namespace.to_string();
+ let id_owned = id.to_string();
+ let bytes_clone = bytes.clone();
+ let _ = tokio::task::spawn_blocking(move || {
+ crate::cache::set_namespaced_image_cache(&ns, &id_owned, &bytes_clone);
+ })
+ .await;
+ decode_poster(bytes).await
}
pub async fn download_subtitle_file(
@@ -352,7 +402,7 @@ impl MovieBoxService {
.unwrap_or_else(|| "srt".to_string());
let base_dir = resolve_subtitle_dir();
- let _ = std::fs::create_dir_all(&base_dir);
+ let _ = tokio::fs::create_dir_all(&base_dir).await;
let file_stem = if let Some(pref) = preferred_filename {
crate::download::safe_file_stem(pref)
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 235bdb4..01aefbd 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -3,10 +3,6 @@ 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 {
- crate::service::resolve_download_dir(self.state.download_dir.as_deref())
- }
-
pub(super) fn start_resilient_download(
&mut self,
subtitle_url: Option<String>,
@@ -63,21 +59,14 @@ impl App {
.unwrap_or("mp4")
.to_ascii_lowercase();
- let base_dir = self.resolve_download_base_dir();
- let (target_dir, base_name) = if is_series {
- (
- base_dir
- .join("Series")
- .join(&safe_title)
- .join(format!("Season {season}")),
- format!("{safe_title} - S{season:02}E{episode:02}"),
- )
- } else {
- (
- base_dir.join("Movies").join(&safe_title),
- safe_title.clone(),
- )
- };
+ let base_dir = crate::service::resolve_download_dir(self.state.download_dir.as_deref());
+ let (target_dir, base_name) = crate::download::resolve_media_target(
+ &base_dir,
+ &safe_title,
+ is_series,
+ season,
+ episode,
+ );
let destination = target_dir.join(format!("{base_name}.{extension}"));
{
let resolved_base =
@@ -128,7 +117,7 @@ impl App {
let sender = self.action_sender.clone();
let user_agent = self.service.client.user_agent().to_string();
- let mut client_builder = crate::net::streaming_client_builder()
+ let mut client_builder = crate::net::http_client_builder_base()
.connect_timeout(std::time::Duration::from_secs(15))
.tcp_keepalive(std::time::Duration::from_secs(30));
@@ -155,10 +144,10 @@ impl App {
log::warn!(
"failed to build custom download client ({err}), falling back to default"
);
- self.service.http_client().clone()
+ self.service.http_client.clone()
});
- let is_dash = link.ends_with(".mpd") || link.contains("/dash/");
+ let is_dash = crate::player::is_dash_url(&link);
self.request_tasks.cancel_download();
let validation_base_dir = base_dir.clone();
@@ -272,7 +261,7 @@ impl App {
cmd.arg("--add-header").arg(format!("{clean_k}: {clean_v}"));
}
}
- let format_spec = ytdlp_format_selector(max_height);
+ let format_spec = crate::player::ytdlp_format_selector(max_height);
cmd.arg("-f")
.arg(format_spec)
.arg("--newline")
@@ -687,14 +676,7 @@ impl App {
.state
.selected_details
.as_ref()
- .map(|d| {
- let mut ids = vec![d.id.value.clone()];
- ids.extend(d.dubs.iter().map(|dub| dub.subject_id.clone()));
- ids.retain(|s| !s.is_empty());
- ids.sort();
- ids.dedup();
- ids
- })
+ .map(|d| d.sibling_ids())
.unwrap_or_default();
let season = self.state.selected_season;
let episode = self.state.selected_episode;
@@ -757,12 +739,15 @@ impl App {
let clean_title = crate::providers::moviebox::clean_moviebox_title(raw_title);
let safe_title = crate::download::safe_file_stem(clean_title);
- let base_dir = self.resolve_download_base_dir();
- let target_dir = base_dir
- .join("Series")
- .join(&safe_title)
- .join(format!("Season {season}"));
- let base_name = format!("{safe_title} - S{season:02}E{episode:02}");
+ let base_dir =
+ crate::service::resolve_download_dir(self.state.download_dir.as_deref());
+ let (target_dir, base_name) = crate::download::resolve_media_target(
+ &base_dir,
+ &safe_title,
+ true,
+ season,
+ episode,
+ );
if is_media_already_downloaded(&target_dir, &base_name) {
self.state.notify(
@@ -1056,15 +1041,6 @@ pub(crate) fn yt_dlp_missing_guidance() -> String {
"DASH streams require yt-dlp & ffmpeg.".to_string()
}
}
-pub(crate) fn ytdlp_format_selector(max_height: Option<u64>) -> String {
- if let Some(height) = max_height.filter(|&h| h > 0) {
- format!(
- "bestvideo[height<={height}]+bestaudio/best[height<={height}]/bestvideo+bestaudio/best"
- )
- } else {
- "bestvideo+bestaudio/best".to_string()
- }
-}
pub(crate) fn parse_ytdlp_progress(line: &str) -> Option<(f64, String)> {
if !line.contains("[download]") || line.contains("Destination:") {
@@ -1149,7 +1125,6 @@ pub(crate) fn parse_ytdlp_progress(line: &str) -> Option<(f64, String)> {
#[cfg(test)]
mod tests {
- use super::*;
use crate::providers::models::{ProviderKind, Release, SourceMirror};
use crate::tui::action::Action;
use crate::tui::app::App;
@@ -1380,7 +1355,7 @@ mod tests {
Some("https://example.com/dash/123/index.mpd")
);
assert_eq!(max_height, Some(480));
- let format_spec = ytdlp_format_selector(max_height);
+ let format_spec = crate::player::ytdlp_format_selector(max_height);
assert_eq!(
format_spec,
"bestvideo[height<=480]+bestaudio/best[height<=480]/bestvideo+bestaudio/best"
@@ -1401,7 +1376,7 @@ mod tests {
match dispatched {
Action::StartDownload(_, _, _, max_height) => {
assert_eq!(max_height, Some(720));
- let format_spec = ytdlp_format_selector(max_height);
+ let format_spec = crate::player::ytdlp_format_selector(max_height);
assert_eq!(
format_spec,
"bestvideo[height<=720]+bestaudio/best[height<=720]/bestvideo+bestaudio/best"
@@ -1414,28 +1389,35 @@ mod tests {
#[test]
fn test_ytdlp_format_selector_specs() {
assert_eq!(
- ytdlp_format_selector(Some(480)),
+ crate::player::ytdlp_format_selector(Some(480)),
"bestvideo[height<=480]+bestaudio/best[height<=480]/bestvideo+bestaudio/best"
);
assert_eq!(
- ytdlp_format_selector(Some(720)),
+ crate::player::ytdlp_format_selector(Some(720)),
"bestvideo[height<=720]+bestaudio/best[height<=720]/bestvideo+bestaudio/best"
);
assert_eq!(
- ytdlp_format_selector(Some(1080)),
+ crate::player::ytdlp_format_selector(Some(1080)),
"bestvideo[height<=1080]+bestaudio/best[height<=1080]/bestvideo+bestaudio/best"
);
- assert_eq!(ytdlp_format_selector(None), "bestvideo+bestaudio/best");
- assert_eq!(ytdlp_format_selector(Some(0)), "bestvideo+bestaudio/best");
+ assert_eq!(
+ crate::player::ytdlp_format_selector(None),
+ "bestvideo+bestaudio/best"
+ );
+ assert_eq!(
+ crate::player::ytdlp_format_selector(Some(0)),
+ "bestvideo+bestaudio/best"
+ );
}
#[test]
fn test_download_directory_and_filename_conventions() {
let base_dir = std::path::PathBuf::from("/tmp/MovieBox-TUI");
let movie_title = "Ek Deewane Ki Deewaniyat";
- let movie_target = base_dir.join("Movies").join(movie_title);
- let movie_file = movie_target.join(format!("{movie_title}.mp4"));
- let movie_sub = movie_target.join(format!("{movie_title}.en.srt"));
+ let (movie_target, movie_base) =
+ crate::download::resolve_media_target(&base_dir, movie_title, false, 1, 1);
+ let movie_file = movie_target.join(format!("{movie_base}.mp4"));
+ let movie_sub = movie_target.join(format!("{movie_base}.en.srt"));
let expected_movie_file = base_dir
.join("Movies")
@@ -1451,11 +1433,8 @@ mod tests {
let series_title = "Breaking Bad";
let season: usize = 1;
let episode: usize = 1;
- let series_target = base_dir
- .join("Series")
- .join(series_title)
- .join(format!("Season {season}"));
- let base_name = format!("{series_title} - S{season:02}E{episode:02}");
+ let (series_target, base_name) =
+ crate::download::resolve_media_target(&base_dir, series_title, true, season, episode);
let series_file = series_target.join(format!("{base_name}.mp4"));
let series_sub = series_target.join(format!("{base_name}.en.srt"));
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 5039774..3a9874c 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -11,7 +11,6 @@ mod favorites;
mod keyboard;
mod mouse;
mod navigation;
-mod network;
mod playback;
mod requests;
mod run;
diff --git a/src/tui/app/network.rs b/src/tui/app/network.rs
deleted file mode 100644
index ebd6c4c..0000000
--- a/src/tui/app/network.rs
+++ /dev/null
@@ -1,13 +0,0 @@
-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)
- .header("User-Agent", crate::net::APP_HTTP_USER_AGENT)
- .send()
- .await
- .ok()?
- .error_for_status()
- .ok()?;
- Some(response.bytes().await.ok()?.to_vec())
-}
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index b05fef4..ab9c6bc 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -282,7 +282,9 @@ impl App {
.record_start(item, resume_seconds.unwrap_or(0));
}
- if let (Some((p, s, se, ep)), Some(item)) = (&tracker_opts, &history_item) {
+ if matches!(kind, crate::tui::state::PlayerKind::Mpv)
+ && let (Some((p, s, se, ep)), Some(item)) = (&tracker_opts, &history_item)
+ {
if let Some(state_path) = crate::player::tracker::state_file_path(p, s, *se, *ep) {
let initial_state = crate::history::PendingPlaybackState::from_item(
item,
@@ -360,7 +362,8 @@ impl App {
crate::logging::sanitize_url(url)
);
let _ = sender.send(Action::SetStatus(
- "External subtitle unavailable; playing stream directly.".to_string(),
+ "Warning: External subtitle unavailable; playing stream directly."
+ .to_string(),
));
}
}
@@ -370,17 +373,27 @@ 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 | crate::tui::state::PlayerKind::AndroidIntent
- ) && headers.iter().any(|(name, _)| {
+ let is_dash = crate::player::is_dash_url(&link);
+ let has_extra_headers = headers.iter().any(|(name, _)| {
!name.eq_ignore_ascii_case("referer") && !name.eq_ignore_ascii_case("user-agent")
});
+ let needs_proxy = is_dash
+ || (matches!(
+ kind,
+ crate::tui::state::PlayerKind::Vlc
+ | crate::tui::state::PlayerKind::AndroidIntent
+ ) && has_extra_headers);
+ let sidecar_sub = if matches!(kind, crate::tui::state::PlayerKind::AndroidIntent) {
+ subtitle.as_deref()
+ } else {
+ None
+ };
+ let mut sidecar_child = None;
let (effective_link, effective_subtitle) = if needs_proxy {
- match crate::proxy::spawn_sidecar(&link, &headers, subtitle.as_deref(), max_height)
- {
- Ok(local_url) => {
+ match crate::proxy::spawn_sidecar(&link, &headers, sidecar_sub, max_height) {
+ Ok((local_url, sc_child)) => {
+ sidecar_child = Some(sc_child);
let sub_url =
if matches!(kind, crate::tui::state::PlayerKind::AndroidIntent) {
if local_subtitle.is_some() {
@@ -407,37 +420,56 @@ impl App {
(local_url, sub_url)
}
Err(err) => {
- log::error!("Failed to spawn stream proxy sidecar: {err}");
- let _ = sender.send(Action::PlayerExited);
- let _ = sender.send(Action::SetStatus(format!(
- "Stream proxy initialization failed: {err}"
- )));
- return;
+ if matches!(
+ kind,
+ crate::tui::state::PlayerKind::Mpv
+ | crate::tui::state::PlayerKind::Iina
+ ) {
+ log::warn!(
+ "Failed to spawn stream proxy sidecar ({err}), falling back to direct playback"
+ );
+ (link.clone(), local_subtitle.clone())
+ } else {
+ log::error!("Failed to spawn stream proxy sidecar: {err}");
+ let _ = sender.send(Action::PlayerExited);
+ let _ = sender.send(Action::SetStatus(format!(
+ "Error: Stream proxy initialization failed: {err}"
+ )));
+ return;
+ }
}
}
} else {
(link.clone(), local_subtitle.clone())
};
+ let log_dir = std::env::temp_dir().join("moviebox-tui/subs");
+ let _ = std::fs::create_dir_all(&log_dir);
+ let log_stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let log_path = log_dir.join(format!("player_{}_{log_stamp}.log", std::process::id()));
+
let spawn_configured_command =
|mut cmd: std::process::Command, capture_stdout: bool| {
cmd.stdin(std::process::Stdio::null());
+ let log_file = std::fs::File::create(&log_path).ok();
if capture_stdout {
- cmd.stdout(std::process::Stdio::piped());
+ if let Some(cloned) = log_file.as_ref().and_then(|f| f.try_clone().ok()) {
+ cmd.stdout(std::process::Stdio::from(cloned));
+ } else {
+ cmd.stdout(std::process::Stdio::null());
+ }
} else {
cmd.stdout(std::process::Stdio::null());
}
- cmd.stderr(std::process::Stdio::piped());
- #[cfg(unix)]
- {
- use std::os::unix::process::CommandExt;
- cmd.process_group(0);
- }
- #[cfg(windows)]
- {
- use std::os::windows::process::CommandExt;
- cmd.creation_flags(0x0000_0200);
+ if let Some(file) = log_file {
+ cmd.stderr(std::process::Stdio::from(file));
+ } else {
+ cmd.stderr(std::process::Stdio::null());
}
+ crate::player::configure_detached_process(&mut cmd);
cmd.spawn()
};
let is_android = matches!(kind, crate::tui::state::PlayerKind::AndroidIntent);
@@ -456,7 +488,8 @@ impl App {
&& (!headers.is_empty() || subtitle.is_some())
{
let _ = sender.send(Action::SetStatus(
- "IINA opened without iina-cli: headers and subtitles unavailable.".to_string(),
+ "Warning: IINA opened without iina-cli: headers and subtitles unavailable."
+ .to_string(),
));
}
@@ -498,45 +531,27 @@ impl App {
match spawn_result {
Ok(mut child) => {
let start_time = std::time::Instant::now();
- let stderr_stream = child.stderr.take();
- let stdout_stream = child.stdout.take();
let fallback_link = effective_link.clone();
let fallback_sub = effective_subtitle.clone();
let fallback_headers = headers.clone();
tokio::task::spawn_blocking(move || {
- let mut error_output = String::new();
- let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
- if let Some(mut stderr) = stderr_stream {
- std::thread::spawn(move || {
- let mut buf = String::new();
- use std::io::Read;
- let _ = stderr.read_to_string(&mut buf);
- let _ = stderr_tx.send(buf);
- });
- } else {
- drop(stderr_tx);
- }
-
- if let Some(mut stdout) = stdout_stream {
- use std::io::Read;
- let _ = stdout.read_to_string(&mut error_output);
- }
-
let result = child.wait();
- let stderr_str = stderr_rx
- .recv_timeout(std::time::Duration::from_secs(2))
- .unwrap_or_default();
- if !stderr_str.is_empty() {
- if !error_output.is_empty() {
- error_output.push('\n');
- }
- error_output.push_str(&stderr_str);
- }
+ let error_output = std::fs::read_to_string(&log_path).unwrap_or_default();
+ let _ = std::fs::remove_file(&log_path);
- match result {
- Ok(status) if status.success() => {
+ match &result {
+ Ok(status)
+ if status.success()
+ || is_vlc_normal_exit(
+ kind,
+ status.code(),
+ error_output.trim(),
+ )
+ || is_user_quit(status) =>
+ {
log::info!(
- "player {kind:?} finished cleanly (duration: {}s)",
+ "player {kind:?} finished cleanly (code: {:?}, duration: {}s)",
+ status.code(),
start_time.elapsed().as_secs()
);
let has_tracker = tracker_opts.is_some()
@@ -569,40 +584,6 @@ impl App {
}
}
}
- Ok(status)
- if is_vlc_normal_exit(kind, status.code(), error_output.trim())
- || is_user_quit(&status) =>
- {
- log::info!(
- "player {:?} exited cleanly (code: {:?})",
- kind,
- status.code()
- );
- if let Some(item) = history_item {
- let elapsed = start_time.elapsed().as_secs();
- if elapsed >= 30 {
- let duration = item.duration_seconds;
- let start_pos = resume_seconds.unwrap_or(0);
- let total_pos = start_pos.saturating_add(elapsed);
- let progress = if let Some(d) = duration {
- total_pos.min(d)
- } else {
- total_pos
- };
- let completed = duration.is_some_and(|d| {
- d > 0 && progress >= (d as f64 * 0.90) as u64
- });
- sender
- .send(Action::UpdateProgress {
- item: Box::new(item),
- progress,
- duration,
- completed,
- })
- .ok();
- }
- }
- }
Ok(status) => {
let is_termux_socket_err = is_android
&& (error_output.contains("am.sock")
@@ -633,13 +614,11 @@ impl App {
&fallback_headers,
);
fallback_cmd.stdin(std::process::Stdio::null());
- fallback_cmd.stdout(std::process::Stdio::piped());
- fallback_cmd.stderr(std::process::Stdio::piped());
- #[cfg(unix)]
- {
- use std::os::unix::process::CommandExt;
- fallback_cmd.process_group(0);
- }
+ fallback_cmd.stdout(std::process::Stdio::null());
+ fallback_cmd.stderr(std::process::Stdio::null());
+ crate::player::configure_detached_process(
+ &mut fallback_cmd,
+ );
if let Ok(mut retry_child) = fallback_cmd.spawn() {
if let Ok(retry_status) = retry_child.wait() {
if retry_status.success() {
@@ -679,8 +658,18 @@ impl App {
.ok();
}
}
-
- if let Some(path) = temporary_subtitle {
+ if !is_android
+ && (matches!(kind, crate::tui::state::PlayerKind::Mpv)
+ || start_time.elapsed() >= std::time::Duration::from_secs(3)
+ || result.as_ref().is_ok_and(|s| !s.success()))
+ && let Some(mut sc) = sidecar_child
+ {
+ let _ = sc.kill();
+ let _ = sc.wait();
+ }
+ if start_time.elapsed() >= std::time::Duration::from_secs(3)
+ && let Some(path) = temporary_subtitle
+ {
let _ = std::fs::remove_file(path);
}
sender.send(Action::PlayerExited).ok();
@@ -692,6 +681,11 @@ impl App {
kind,
crate::logging::sanitize_url(&link)
);
+ let _ = tokio::fs::remove_file(&log_path).await;
+ if let Some(mut sc) = sidecar_child {
+ let _ = sc.kill();
+ let _ = sc.wait();
+ }
if let Some(path) = temporary_subtitle {
let _ = tokio::fs::remove_file(path).await;
}
@@ -897,32 +891,11 @@ impl App {
.state
.selected_details
.as_ref()
- .map(|d| {
- let mut ids = vec![d.id.value.clone()];
- ids.extend(d.dubs.iter().map(|dub| dub.subject_id.clone()));
- ids.retain(|s| !s.is_empty());
- ids.sort();
- ids.dedup();
- ids
- })
+ .map(|d| d.sibling_ids())
.unwrap_or_default();
let season = self.state.selected_season;
let episode = self.state.selected_episode;
tokio::spawn(async move {
- let cached = tokio::task::spawn_blocking({
- let subject_id = subject_id.clone();
- let rid = rid.clone();
- move || crate::cache::get_captions_cache_typed(&subject_id, &rid)
- })
- .await
- .ok()
- .flatten();
- if let Some(res) = cached {
- sender
- .send(Action::ShowSubtitlePopup(source_clone.url.clone(), res))
- .ok();
- return;
- }
let result = tokio::time::timeout(
std::time::Duration::from_secs(15),
service.get_ext_captions(
@@ -936,16 +909,6 @@ impl App {
.await;
match result {
Ok(Ok(res)) => {
- let subject_id = subject_id.clone();
- let rid = rid.clone();
- let res_for_cache = res.clone();
- tokio::task::spawn_blocking(move || {
- crate::cache::set_captions_cache_typed(
- &subject_id,
- &rid,
- &res_for_cache,
- );
- });
sender
.send(Action::ShowSubtitlePopup(source_clone.url, res))
.ok();
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index fcd65f1..e1de527 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -1,4 +1,4 @@
-use super::{App, network};
+use super::App;
use crate::models::{Episode, MediaType, ProviderKind, Season};
use crate::tui::{
action::Action,
@@ -608,42 +608,14 @@ impl App {
let cover_url = channel.logo.clone();
if !cover_url.is_empty() {
let tx = self.action_sender.clone();
- let client = self.service.http_client().clone();
+ let service = self.service.clone();
let id2 = id.clone();
tokio::spawn(async move {
- if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
- let id_clone = id2.clone();
- move || {
- crate::cache::get_namespaced_image_cache(
- "iptv", &id_clone,
- )
- }
- })
- .await
+ if let Some(img) = service
+ .fetch_and_decode_cached_poster("iptv", &id2, &cover_url)
+ .await
{
- if let Some(img) = network::decode_poster(bytes).await {
- tx.send(Action::SearchPosterLoaded(id2, Some(img)))
- .ok();
- return;
- }
- }
- if let Some(bytes) =
- network::fetch_poster_bytes(&client, &cover_url).await
- {
- let bytes_clone = bytes.clone();
- let id_clone = id2.clone();
- let _ = tokio::task::spawn_blocking(move || {
- crate::cache::set_namespaced_image_cache(
- "iptv",
- &id_clone,
- &bytes_clone,
- )
- })
- .await;
- if let Some(img) = network::decode_poster(bytes).await {
- tx.send(Action::SearchPosterLoaded(id2, Some(img)))
- .ok();
- }
+ tx.send(Action::SearchPosterLoaded(id2, Some(img))).ok();
}
});
}
@@ -676,38 +648,13 @@ impl App {
let url = url.to_string();
let tx = self.action_sender.clone();
let id2 = id.clone();
- let client = self.service.http_client().clone();
+ let service = self.service.clone();
tokio::spawn(async move {
- if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
- let id_clone = id2.clone();
- move || {
- crate::cache::get_namespaced_image_cache(
- prov.cache_key(),
- &id_clone,
- )
- }
- })
- .await
+ if let Some(img) = service
+ .fetch_and_decode_cached_poster(prov.cache_key(), &id2, &url)
+ .await
{
- if let Some(img) = network::decode_poster(bytes).await {
- tx.send(Action::PosterSuccess(id2, img)).ok();
- return;
- }
- }
- if let Some(bytes) = network::fetch_poster_bytes(&client, &url).await {
- let bytes_clone = bytes.clone();
- let id_clone = id2.clone();
- let _ = tokio::task::spawn_blocking(move || {
- crate::cache::set_namespaced_image_cache(
- prov.cache_key(),
- &id_clone,
- &bytes_clone,
- )
- })
- .await;
- if let Some(img) = network::decode_poster(bytes).await {
- tx.send(Action::PosterSuccess(id2, img)).ok();
- }
+ tx.send(Action::PosterSuccess(id2, img)).ok();
}
});
}
@@ -798,35 +745,13 @@ impl App {
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
- let http_client = self.service.http_client().clone();
+ let service = self.service.clone();
tokio::spawn(async move {
- if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
- let id_clone = id_clone.clone();
- move || crate::cache::get_namespaced_image_cache("posters", &id_clone)
- })
- .await
- {
- if let Some(img) = network::decode_poster(bytes).await {
- let _ = action_tx.send(Action::PosterSuccess(id_clone, img));
- return;
- }
- }
- if let Some(bytes) =
- network::fetch_poster_bytes(&http_client, &url_clone).await
+ if let Some(img) = service
+ .fetch_and_decode_cached_poster("posters", &id_clone, &url_clone)
+ .await
{
- let bytes_clone = bytes.clone();
- let id_clone2 = id_clone.clone();
- let _ = tokio::task::spawn_blocking(move || {
- crate::cache::set_namespaced_image_cache(
- "posters",
- &id_clone2,
- &bytes_clone,
- )
- })
- .await;
- if let Some(img) = network::decode_poster(bytes).await {
- let _ = action_tx.send(Action::PosterSuccess(id_clone, img));
- }
+ let _ = action_tx.send(Action::PosterSuccess(id_clone, img));
}
});
}
@@ -988,41 +913,15 @@ impl App {
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
- let http_client = self.service.http_client().clone();
+ let service = self.service.clone();
tokio::spawn(async move {
- if let Ok(Some(bytes)) = tokio::task::spawn_blocking({
- let id_clone = id_clone.clone();
- move || {
- crate::cache::get_namespaced_image_cache(
- "posters", &id_clone,
- )
- }
- })
- .await
+ if let Some(img) = service
+ .fetch_and_decode_cached_poster(
+ "posters", &id_clone, &url_clone,
+ )
+ .await
{
- if let Some(img) = network::decode_poster(bytes).await {
- let _ =
- action_tx.send(Action::PosterSuccess(id_clone, img));
- return;
- }
- }
- if let Some(bytes) =
- network::fetch_poster_bytes(&http_client, &url_clone).await
- {
- let bytes_clone = bytes.clone();
- let id_clone2 = id_clone.clone();
- let _ = tokio::task::spawn_blocking(move || {
- crate::cache::set_namespaced_image_cache(
- "posters",
- &id_clone2,
- &bytes_clone,
- );
- })
- .await;
- if let Some(img) = network::decode_poster(bytes).await {
- let _ =
- action_tx.send(Action::PosterSuccess(id_clone, img));
- }
+ let _ = action_tx.send(Action::PosterSuccess(id_clone, img));
}
});
}
@@ -1225,16 +1124,16 @@ impl App {
let url_clone = url.to_string();
let action_tx = self.action_sender.clone();
let id_clone = id.clone();
- let http_client = self.service.http_client().clone();
+ let service = self.service.clone();
tokio::spawn(async move {
- if let Some(bytes) =
- network::fetch_poster_bytes(&http_client, &url_clone)
- .await
+ if let Some(img) = service
+ .fetch_and_decode_cached_poster(
+ "posters", &id_clone, &url_clone,
+ )
+ .await
{
- if let Some(img) = network::decode_poster(bytes).await {
- let _ = action_tx
- .send(Action::PosterSuccess(id_clone, img));
- }
+ let _ = action_tx
+ .send(Action::PosterSuccess(id_clone, img));
}
});
}
@@ -1420,7 +1319,7 @@ impl App {
if !blocked_addons.is_empty() {
sender
.send(Action::SetStatus(format!(
- "Blocked {} torrent streams. HTTP only.",
+ "Warning: Blocked {} torrent streams. HTTP only.",
blocked_addons.join(", ")
)))
.ok();
@@ -1595,10 +1494,6 @@ impl App {
let id_clone = subject_id.clone();
self.request_tasks.spawn_streams(async move {
- sender
- .send(Action::SetStatus("Fetching streams...".to_string()))
- .ok();
-
match crate::providers::ReleaseProvider::episode_streams(
&client, &id_clone, season, episode,
)
@@ -1798,49 +1693,14 @@ impl App {
.state
.selected_details
.as_ref()
- .map(|d| {
- let mut ids = vec![d.id.value.clone()];
- ids.extend(d.dubs.iter().map(|dub| dub.subject_id.clone()));
- ids.retain(|s| !s.is_empty());
- ids.sort();
- ids.dedup();
- ids
- })
+ .map(|d| d.sibling_ids())
.unwrap_or_default();
let season = self.state.selected_season;
let episode = self.state.selected_episode;
tokio::spawn(async move {
- let already_cached = tokio::task::spawn_blocking({
- let subject_id = subject_id.clone();
- let rid = rid.clone();
- move || {
- crate::cache::get_captions_cache_typed(&subject_id, &rid)
- .is_some()
- }
- })
- .await
- .unwrap_or(false);
-
- if !already_cached {
- if let Ok(res) = service
- .get_ext_captions(
- &subject_id,
- &rid,
- &sibling_ids,
- season,
- episode,
- )
- .await
- {
- tokio::task::spawn_blocking(move || {
- crate::cache::set_captions_cache_typed(
- &subject_id,
- &rid,
- &res,
- );
- });
- }
- }
+ let _ = service
+ .get_ext_captions(&subject_id, &rid, &sibling_ids, season, episode)
+ .await;
});
}
}
diff --git a/src/tui/app/search.rs b/src/tui/app/search.rs
index fb00616..ef713dd 100644
--- a/src/tui/app/search.rs
+++ b/src/tui/app/search.rs
@@ -1,4 +1,4 @@
-use super::{App, network};
+use super::App;
use crate::models::CatalogItem;
use crate::providers::models::{ProviderKind, RequestContext};
use crate::tui::{
@@ -688,7 +688,7 @@ impl App {
})
.await
{
- if let Some(img) = network::decode_poster(bytes).await {
+ if let Some(img) = crate::service::decode_poster(bytes).await {
tx.send(Action::SearchPosterLoaded(id_clone, Some(img)))
.ok();
return;
@@ -723,7 +723,7 @@ impl App {
return;
}
- if let Some(img) = network::decode_poster(bytes).await {
+ if let Some(img) = crate::service::decode_poster(bytes).await {
tx.send(Action::SearchPosterLoaded(id, Some(img))).ok();
return;
}
diff --git a/src/tui/app/system.rs b/src/tui/app/system.rs
index 29faba4..c84fd64 100644
--- a/src/tui/app/system.rs
+++ b/src/tui/app/system.rs
@@ -326,7 +326,9 @@ impl App {
self.state.download_dir = None;
self.state.settings_download_dir_input = None;
self.persist_config();
- let default_dir = crate::logging::sanitize_path(self.resolve_download_base_dir());
+ let default_dir = crate::logging::sanitize_path(
+ crate::service::resolve_download_dir(self.state.download_dir.as_deref()),
+ );
self.state.notify(
NotificationKind::Success,
"Download Folder",
@@ -455,7 +457,9 @@ impl App {
self.state.download_dir = None;
self.persist_config();
let default_dir = crate::logging::sanitize_path(
- self.resolve_download_base_dir(),
+ crate::service::resolve_download_dir(
+ self.state.download_dir.as_deref(),
+ ),
);
self.state.notify(
NotificationKind::Success,
@@ -683,7 +687,17 @@ impl App {
};
self.state
.notify(NotificationKind::Error, title, clean_body);
+ } else if let Some(body) = msg.strip_prefix("Warning:") {
+ log::warn!("{msg}");
+ self.state
+ .notify(NotificationKind::Warning, "Notice", body.trim());
} else {
+ if self.state.active_screen != crate::tui::state::Screen::Home
+ || self.state.addon_manager_popup
+ {
+ self.state
+ .notify(NotificationKind::Info, "Status", msg.clone());
+ }
self.state.set_status_default(msg);
}
}
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index 7baaa92..85154b6 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -431,14 +431,54 @@ pub fn browse_category_badge<'a>(label: &str, theme: &'a Theme) -> (Span<'a>, &'
}
}
-pub fn notifications(
- frame: &mut Frame,
+struct NotificationCard<'a> {
+ original_idx: usize,
+ notification: &'a Notification,
+ rect: Rect,
+ inner_width: usize,
+ msg_lines: Vec<String>,
+}
+
+fn notification_badge(kind: NotificationKind, basic_terminal: bool) -> &'static str {
+ match kind {
+ NotificationKind::Info => {
+ if basic_terminal {
+ "i INFO"
+ } else {
+ "ℹ INFO"
+ }
+ }
+ NotificationKind::Success => {
+ if basic_terminal {
+ "+ SUCCESS"
+ } else {
+ "✔ SUCCESS"
+ }
+ }
+ NotificationKind::Warning => {
+ if basic_terminal {
+ "! WARNING"
+ } else {
+ "⚠ WARNING"
+ }
+ }
+ NotificationKind::Error => {
+ if basic_terminal {
+ "x ERROR"
+ } else {
+ "✖ ERROR"
+ }
+ }
+ }
+}
+
+fn compute_notification_cards<'a>(
area: Rect,
- notifications: &std::collections::VecDeque<Notification>,
- theme: &Theme,
+ notifications: &'a std::collections::VecDeque<Notification>,
basic_terminal: bool,
download_active: bool,
-) {
+) -> Vec<NotificationCard<'a>> {
+ let mut cards = Vec::new();
let bottom_offset = if download_active { 5 } else { 2 };
let mut y = area.bottom().saturating_sub(bottom_offset);
@@ -452,8 +492,8 @@ pub fn notifications(
(3, 64.min(area.width.saturating_sub(4) as usize), 3)
};
- for notification in notifications.iter().rev().take(max_visible) {
- let (badge, badge_style) = notification_style(notification.kind, theme, basic_terminal);
+ for (rev_idx, notification) in notifications.iter().rev().take(max_visible).enumerate() {
+ let badge = notification_badge(notification.kind, basic_terminal);
let has_message =
!notification.message.is_empty() && notification.message != notification.title;
@@ -494,7 +534,7 @@ pub fn notifications(
}
y = y.saturating_sub(height);
- let toast_area = Rect::new(
+ let rect = Rect::new(
area.right()
.saturating_sub(target_card_width)
.saturating_sub(2),
@@ -503,27 +543,54 @@ pub fn notifications(
height,
);
- crate::tui::clear_area(frame, toast_area, theme);
+ let original_idx = notifications.len().saturating_sub(1 + rev_idx);
+ cards.push(NotificationCard {
+ original_idx,
+ notification,
+ rect,
+ inner_width,
+ msg_lines,
+ });
+
+ y = y.saturating_sub(1);
+ }
+ cards
+}
+
+pub fn notifications(
+ frame: &mut Frame,
+ area: Rect,
+ notifications: &std::collections::VecDeque<Notification>,
+ theme: &Theme,
+ basic_terminal: bool,
+ download_active: bool,
+) {
+ for card in compute_notification_cards(area, notifications, basic_terminal, download_active) {
+ let (badge, badge_style) =
+ notification_style(card.notification.kind, theme, basic_terminal);
+
+ crate::tui::clear_area(frame, card.rect, theme);
let mut lines = Vec::new();
lines.push(Line::from(vec![Span::styled(
- crate::tui::text::truncate_width(&notification.title, inner_width),
+ crate::tui::text::truncate_width(&card.notification.title, card.inner_width),
badge_style.add_modifier(Modifier::BOLD),
)]));
- for line in &msg_lines {
+ for line in &card.msg_lines {
lines.push(Line::from(vec![Span::styled(
- crate::tui::text::truncate_width(line, inner_width),
+ crate::tui::text::truncate_width(line, card.inner_width),
theme.subtext1,
)]));
}
- let total_duration = notification.kind.total_duration();
- let remaining = notification
+ let total_duration = card.notification.kind.total_duration();
+ let remaining = card
+ .notification
.expires_at
.saturating_duration_since(std::time::Instant::now());
let ratio = (remaining.as_secs_f64() / total_duration.as_secs_f64()).clamp(0.0, 1.0);
- let bar_width = inner_width.clamp(3, 16);
+ let bar_width = card.inner_width.clamp(3, 16);
let filled = ((bar_width as f64) * ratio).round() as usize;
let countdown_bar = if basic_terminal {
format!(
@@ -556,9 +623,7 @@ pub fn notifications(
.border_style(badge_style)
.padding(ratatui::widgets::Padding::horizontal(1));
- frame.render_widget(Paragraph::new(lines).block(block), toast_area);
-
- y = y.saturating_sub(1);
+ frame.render_widget(Paragraph::new(lines).block(block), card.rect);
}
}
@@ -645,36 +710,13 @@ fn notification_style(
theme: &Theme,
basic_terminal: bool,
) -> (&'static str, Style) {
- match kind {
- NotificationKind::Info => (
- if basic_terminal { "i INFO" } else { "ℹ INFO" },
- theme.sapphire,
- ),
- NotificationKind::Success => (
- if basic_terminal {
- "+ SUCCESS"
- } else {
- "✔ SUCCESS"
- },
- theme.success,
- ),
- NotificationKind::Warning => (
- if basic_terminal {
- "! WARNING"
- } else {
- "⚠ WARNING"
- },
- theme.rating,
- ),
- NotificationKind::Error => (
- if basic_terminal {
- "x ERROR"
- } else {
- "✖ ERROR"
- },
- theme.error,
- ),
- }
+ let style = match kind {
+ NotificationKind::Info => theme.sapphire,
+ NotificationKind::Success => theme.success,
+ NotificationKind::Warning => theme.rating,
+ NotificationKind::Error => theme.error,
+ };
+ (notification_badge(kind, basic_terminal), style)
}
pub fn notification_rects(
@@ -683,79 +725,10 @@ pub fn notification_rects(
basic_terminal: bool,
download_active: bool,
) -> Vec<(usize, Rect)> {
- let mut rects = Vec::new();
- let bottom_offset = if download_active { 5 } else { 2 };
- let mut y = area.bottom().saturating_sub(bottom_offset);
- let theme_placeholder = Theme::default();
-
- let (max_visible, max_card_w, max_msg_lines) = if area.height < 20 {
- (1, 42.min(area.width.saturating_sub(4) as usize), 1)
- } else if area.width < 65 {
- (1, 42.min(area.width.saturating_sub(4) as usize), 2)
- } else if area.height < 30 {
- (2, 56.min(area.width.saturating_sub(4) as usize), 2)
- } else {
- (3, 64.min(area.width.saturating_sub(4) as usize), 3)
- };
-
- for (rev_idx, notification) in notifications.iter().rev().take(max_visible).enumerate() {
- let (badge, _) = notification_style(notification.kind, &theme_placeholder, basic_terminal);
- let has_message =
- !notification.message.is_empty() && notification.message != notification.title;
-
- let title_w = crate::tui::text::width(&notification.title).saturating_add(6);
- let badge_w = crate::tui::text::width(badge).saturating_add(6);
- let raw_msg_w = if has_message {
- notification
- .message
- .lines()
- .map(|line| crate::tui::text::width(line.trim()))
- .max()
- .unwrap_or(0)
- .saturating_add(6)
- } else {
- 0
- };
-
- let target_card_width = title_w
- .max(badge_w)
- .max(raw_msg_w)
- .clamp(20, max_card_w.max(20)) as u16;
-
- let inner_width = (target_card_width.saturating_sub(4) as usize).max(1);
-
- let msg_lines: Vec<String> = if has_message {
- crate::tui::text::wrap_text(&notification.message, inner_width)
- .into_iter()
- .take(max_msg_lines)
- .collect()
- } else {
- Vec::new()
- };
-
- let height = 2 + 1 + msg_lines.len() as u16;
-
- if target_card_width < 10 || y < area.y.saturating_add(height) {
- break;
- }
-
- y = y.saturating_sub(height);
-
- let toast_area = Rect::new(
- area.right()
- .saturating_sub(target_card_width)
- .saturating_sub(2),
- y,
- target_card_width,
- height,
- );
-
- let original_idx = notifications.len().saturating_sub(1 + rev_idx);
- rects.push((original_idx, toast_area));
-
- y = y.saturating_sub(1);
- }
- rects
+ compute_notification_cards(area, notifications, basic_terminal, download_active)
+ .into_iter()
+ .map(|card| (card.original_idx, card.rect))
+ .collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/src/updater/apply.rs b/src/updater/apply.rs
index 1cacef8..8a1e6c5 100644
--- a/src/updater/apply.rs
+++ b/src/updater/apply.rs
@@ -23,8 +23,30 @@ pub enum InstallationEnvironment {
}
impl InstallationEnvironment {
+ pub fn upgrade_instruction(&self) -> Option<&'static str> {
+ match self {
+ Self::Homebrew => {
+ Some("This installation is managed by Homebrew. Run: brew upgrade moviebox-tui")
+ }
+ Self::Scoop => {
+ Some("This installation is managed by Scoop. Run: scoop update moviebox-tui")
+ }
+ Self::Termux => Some(
+ "Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'",
+ ),
+ Self::Flatpak => Some("Running inside Flatpak. Please update via: flatpak update"),
+ Self::Snap => {
+ Some("Running inside Snap. Please update via: sudo snap refresh moviebox-tui")
+ }
+ Self::ReadOnly => Some(
+ "MovieBox-Tui binary is not user-writable. Please update via your system package manager.",
+ ),
+ Self::DirectReplace | Self::WindowsHelper => None,
+ }
+ }
+
pub fn has_managed_notice(&self) -> bool {
- !matches!(self, Self::DirectReplace | Self::WindowsHelper)
+ self.upgrade_instruction().is_some()
}
}
@@ -121,37 +143,13 @@ pub fn apply_staged_binary(
) -> Result<SelfUpdateOutcome, String> {
let env = detect_environment(current_exe);
+ if let Some(instruction) = env.upgrade_instruction() {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ instruction.to_string(),
+ ));
+ }
+
match env {
- InstallationEnvironment::Homebrew => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui".to_string(),
- ))
- }
- InstallationEnvironment::Scoop => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "This installation is managed by Scoop. Run: scoop update moviebox-tui".to_string(),
- ))
- }
- InstallationEnvironment::Termux => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
- ))
- }
- InstallationEnvironment::Flatpak => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Running inside Flatpak. Please update via: flatpak update".to_string(),
- ))
- }
- InstallationEnvironment::Snap => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Running inside Snap. Please update via: sudo snap refresh moviebox-tui".to_string(),
- ))
- }
- InstallationEnvironment::ReadOnly => {
- Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
- ))
- }
InstallationEnvironment::DirectReplace => {
replace_binary_with_backup(staged_path, current_exe)?;
Ok(SelfUpdateOutcome::Success)
@@ -163,6 +161,7 @@ pub fn apply_staged_binary(
}
result.map(|_| SelfUpdateOutcome::Success)
}
+ _ => unreachable!(),
}
}
@@ -178,9 +177,6 @@ pub fn stale_update_artifacts(current_exe: &Path) -> Vec<PathBuf> {
}
pub fn cleanup_stale_update_artifacts(current_exe: &Path) {
- if !cfg!(windows) {
- return;
- }
for path in stale_update_artifacts(current_exe) {
let _ = std::fs::remove_file(path);
}
@@ -213,6 +209,9 @@ fn replace_binary_with_backup(staged_path: &Path, current_exe: &Path) -> Result<
if let Err(err) = install_result {
if backup_path.exists() {
+ if current_exe.exists() {
+ let _ = std::fs::remove_file(current_exe);
+ }
let _ = std::fs::rename(&backup_path, current_exe);
}
return Err(err);
@@ -381,7 +380,6 @@ mod tests {
assert_eq!(*lines.last().expect("non-empty"), "del \"%~f0\"");
}
- #[cfg(windows)]
#[test]
fn cleanup_removes_only_known_artifacts() {
let dir = std::env::temp_dir().join(format!("mbx_apply_test_{}", std::process::id()));
diff --git a/src/updater/mod.rs b/src/updater/mod.rs
index 81fe5eb..0089a53 100644
--- a/src/updater/mod.rs
+++ b/src/updater/mod.rs
@@ -20,40 +20,10 @@ pub async fn perform_self_update(
.map_err(|e| format!("failed to get current executable path: {e}"))?;
let env = detect_environment(&current_exe);
- match env {
- InstallationEnvironment::Homebrew => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "This installation is managed by Homebrew. Run: brew upgrade moviebox-tui"
- .to_string(),
- ));
- }
- InstallationEnvironment::Scoop => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "This installation is managed by Scoop. Run: scoop update moviebox-tui".to_string(),
- ));
- }
- InstallationEnvironment::Termux => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Android / Termux update: run 'curl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh | bash'".to_string(),
- ));
- }
- InstallationEnvironment::Flatpak => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Running inside Flatpak. Please update via: flatpak update".to_string(),
- ));
- }
- InstallationEnvironment::Snap => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "Running inside Snap. Please update via: sudo snap refresh moviebox-tui"
- .to_string(),
- ));
- }
- InstallationEnvironment::ReadOnly => {
- return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
- "MovieBox-Tui binary is not user-writable. Please update via your system package manager.".to_string(),
- ));
- }
- InstallationEnvironment::DirectReplace | InstallationEnvironment::WindowsHelper => {}
+ if let Some(instruction) = env.upgrade_instruction() {
+ return Ok(SelfUpdateOutcome::RequiresManualUpgrade(
+ instruction.to_string(),
+ ));
}
let platform = TargetPlatform::current().ok_or_else(|| {
diff --git a/tests/addons_manifest.rs b/tests/addons_manifest.rs
index 2fc8f20..9696912 100644
--- a/tests/addons_manifest.rs
+++ b/tests/addons_manifest.rs
@@ -1,11 +1,12 @@
use moviebox_tui::models::MediaType;
use moviebox_tui::providers::addons::adapter::{
meta_detail_to_media_details, parse_audio_tracks, parse_codec, parse_quality,
- parse_season_episode, parse_size_bytes_from_text, stream_item_to_release,
+ parse_season_episode, stream_item_to_release,
};
use moviebox_tui::providers::addons::models::{
AddonManifest, InstalledAddon, MetaDetail, StreamBehaviorHints, StreamItem,
};
+use moviebox_tui::providers::models::parse_size_bytes;
use std::collections::HashMap;
#[test]
@@ -256,14 +257,8 @@ fn test_addon_token_and_audio_parsers() {
assert_eq!(parse_codec("H.264 AVC"), Some("AVC/x264".to_string()));
assert_eq!(parse_codec("Movie AV1 HDR"), Some("AV1".to_string()));
- assert_eq!(
- parse_size_bytes_from_text("Size: 1.15 GB"),
- Some(1_234_803_097)
- );
- assert_eq!(
- parse_size_bytes_from_text("File size: 850 MB"),
- Some(891_289_600)
- );
+ assert_eq!(parse_size_bytes("Size: 1.15 GB"), Some(1_234_803_097));
+ assert_eq!(parse_size_bytes("File size: 850 MB"), Some(891_289_600));
assert_eq!(
parse_audio_tracks("Hindi + English Dual Audio"),