Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
docs: streamline documentation clarity and harden automated test verification
Samir Hossainse27033bee2a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f1aac88..10088b4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,15 @@- Added fast-fail handling in `src/download.rs` when segment workers receive `200 OK`, avoiding wasteful retries and falling back immediately to single-stream downloading.- Buffered single-connection file writes in `src/download.rs` with a 256KB `tokio::io::BufWriter`, reducing syscall overhead during single-stream downloads.- Sanitized download failure notices via `DownloadError::user_message()` in `src/download.rs` and `src/tui/app/download.rs`, replacing raw error dumps and URL tokens with clean, actionable status messages.+### Changed+- **Documentation Overhaul & Clarity Streamlining**:+ - Overhauled all user and technical guides in `docs/` (`players.md`, `controls.md`, `tv-mode.md`, `config.md`, `addons-mode.md`, `providers.md`, `cross-platform.md`, `cache.md`, `downloads.md`), cutting redundant tables, eliminating dense run-on text walls, and standardizing on direct, beginner-accessible explanations.+ - Added complete environment variable documentation for `MOVIEBOX_LOG`, `MOVIEBOX_IMAGE_PROTOCOL`, `MOVIEBOX_CELL_SIZE`, and `NO_COLOR` in `docs/config.md`.+- **Automated Test Architecture Hardening**:+ - Replaced thread-shared `cargo test` execution with process-isolated `cargo nextest run` across testing rules in `.omp/AGENTS.md`.+ - Added hermetic local loopback server download tests in `src/download.rs` verifying custom authentication headers (`X-Auth-Token`, `User-Agent`, `Referer`), byte streaming, and progress callbacks.+ - Added deterministic CLI argument and header verification tests in `src/player.rs` for `mpv` and `VLC`.+ - Pruned tautological assertions and dead code (`step_header_aware_list`).## [0.1.23] - 2026-09-21### Fixeddiff --git a/docs/addons-mode.md b/docs/addons-mode.mdindex 4fd4f14..27b4700 100644--- a/docs/addons-mode.md+++ b/docs/addons-mode.md@@ -1,34 +1,31 @@-# Stremio Addons Provider (HTTP Addons)+# Stremio Addons-Stremio Addons are integrated directly into standard Streaming Mode as a first-class content provider alongside MovieBox, 4KHDHub, and BDIX mirrors. You can install any standard addon manifest URL to fetch metadata catalogs and aggregate direct HTTP/HTTPS media streams.+MovieBox-TUI supports Stremio HTTP addons. You can install standard addon manifest URLs to browse catalogs and stream media.-## Features+## Quick Start-- **Standard Protocol Support**: Compatibility with standard addon manifests (`/manifest.json`, `/catalog`, `/meta`, `/stream`).-- **Core Metadata Protection & Fast Resolution**: Cinemeta is pre-installed out-of-the-box as the core metadata provider (`[Core]`) and locked to prevent accidental removal. Metadata requests prioritize media type resolution with full support for alternate crew fields (`directors`, `writers`, `stars`).-- **Direct HTTP Stream Engine**: Automatically extracts and filters direct Cloudflare R2, PixelDrain, direct video CDN, and HubCloud/HubDrive HTTP streams.-- **Multi-Addon Concurrency**: Simultaneously queries all enabled stream addons and aggregates releases.-- **Quality, Resolution & Codec Parsing**: Ranks streams with high-contrast color-coded resolution badges (`4K UHD`, `1080p FHD`, `720p HD`, `SD`) and granular audio/video codec tags (`HDR`, `DV`, `ATMOS`, `5.1`, `HEVC`, `AV1`, `BluRay`, `WEB-DL`, `REMUX`), file size in GB/MB, and audio language tracks (e.g. `[Dual]`, `[Multi]`, `Hindi + English`).-- **Series & Episode Hierarchy**: Series are automatically organized into explicit `Seasons` and `Episodes` selector panes (including Season 0 Specials) with smooth horizontal navigation (`←`/`→`/`h`/`l`/`Tab`). Selecting any episode drives episode-specific stream requests (`/stream/series/:id:season:episode.json`).-- **Episode Stream Isolation**: Built-in token parsing (`parse_season_episode`) guarantees that only streams matching the selected season and episode are displayed, eliminating cross-episode stream mixing.-- **Direct Playback & Custom Headers**: Video stream headers (`behaviorHints.headers`) such as `Referer` and `User-Agent` are preserved and forwarded directly to external media players (`mpv`, `IINA`, `VLC`) and the multi-segment downloader.-- **Watch History & Progress Parity**: Full `/history` support for Addon streams with real-time `mpv` position tracking, scrub lines, and auto-resume.-- **High-Performance Caching**: Curated `/browse` catalogs are cached for `1 hour`, manifests for `24 hours`, and stream aggregations for `2 hours`.+- **Switch to Addons**: Press `Ctrl+P` on the home screen until `[Addons]` is selected.+- **Open Addon Manager**: Type `/config` or click `[Addons]` in the search bar.+- **Browse Catalogs**: Type `/browse` to view Top Movies, Top Series, and curated lists.+- **Search**: Type in the search bar to search titles across installed addons.-## Accessing Addon Streams+## Addon Manager-- `Ctrl+P`: Cycle providers in Streaming Mode to select **Addons**.-- `/config`: Open the **Addon Manager** directly when the active provider is `Addons`.-- `Tab` or click `[Addons]`: Open the **Addon Manager** popup directly from the search bar.-- `Ctrl+S`: Return smoothly to **MovieBox** provider.-- `/browse`: Browse curated addon catalogs (`Top Movies`, `Top Series`, `Top Rated Movies`, `Top Rated Series`).+The Addon Manager lets you add, enable, or remove addon manifests:-## Addon Manager+- **Toggle Addon**: Press `Enter` or `Space` on an addon to enable (`✓`) or disable it.+- **Add Addon**: Select `+ Add manifest URL`, paste the addon manifest URL, and press `Enter`.+- **Remove Addon**: Press `d` or `Delete` to remove an addon.+- **Core Addon (Cinemeta)**: Pre-installed for movie and series metadata. It cannot be deleted.++## Supported Streams++- Streams are parsed and labeled with quality tags (`4K`, `1080p`, `720p`), codec, and file size.+- Video stream headers (`User-Agent`, `Referer`) are automatically forwarded to external players (`mpv`, `VLC`, `IINA`) and download workers.+- Watch progress and episode resumption are saved automatically to `/history`.-- Interactive modal anchored in place of the landing search bar, displaying installed addons and activation state.-- `✓` / blank indent: Toggle addon enabled/disabled state (`Enter` or `Space`). Core provider remains protected with instant notice.-- `+ Add manifest URL`: Install any public HTTP addon manifest by URL.-- `d` or `Delete`: Remove the selected addon (protected for core metadata provider).-## Persistence+## Storage-Installed addons are atomically saved to `addons_config.json` inside the application config directory (`~/Library/Application Support/moviebox-tui/` on macOS, `~/.config/moviebox-tui/` on Linux, `%APPDATA%\moviebox-tui\` on Windows). If `addons_config.json` encounters corrupt data on disk, it is preserved and rotated to `addons_config.json.corrupt.{timestamp}` before initializing fallback defaults, preventing silent data loss.+Installed addons are saved to `addons_config.json` in your configuration directory:+- **Linux / macOS**: `~/.config/moviebox-tui/addons_config.json`+- **Windows**: `%APPDATA%\MovieBox-Tui\addons_config.json`diff --git a/docs/cache.md b/docs/cache.mdindex 4291759..687bd39 100644--- a/docs/cache.md+++ b/docs/cache.md@@ -1,45 +1,35 @@-# Cache+# Binary Cache & Storage-Disk caching lives in `cache.rs`; in-memory caches live in `AppState`.+MovieBox-TUI uses a disk-backed binary MessagePack caching engine to minimize network requests while maintaining fast startup times.-## Disk layout+## Cache Directory-```-<cache dir>/moviebox-tui/- <provider>/ moviebox, fourkhdhub, bdix_circleftp, bdix_dhakaflix, addons- search/<hash>_<page>.cache- details/details_<schema><hash>.cache- streams/<schema><hash>_<season>_<episode>.cache- images/<hash>.img- moviebox/- homepage/home_<tab>_<page>.cache- captions/captions_<hash>.cache- addons/- catalogs/catalog_<hash>.cache- manifests/manifest_<hash>.cache- streams/<hash>_<season>_<episode>.cache- tv_playlists/<md5>.m3u cached remote playlist snapshots-```+- **Linux / macOS / Termux**: `~/.cache/moviebox-tui/`+- **Windows**: `%LOCALAPPDATA%\MovieBox-Tui\cache\`++Override with the `MOVIEBOX_CACHE_DIR` environment variable.-The cache directory is `dirs::cache_dir()/moviebox-tui` (macOS-`~/Library/Caches`, Windows `%LOCALAPPDATA%`, Linux `$XDG_CACHE_HOME`).+## Binary Cache Architecture++Cache files use a structured MessagePack envelope preceded by a 4-byte magic signature (`MBXC`):++```text+[ 0x4D 0x42 0x58 0x43 ] [ MessagePack Encoded Envelope ]+```-## Properties+The envelope stores the creation timestamp (`u64`) alongside the serialized payload. On read, if the timestamp exceeds the item's TTL, the cache is invalidated and refetched.-- **Binary MessagePack Envelopes**: Cache entries are serialized with `rmp-serde` wrapped in a binary envelope starting with the 4-byte magic signature `MBC1` and an 8-byte TTL timestamp (`CacheEnvelope<T>`). Legacy JSON files are read and migrated on the fly.-- **Fast Table-Lookup Hex Hashing**: Cache file naming and key hashing in `md5_hex` uses static 16-byte lookup table encoding, eliminating dynamic `core::fmt::write` formatting allocations and speeding up digest encoding by 2.51x.-- **Provider namespacing**: Keys include `provider.cache_key()`, preventing collisions across sources.-- **Atomic writes**: Entries are written to a unique temp file (`path.with_extension("tmp-PID-STAMP")`) and atomically replaced (`durable_replace`), preventing truncated or corrupt files on unexpected exits.-- **Validation**: Empty search or stream results are never written or served from cache.-- **Purge**: Background cleanup runs at startup to delete entries older than 7 days. `/settings` → Maintenance → Clear Disk Cache recursively empties all cached provider responses, images, TV playlists, temporary subtitles across Android/Windows/Unix, resets in-memory LRU caches, and cancels in-flight background request tasks.+## Cache TTLs-## In-memory caches (AppState)+| Namespace | TTL | Description |+| :--- | :--- | :--- |+| `search` | 24 Hours | Search query results per provider |+| `details` | Dynamic (CloudFront TTL) | Subject details, cast, and signed streaming cookies (auto-adapts to upstream cookie expiration, min 1h, max 24h) |+| `posters` | 7 Days | Downloaded poster image buffers |+| `tv` | 24 Hours | Remote M3U playlist text snapshots |-- `image_cache` (30), `search_posters` (300), `failed_posters` (300),- `search_poster_protocols` (300), `preview_cache` (30): `lru::LruCache` for poster- images, negative lookup cache, and terminal image protocols; `stream_pool`:- resolved streams per subject.+## Durability & Safety-All disk access in async code is wrapped in `tokio::task::spawn_blocking` so the event-loop never blocks. Failures are logged (see [logging.md](logging.md)) and treated as-cache misses.+- **Atomic File Writes**: All cache entries are written to a temporary sidecar file (`.tmp.<pid>.<salt>`) and renamed atomically to destination, preventing corruption if interrupted.+- **Automatic Purging**: Stale cache entries older than 7 days are automatically removed by a background worker at startup.+- **Manual Purge**: Enter `/settings` → **Maintenance** → **Clear Disk Cache** to immediately wipe all cached files, images, and playlist snapshots.diff --git a/docs/config.md b/docs/config.mdindex 9bcf639..0809b19 100644--- a/docs/config.md+++ b/docs/config.md@@ -1,82 +1,55 @@# Configuration-## `config.json`--Written atomically under the config directory (`dirs::config_dir()/moviebox-tui/`;-macOS `~/Library/Application Support/moviebox-tui`, Linux `~/.config/moviebox-tui`).--| Field | Type | Meaning |-| :--- | :--- | :--- |-| `auto_update` | bool | Check for updates on startup (max once/hour). |-| `last_update_check` | u64 | Epoch seconds of the last update check. |-| `active_mode` | string | Last active mode (`streaming`, `tv`) restored on startup. |-| `active_provider` | string | Last provider (`moviebox`, `fourkhdhub`, `bdix_circleftp`, `bdix_dhakaflix`, `addons`). |-| `active_theme` | string | Theme name (`Mocha`, `TokyoNight`, `Nord`, `Dracula`, `Gruvbox`, `RosePine`). |-| `moviebox_enabled` | bool | Enable MovieBox streaming provider (`/settings` → Content Modes → Streaming Sources). |-| `fourkhdhub_enabled` | bool | Enable 4KHDHub streaming provider (`/settings` → Content Modes → Streaming Sources). |-| `bdix_circleftp_enabled` | bool | Enable CircleFTP mirror (`/settings` → Content Modes → Streaming Sources). |-| `bdix_dhakaflix_enabled` | bool | Enable DhakaFlix mirror (`/settings` → Content Modes → Streaming Sources). |-| `bdix_probed` | bool | Tracks if initial startup BDIX probe has executed. |-| `streaming_enabled` | bool | Enable Streaming Mode navigation in bottom dock (`/settings` → Content Modes). |-| `tv_enabled` | bool | Enable TV Mode navigation in bottom dock (`/settings` → Content Modes). |-| `addons_enabled` | bool | Enable Stremio Addons provider availability. |-| `default_player` | string or null | Preferred player: `mpv`, `iina`, `vlc`, `android`; absent/null until you choose one from the in-app picker. |-| `download_dir` | string or null | Custom directory for video and subtitle downloads (null uses OS default). |+MovieBox-TUI stores its settings in `config.json` inside your platform configuration directory.## Interactive Settings Hub (`/settings`)-All settings in `config.json` can be configured interactively inside the application by typing `/settings` into the search bar.--- **General**: Toggle automatic update checks, choose default media player (`mpv`, `VLC`, `IINA`, `Android`), and edit download folder path.-- **Content Modes**: Toggle Streaming Mode, open the Streaming Sources selector (to enable/disable MovieBox, 4KHDHub, CircleFTP, DhakaFlix), and toggle Live TV.-- **Appearance**: Open the visual theme swatch picker to select among 6 built-in color themes.-- **Maintenance**: Query GitHub for release updates, trigger a manual local network BDIX re-probe, purge disk cache, clear watch history, and open the GitHub repository.-## Persisted configuration (`config.json`)--The central configuration file is located at `~/.config/moviebox-tui/config.json` (or `%APPDATA%\MovieBox-Tui\config.json` on Windows). In addition to settings toggled via `/settings`, custom player binary paths can be directly set here:--```json-{- "default_player": "vlc",- "vlc_path": "D:\\PortableApps\\VLC\\vlc.exe",- "mpv_path": "C:\\Program Files\\mpv\\mpv.exe",- "iina_path": "/Applications/IINA.app/Contents/MacOS/iina-cli"-}-```--## Other persisted files-- `addons_config.json` — list of installed HTTP addons in the config directory (see [addons-mode.md](addons-mode.md)).-- `tv_config.json` — list of M3U playlist sources in the config directory (see [tv-mode.md](tv-mode.md)).-- `history.json` — watch history in the system data directory (`dirs::data_dir()/moviebox-tui/`).-- `favorites.json`: starred titles in the system data directory. Independent of `history.json`; clearing watch history or cache never touches it.-- `playback/` — temporary playback states in the system data directory for resilient progress tracking.-- `scripts/` — bundled player scripts (`moviebox_tracker.lua`) in the system data directory.-- `iptv_cache/` — legacy TV image cache directory that `ClearCache` still removes.--## Environment variables--| Variable | Purpose |+Enter `/settings` or press `s` on the Home screen to configure options interactively:++- **General**: Toggle automatic update checks, select default media player (`mpv`, `VLC`, `IINA`, `Android`), and customize download directory.+- **Content Modes**: Toggle Streaming Mode, enable or disable specific streaming providers (MovieBox, 4KHDHub, CircleFTP, DhakaFlix), and toggle Live TV Mode.+- **Appearance**: Select among 6 color themes with live preview.+- **Maintenance**: Check for updates, re-test local BDIX network connectivity, clear disk cache, clear watch history, and open the GitHub repository.++## Configuration File Paths++- **Linux / macOS / Termux**: `~/.config/moviebox-tui/config.json`+- **Windows**: `%APPDATA%\MovieBox-Tui\config.json`++## Configuration Options (`config.json`)++| Field | Type | Default | Description |+| :--- | :--- | :--- | :--- |+| `auto_update` | `bool` | `true` | Check for application updates on launch |+| `default_player` | `string` | `"mpv"` | Default player (`"mpv"`, `"vlc"`, `"iina"`, `"android"`) |+| `download_dir` | `string?` | `None` | Custom download directory (defaults to `~/Downloads/MovieBox-TUI`) |+| `streaming_enabled` | `bool` | `true` | Enable on-demand streaming |+| `tv_enabled` | `bool` | `true` | Enable live TV mode |+| `addons_enabled` | `bool` | `false` | Enable Stremio Addons provider |+| `moviebox_enabled` | `bool` | `true` | Enable MovieBox streaming provider |+| `fourkhdhub_enabled` | `bool` | `true` | Enable 4KHDHub streaming provider |+| `dramachi_enabled` | `bool` | `true` | Enable Dramachi streaming provider |+| `bdix_circleftp_enabled` | `bool` | `false` | Enable CircleFTP (BDIX) provider |+| `bdix_dhakaflix_enabled` | `bool` | `false` | Enable DhakaFlix (BDIX) provider |+| `theme` | `string` | `"TokyoNight"` | Active color theme |+| `mpv_path` | `string?` | `None` | Custom executable path for `mpv` |+| `vlc_path` | `string?` | `None` | Custom executable path for `VLC` |+| `iina_path` | `string?` | `None` | Custom executable path for `IINA` (macOS) |++## Environment Variables++| Variable | Description || :--- | :--- |-| `MOVIEBOX_LOG` | Log level: `off`, `error`, `warn`, `info`, `debug`, `trace`. See [logging.md](logging.md). |-| `MOVIEBOX_PLAYER` | Preferred player (overrides `default_player`). |-| `MOVIEBOX_MPV_PATH` | Custom mpv executable. |-| `MOVIEBOX_VLC_PATH` | Custom VLC executable. |-| `MOVIEBOX_IINA_PATH` | Custom IINA/iina-cli executable. |-| `MOVIEBOX_FOURKHDHUB_URL` | Override the 4KHDHub base URL. |-| `MOVIEBOX_THEME` | Force a theme (e.g. `Mocha`, `Latte`, `Macchiato`, `Frappe`, `Nord`, `TokyoNight`, `Dracula`, `Gruvbox`, `RosePine`). When unset and no saved theme exists, the app auto-detects: `NO_COLOR` wins, truecolor terminals get full palettes, 256-color terminals get quantized palettes, and the OSC 11 background query picks light/dark variants with WCAG AA contrast. |-| `MOVIEBOX_NO_IMAGE` | Disable poster image queries (set to `1` or `true`). |-| `MOVIEBOX_IMAGE_PROTOCOL` | Override image protocol (`kitty`, `sixel`, `iterm2`, or `none`/`off`). Required when running inside `tmux` with an outer terminal that is not auto-detected as graphics-capable (Ghostty, Kitty, WezTerm, iTerm2, foot, Alacritty). Example: `MOVIEBOX_IMAGE_PROTOCOL=kitty moviebox-tui`. |-| `MOVIEBOX_CELL_SIZE` | Override terminal cell size as `WxH` (e.g. `10x20`) for poster scaling. |--### tmux poster passthrough--Inside a `tmux` session, poster images are automatically enabled when the outer-terminal is Ghostty, Kitty, WezTerm, iTerm2, foot, or Alacritty. `tmux` must-have `allow-passthrough` enabled (set automatically by the app on supported-terminals). For any other outer terminal, set-`MOVIEBOX_IMAGE_PROTOCOL=kitty` (or `sixel`/`iterm2`) to force passthrough.--## CLI--- `moviebox-tui --help` and `moviebox-tui -h` print the help manual and exit.-- `moviebox-tui --version`, `moviebox-tui -v`, and `moviebox-tui -V` print the version and exit.+| `MOVIEBOX_PLAYER` | Force media player (`"mpv"`, `"vlc"`, `"iina"`, `"android"`) |+| `MOVIEBOX_MPV_PATH` | Custom executable path for `mpv` |+| `MOVIEBOX_VLC_PATH` | Custom executable path for `VLC` |+| `MOVIEBOX_IINA_PATH` | Custom executable path for `IINA` (macOS) |+| `MOVIEBOX_CONFIG_DIR` | Custom directory for `config.json` |+| `MOVIEBOX_DATA_DIR` | Custom directory for watch history and favorites |+| `MOVIEBOX_CACHE_DIR` | Custom directory for disk cache |+| `MOVIEBOX_THEME` | Override active theme on launch (e.g. `"TokyoNight"`, `"Dracula"`) |+| `MOVIEBOX_LOG` | Logging level (`"error"`, `"warn"`, `"info"`, `"debug"`, `"trace"`) |+| `MOVIEBOX_NO_IMAGE` | Set to `"1"` or `"true"` to disable terminal image previews |+| `MOVIEBOX_IMAGE_PROTOCOL` | Force image protocol (`"kitty"`, `"sixel"`, `"iterm2"`, or `"off"`) |+| `MOVIEBOX_CELL_SIZE` | Override font cell size for image scaling (e.g. `"10x20"`) |+| `NO_COLOR` | Force high-contrast monochrome mode |diff --git a/docs/controls.md b/docs/controls.mdindex 4f432aa..68bfa27 100644--- a/docs/controls.md+++ b/docs/controls.md@@ -1,158 +1,72 @@# Controls & Shortcuts-MovieBox-TUI is designed for fast keyboard navigation with complete mouse support throughout the interface. You can press `?` anywhere inside the application to open the mode-aware interactive help dialog.+Press `?` anywhere inside the application to open the interactive help dialog.## Global Shortcuts| Key | Action || :--- | :--- |-| **`↑` / `↓` / `k` / `j`** | Navigate lists, search results, or move cursor up/down |-| **`←` / `→` / `h` / `l`** | Move text input cursor, step wide grid columns, or switch Details panes (Audio/Seasons/Episodes/Streams) |-| **`Home` / `End` / `g` / `G`** | Jump to start / end of search results (Home screen only), or move cursor to beginning / end of input line |-| **`PageUp` / `PageDown`** | Scroll search results, lists, help overlay, and modal pickers by visible page height |-| **`Enter`** | Open, play, or confirm the selected item |-| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` or Home Continue Watching deck |-| **`Esc`** | Dismiss active notifications, focus search input (when results present), dismiss popup dialog, or return to landing |-| **`Tab` / `Shift+Tab`** | Auto-complete suggestion (Tab); cycle landing deck tabs (Resume / Favorites); switch details panes; toggle dialog buttons |-| **`Backspace`** | Delete character before cursor, or return focus to search bar from results |-| **`d` / `Delete`** | Delete character at cursor in text inputs; remove selected entry in `/history`, Home Continue Watching deck, or TV/Addon managers |-| **`Ctrl+U`** | Clear entire input line (Search, TV URL, Addon URL) |-| **`Ctrl+W`** | Delete backward word in text inputs |-| **`c`** | Clear active search query and return to landing screen (Normal mode) |-| **`x` / `X`** | Cancel active download and preserve partial `.part` data |-| **`Ctrl+S`** | Switch to standard **Streaming Mode** |-| **`Ctrl+T`** | Toggle / switch to **TV Mode** |-| **`?`** | Open interactive in-app help menu |-| **`Ctrl+C` / `q`** | Quit application and restore terminal |--## Text Input & Cursor Editing--Text editing across Search, TV Playlist Manager, and Addon Manager uses a unified grapheme-safe input engine:--| Key | Action |-| :--- | :--- |-| **`Left` / `Right`** | Move text cursor one grapheme cluster left or right |-| **`Home` / `End`** | Jump cursor directly to the beginning or end of the input line |-| **`Backspace`** | Delete the grapheme cluster immediately before the cursor |-| **`Delete`** | Delete the grapheme cluster at the cursor position |-| **`Ctrl+W`** | Delete the preceding word (up to space or punctuation delimiter) |-| **`Ctrl+U`** | Clear the entire input buffer |-| **`Tab`** | Auto-complete active search suggestion or slash command |-| **`Enter`** | Submit search query, save TV playlist URL/path, or verify and install Addon manifest |-| **`Esc`** | Cancel input, dismiss input prompt, or clear search buffer |--## Modal Dialogs & Pickers--All popup dialogs (Theme picker, Browse categories, Provider menu, Settings Media Player picker, TV Manager, Addon Manager, Download Confirmation) support standard keyboard controls:--- **`↑` / `↓` / `k` / `j`**: Move selection up / down by one item (vim keys `k`/`j` supported across all pickers: themes, browse categories, providers, players, TV manager, and addon manager).-- **`Home` / `End`**: Jump immediately to the first or last item in the list.-- **`PageUp` / `PageDown`**: Step up or down by 5 items (supported in provider menu, player picker, TV manager, and addon manager).-- **`Enter` / `Space`**: Confirm selection, activate entry, or submit dialog.-- **`Esc`**: Dismiss popup dialog without applying changes.-- **Download Confirmation Dialog**:- - **`y` / `Y`**: Confirm and begin download immediately without navigating buttons.- - **`n` / `N`**: Cancel and dismiss confirmation dialog immediately.- - **`h` / `l`**: Switch focus between `[ Download ]` (`h`) and `[ Cancel ]` (`l`).- - **`Tab` / `Shift+Tab` / `BackTab`**: Toggle active selection between `[ Download ]` and `[ Cancel ]`.- - **`Left` / `Right`**: Switch between `[ Download ]` and `[ Cancel ]`.- - **`Enter`**: Confirm the currently focused action.- - **`Esc`**: Cancel and close the confirmation dialog.-- **Sources Picker (Stream Sources)**:- - **`↑` / `↓` / `k` / `j`**: Navigate available stream sources.- - **`Enter` / `Space`**: Select highlighted stream source.- - **`Esc`**: Dismiss sources picker.-- **Subtitle Picker**:- - **`↑` / `↓` / `k` / `j`**: Navigate subtitle language options.- - **`Enter`**: Select highlighted subtitle track.- - **`Esc`**: Dismiss subtitle picker.-- **Overview / Synopsis Modal**:- - **`i`** (or click header card / click footer `[i] Info`): Open full Overview / Synopsis modal for current movie, series, or selected episode.- - **`↑` / `↓` / `k` / `j` / `PageUp` / `PageDown`**: Scroll synopsis text.- - **`Esc` / `Enter` / `q` / `i` / Click outside**: Dismiss overview modal.-## Mode-Specific Controls--### Streaming Mode-- **`Ctrl+P`**: Cycle content providers (`MovieBox` → `4KHDHub` → `BDIX` → `Addons`) and return to Home search.-- **`←` / `→` / `h` / `l` / `Tab` / `Shift+Tab`**: Switch Details screen selector panes (Audio Languages, Seasons, Episodes, Streams).-- **`i`**: Open full Overview / Synopsis modal for current movie, series, or selected episode.-- **`Enter` / `p` / `P`**: Play selected stream or open selected title.-- **`d`**: Download current episode or full season batch.-- **`r`**: Refresh search results / stream list.-- **`f`**: Favorite / unfavorite the selected title (Home & Details screens).-- **Settings Screen**:- - **`d` / `D`**: Reset custom download directory to application default (when Directory row is highlighted).-- **`/browse`**: Open curated browse categories (Trending, Popular, Top Rated, etc.).-- **`/history`**: Open watch history (`Space` or `P` to instantly resume recorded episode/movie).-- **`/favorites`**: Open your starred titles.-- **`/clear`**: Clear active search query and return to landing.--### Live TV Mode-- **`Enter`**: Play selected TV channel immediately with default player.-- **`r`**: Reload all active M3U playlist sources.-- **`/list`**: Show all loaded channels.-### Stremio Addons Provider-- **`/config`**: Open the Addon Manager directly when the active provider is `Addons`.-- **`Enter`**: Select title or play resolved stream.-- **`d`**: Download HTTP stream release.-- **`r`**: Refresh addon catalog search results.-- **`f`**: Favorite / unfavorite the selected title (Home & Details screens).-## Mouse Controls--| Action | Result |-| :--- | :--- |-| **Click provider badge** | Open anchored provider selection menu; click provider to switch directly |-| **Click search bar** | Enter search input mode |-| **Click search result row** | Select item and load preview; click again to open full details |-| **Click landing deck tab header** | Switch between Resume and Favorites tabs |-| **`Click [x] Cancel on download bar`** | Cancel active download |-| **Click Resume row (landing)** | Select an in-progress title; click again to resume playback with auto-play |-| **Click Favorites row (landing)** | Select a starred title; click again to open details |-| **Click "+N more • /history" or "+N more • /favorites"** | Open the full watch history or favorites list |-| **Click header metadata card** | Open full Overview / Synopsis modal for movie or series |-| **Click footer "[i] Info"** | Open full Overview / Synopsis modal for current selection (movie, series, or episode) |-| **Click audio / season / episode / stream** | Switch audio language, change season, or select episode; click a specific stream row to play; click empty stream pane space to focus without playing |-| **Click footer buttons** | Switch provider / mode, open help (`[?]`), or quit (`[q]`) |-| **Click modal buttons** | Choose a theme, subtitles, player, or confirm actions |-| **Click outside a modal** | Dismiss popup dialog |+| **`↑` / `↓` / `k` / `j`** | Move selection up / down |+| **`←` / `→` / `h` / `l`** | Switch Details panes, step grid columns, or move input cursor |+| **`Home` / `End` / `g` / `G`** | Jump to start / end of lists or text inputs |+| **`PageUp` / `PageDown`** | Scroll lists by one page height |+| **`Enter`** | Play, open, or confirm selected item |+| **`Space` / `P`** | Direct resume playback from Home Continue Watching or `/history` |+| **`Esc`** | Dismiss dialogs, close popups, or cancel search query |+| **`Tab` / `Shift+Tab`** | Cycle landing tabs (Resume / Favorites), switch Details panes, or auto-complete |+| **`d` / `Delete`** | Delete selected entry in `/history`, playlist manager, or addon manager |+| **`c`** | Clear active search query and return to landing (Normal mode) |+| **`x` / `X`** | Cancel active download |+| **`Ctrl+S`** | Switch to **Streaming Mode** |+| **`Ctrl+T`** | Switch to **TV Mode** |+| **`?`** | Open help overlay |+| **`Ctrl+C` / `q`** | Quit application |++## Text Editing (Search & Dialog Prompts)++- **`Left` / `Right`**: Move cursor one character.+- **`Home` / `End`**: Jump to start / end of input.+- **`Backspace` / `Delete`**: Delete character before / at cursor.+- **`Ctrl+W`**: Delete preceding word.+- **`Ctrl+U`**: Clear entire input line.+- **`Tab`**: Auto-complete suggestion or command.+- **`Enter`**: Submit input.+- **`Esc`**: Cancel input prompt.++## Dialog & Modal Controls++All popups (Themes, Providers, Players, TV Manager, Addon Manager, Download Confirmation) share standard navigation:++- **`↑` / `↓` / `k` / `j`**: Navigate choices.+- **`Home` / `End`**: Jump to first / last item.+- **`Enter`**: Confirm selection.+- **`Esc`**: Dismiss popup without applying changes.+- **Download Confirmation**:+ - `y` / `Y`: Confirm download immediately.+ - `n` / `N`: Cancel download immediately.+ - `Left` / `Right` / `Tab`: Toggle between `[ Download ]` and `[ Cancel ]`.+- **TV & Addon Managers**:+ - `r`: Reload playlist sources or addon catalogs.+ - `d` / `Delete`: Remove selected source.## Slash Commands-Type these commands directly into the search bar:+Type `/` in the search bar on the Home screen to trigger slash commands:-| Command | Applicable Mode | Action |+| Command | Mode | Action || :--- | :--- | :--- |-| `/settings` | All | Open interactive Settings & Preferences Hub |-| `/config` | Contextual | Open playlist manager in TV mode, or Addon Manager in Addons provider (prompts `/settings` on MovieBox/4KHDHub) |-| `/browse` | Streaming | Browse curated views (Trending, Popular) or Addon catalogs (Top Movies, Top Series) |-| `/history` | Streaming | View watch history with latest progress |-| `/favorites` | Streaming | View all starred titles |-| `/clear` | All | Clear search results and return to landing |-| `/help` | All | Open interactive keybinding help menu (alias `/?`) |-| `/list` | TV | View live TV channels |-| `/exit` | All | Exit application and return to shell (aliases `/quit`, `/q`) |--## Help Menu Overlay+| **`/settings`** | All | Open Settings Hub |+| **`/config`** | Contextual | Open TV Playlist Manager (TV mode) or Addon Manager (Addons provider) |+| **`/browse`** | Streaming | Browse curated views (Trending, Popular, Addon catalogs) |+| **`/history`** | Streaming | View watch history and resume playback |+| **`/favorites`** | Streaming | View starred titles |+| **`/list`** | TV Mode | View all loaded live TV channels |+| **`/clear`** | All | Reset search input and results |+| **`/help`** | All | Open interactive help dialog |+| **`/exit`** | All | Quit application |-- Open with `?`; close with `?`, `Esc`, or `q`.-- `↑`/`↓`, `PageUp`/`PageDown`, and the mouse wheel scroll long content.-- Other keys are ignored while help is open.--## Update Notification & Self-Update Modals--When a new release is detected, a centered modal card displays the version comparison, environment instructions, release highlights, and quick actions:--- `u` / `U`: Download and install update immediately (direct binary replacement platforms).-- `b` / `B`: Copy Homebrew upgrade command (`brew upgrade moviebox-tui`) to clipboard with status toast on Homebrew-managed installations.-- `s` / `S`: Copy Scoop upgrade command (`scoop update moviebox-tui`) to clipboard with status toast on Scoop-managed installations.-- `o` / `O`: Open GitHub release notes in the system browser.-- `Esc`: Dismiss modal and return to previous screen.-- The notification modal formats release notes into clean, indented category sections (`[Added]`, `[Fixed]`) with bold feature titles and bullet items, docked with inline quick actions (`[u] Update ──── [o] GitHub`).-- During self-update (`u`), a focused progress card displays an active spinner with the active stage (`Downloading release`, `Verifying checksum`, `Installing binary`) anchored cleanly at the search bar position.-- Modal presentation is deferred while actively typing in the search bar (`InputMode::Editing`) to prevent input hijacking. During update installation, keyboard and mouse inputs are locked while the progress modal is displayed.-## Wide-Terminal Grid+## Mouse Controls-On terminals at least 110 columns wide, search results render in two-columns (three at 160+). `↑`/`↓` move one visual row, `←`/`→` move one-item, and clicks map through column bounds. Narrower terminals keep the-classic single-column list where `←`/`→` jump a full page.+- **Left Click**: Select and activate search cards, tabs, buttons, or playlist entries.+- **Scroll Wheel**: Scroll search results, seasons, episodes, and modal dialogs.+- **Click Outside**: Click anywhere outside an active dialog to dismiss it.diff --git a/docs/cross-platform.md b/docs/cross-platform.mdindex 2b11b5f..2e71d7d 100644--- a/docs/cross-platform.md+++ b/docs/cross-platform.md@@ -1,90 +1,33 @@-# Cross-platform+# Cross-Platform Support-Build targets: macOS, Linux, Windows, and Android (Termux). The codebase uses-`crossterm`, `ratatui`, and focused platform integrations.-"Build target" does not mean every runtime integration is verified on every-device. Desktop builds are covered by CI; external players and Termux require-the release checks in [`release-checklist.md`](release-checklist.md).+MovieBox-TUI runs on **macOS**, **Linux**, **Windows**, and **Android (Termux)**.-## OS notes+## Supported Operating Systems-| Platform | Notes |-| :--- | :--- |-| macOS | IINA preferred player (via the installed IINA `iina-cli`); VLC/mpv `.app` paths detected. `process_group(0)` on spawn. |-| Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%` (filtering out 0-byte Windows Store `WindowsApps` execution alias stubs); path-safe file stems; environment variable expansion (`%USERPROFILE%`, `%SystemRoot%`, `%LOCALAPPDATA%`) for `REG_EXPAND_SZ` registry queries; verbatim `\\?\` UNC prefix normalization during download directory containment checks; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries; handle-safe atomic download replacement (dropping file handles before renames); background process spawning (registry queries and yt-dlp downloader) hardened with `CREATE_NO_WINDOW` (`0x08000000`) and isolated with `CREATE_NEW_PROCESS_GROUP` (`0x00000200`) so terminal interrupts do not kill active downloads; updater helper process spawned with `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` so console exit does not abort in-flight binary replacement; full legacy Windows console (`conhost.exe` on Windows 8.1 and earlier) compatibility via crossterm WinAPI fallback by eliminating unsupported underline color sequences. |-| Linux | Flatpak mpv/VLC supported (`flatpak run …`) with `@@` file forwarding markers for local files; xdg data/cache dirs. Linux ARM64 binaries (`MovieBox_Linux_arm64.tar.gz`) are fully static musl executables linked with 64KB ELF segment alignment (`-Wl,-z,max-page-size=65536`) for compatibility across 4KB, 16KB, and 64KB page kernels. |-| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools`. Detection prioritizes the native Android player bridge ahead of headless CLI players, automatically falls back from `termux-am` to `termux-open` if `am.sock` is unavailable, and strictly gates system `am` probes behind `target_os = "android"`. Subtitles are retained in `~/storage/downloads/moviebox_subs` during playback and cleaned up on a 24-hour retention schedule rather than immediate process exit. Download storage directory prefers `~/storage/downloads` when running inside verified Termux environments. |+### macOS+- **Media Players**: `IINA` (CLI + app bundle), `mpv`, and `VLC`.+- **Binaries**: Shipped as universal binaries supporting both Apple Silicon (`arm64`) and Intel (`x86_64`).-## Terminal capabilities+### Linux+- **Media Players**: Native `mpv`, `VLC`, or Flatpaks (`flatpak run io.mpv.Mpv`).+- **Binaries**: Static Musl executables compatible with glibc and musl systems across x86_64 and aarch64.-The app probes the terminal at startup via `ratatui_image` (400ms cap,-off the UI thread). Non-graphics terminals (e.g. macOS `Apple_Terminal`,-legacy Windows `conhost`, and `TERM=dumb/linux/cygwin`) are skipped to-prevent escape sequence probe leakage (`Gi=31...`):+### Windows+- **Media Players**: Discovers `mpv.exe` and `vlc.exe` via WinGet, Scoop, Program Files, and the Windows Registry.+- **Process Safety**: Processes launch with `CREATE_NO_WINDOW` and independent process groups so terminal signals do not terminate playback or downloads.+- **Path Compatibility**: Supports Windows drive letters (`C:\...`), backslashes (`\`), forward slashes (`/`), and UNC paths.-- **Poster rendering**: Sixel, Kitty, and iTerm2 protocols where the probe- detects them. Terminals that report kitty/sixel capability but no cell- size (Windows Terminal sixel, iTerm2 over SSH) are salvaged with default- cell metrics. On terminals lacking graphics support (e.g. standard Windows- PowerShell, legacy console host, macOS Terminal.app), search result cards- and details screens display standardized bordered containers with centered `No Art`- indicators, ensuring consistent layout geometry without confusing broken blocks.- Poster queries are automatically gated behind `has_active_modal()` to prevent graphic bleed- through modal popups and overlays. Inside `tmux` sessions, poster graphics passthrough is- automatically enabled when running under Ghostty, Kitty, WezTerm, iTerm2, foot, or Alacritty.- `MOVIEBOX_NO_IMAGE=1` disables queries; `MOVIEBOX_IMAGE_PROTOCOL` forces a protocol (`kitty`, `sixel`, `iterm2`);- `MOVIEBOX_CELL_SIZE=WxH` overrides metrics.-- **Colors & Themes**: With no explicit theme, `NO_COLOR` wins, then truecolor RGB- (auto-detected across Ghostty, Kitty, WezTerm, iTerm2, Alacritty, Foot, Windows Terminal,- Hyper, Tabby, Warp, VSCode, Konsole, xfce4-terminal, GNOME Terminal, and Tilix; enabled by- default on Windows Terminal via `WT_SESSION`), quantized 256-color palettes for strict terminals,- fallback palette (`Theme::fallback`) using crisp cyan accents; an OSC 11 background query- picks light/dark variants. Light mode themes (including Catppuccin Latte) are tuned for- WCAG AA compliance, ensuring high-contrast readability across light terminal backgrounds.- Modal pickers feature clean transparent border backdrops, minimum 7-row breathing room, and background- selection suppression to isolate dialog focus. An explicit `MOVIEBOX_THEME` or saved theme- always wins over autodetection.-- **Keyboard & Cursor**: The kitty keyboard protocol (disambiguated escapes, event- types) is requested at start and popped on exit (gated behind `!is_termux_environment()`- to prevent escape sequence noise on mobile touch keyboards); unsupported terminals- ignore it. Real input cursor styling (`SetCursorStyle::SteadyBar`) activates- during text editing modes on supported terminals.-- **Loading & Progress Indicators**: Unicode Braille loading spinners (`⠋ ⠙ ⠹ ...`)- render during search, metadata discovery, and stream fetching, falling back to- clean text indicators (`..`) on basic/dumb terminals.-- **Window Titles**: Contextual terminal emulator window titles are emitted dynamically- reflecting active navigation mode and title (`MovieBox-Tui — Streaming`,- `MovieBox-Tui — Live TV`, `MovieBox-Tui — Addons`, `MovieBox-Tui — {Title}`).-- **Terminal classification**: `TERM=dumb`/`linux` fall back to a basic UI.-- Focus events re-render in place without clearing; results render in two- columns from 110 columns wide (three from 160).-- **Responsive Installers**: Both Unix (`install.sh`) and Windows (`install.ps1`) installation scripts query terminal width dynamically (`tput cols` / `stty size` / `$Host.UI.RawUI.WindowSize.Width`), adapting the header across wide (72-column block art), compact (31-column 2-line half-block art for mobile/Termux portrait mode), and minimal (text-only) tiers with dynamic horizontal centering to prevent line wrapping.-## Network & TLS portability+### Android (Termux)+- **Media Players**: Uses Android intent dispatchers (`termux-open` / `am start`) to stream directly to external video players (VLC for Android, Just Player, MX Player, MPV Android).+- **Prerequisites**: Run `pkg install -y termux-tools` in Termux.+- **Subtitles**: Subtitles are saved to shared storage (`~/storage/downloads/moviebox_subs`) for player access.+- **DNS**: Built-in DNS resolver queries public resolvers (Cloudflare, Google, Quad9) without requiring root or Android JNI.-- **TLS Engine**: Uses `rustls` with embedded Mozilla roots (`webpki-roots`) across all targets (macOS, Linux, Windows, Android/Termux). The release binary has no OpenSSL runtime dependency; the `ring` cryptography backend is compiled into the binary by the platform build toolchain.-- **DNS Resolution**: Pure-Rust resolver (hickory) on all platforms: it reads the OS- configuration first (`/etc/resolv.conf`, registry on Windows) and falls back to- embedded public resolvers (Cloudflare `1.1.1.1`, Google `8.8.8.8`, Quad9 `9.9.9.9`)- when no system configuration exists — as on Android/Termux or minimal containers.- No JNI or `ndk-context` required.-## In-App Self-Update Engine+## Terminal Compatibility-MovieBox-TUI embeds an in-app binary upgrade engine (`src/updater/`) with cross-platform environment detection and deterministic fallback:+MovieBox-TUI automatically adapts to your terminal emulator:-- **Direct Replacement**: Supported on Linux (`x86_64`, `aarch64`), macOS (Universal binary), and Windows (`x64`, `arm64`). Downloaded release archives are validated against SHA-256 checksums, unpacked to temporary staging files, and swapped atomically with rollback on failure.-- **Windows Helper Script**: On Windows, because running executables are locked by the OS, an external transient batch helper (`moviebox_update_helper.bat`) waits for the parent process PID to terminate, attempts atomic binary replacement with a 5-iteration retry loop (to tolerate antivirus/SmartScreen file locks), restarts the application, and self-deletes.-- **Homebrew Managed Environments**: Automatically detected via path markers (`/Cellar/`, `/opt/homebrew/`, `/usr/local/Cellar/`, `/home/linuxbrew/`). In-app binary overwrites are disabled to protect package manager integrity; the update modal displays Homebrew instructions (`brew upgrade moviebox-tui`) with a dedicated `[b]` shortcut.-- **Scoop Managed Environments**: Automatically detected via path markers (`/scoop/apps/`, `\scoop\apps\`, `/scoop/shims/`, `\scoop\shims\`). In-app binary overwrites are disabled to protect package manager integrity; the update modal displays Scoop instructions (`scoop update moviebox-tui`) with a dedicated `[s]` shortcut.-- **Android / Termux**: Protects Termux environments from overwriting bionic libc binaries with incompatible Linux glibc binaries. Instructs users to re-run the universal installer script (`curl -fsSL ... | bash`).-- **Deterministic GitHub Asset Fallback**: When GitHub API requests are unauthenticated or rate-limited (status 403), tag resolution falls back to HTTP redirects, and asset download URLs are computed deterministically from release tags rather than failing update operations.-- **Input Isolation & Event Locking**: Update notifications defer blocking modal presentation while typing in search mode (`InputMode::Editing`) to prevent keystroke hijacking. During in-flight update execution (`is_updating`), all keyboard and mouse events are locked while displaying an active Braille progress spinner.--## Things to verify per release--- Player launch on each OS (mpv/VLC/IINA/Android intent) — window sizing, subtitles,- headers.-- Poster rendering across Sixel (Windows Terminal, foot), Kitty, iTerm2, and basic- non-graphics terminals.-- TV mode with a sample M3U playlist (URL and local file).-- Stremio Addons provider with sample HTTP addon manifests (Cinemeta, torrent/stream addons).-- Termux: on-device check that Play opens the Android chooser and the stream plays.+- **Images & Posters**: Automatically detects Kitty graphics, Sixel, and iTerm2 protocols (Ghostty, Kitty, WezTerm, iTerm2, foot, Alacritty). Terminals without image support display clean text containers. Disable with `MOVIEBOX_NO_IMAGE=1`.+- **Colors & Themes**: Auto-detects 24-bit TrueColor, 256-color palettes, and high-contrast monochrome mode (`NO_COLOR=1`).+- **Keyboard Navigation**: Uses the Kitty keyboard protocol on supported emulators. Mobile Termux keyboards use standard ANSI input to avoid character garbage.+- **Window Titles**: Automatically updates terminal window titles based on current title and screen mode.diff --git a/docs/downloads.md b/docs/downloads.mdindex 8793864..e764d9f 100644--- a/docs/downloads.md+++ b/docs/downloads.md@@ -1,66 +1,32 @@-# Downloads+# Downloader-The download engine in `download.rs` streams a video URL to disk with resume, ranges,-and optional segmentation. Orchestration lives in `app/download.rs`.+MovieBox-TUI includes a multi-segment HTTP chunked downloader supporting pause, resume, and authentication header forwarding.-## How it works+## Overview-- Single-episode downloads write to `<dest>.part` plus a `<dest>.part.json` metadata- sidecar (etag, last-modified, total size, segment count).-- **Resume**: on a retry, the engine checks what is already in the `.part` file and- continues from there using `Range` requests.-- **Segmentation**: files above a size threshold can be downloaded in parallel- segments (up to a capped count), then stitched.-- **I/O Aggregation**: Download workers (both multi-segment workers and single-connection fallback) are buffered with a 256KB `tokio::io::BufWriter`, aggregating incoming HTTP response chunks into sequential disk writes and minimizing filesystem syscall overhead.-- **Client Deadlines**: The media download client uses `streaming_client_builder()` without a global request timeout, allowing multi-gigabyte files to transfer continuously while enforcing a 15-second connect timeout and 30-second per-chunk stall detection.-- **Retries**: a failed attempt is retried a limited number of times; 30s idle-- **Cancel**: an `AtomicBool` cancel flag pauses/resumes cleanly, preserving the- partial file for a later resume.-- **User-Agent**: the download HTTP client inherits the active provider's mobile `User-Agent`- to prevent CDN stream rejections when downloading media segments.-- **Stream Engines**:- - **Progressive Streams** (CircleFTP, DhakaFlix, 4KHDHub, Addons): Handled directly by the native Rust multi-segment range downloader, splitting files into parallel chunks with `.part` state tracking.- - **MPEG-DASH Streams** (MovieBox): Multi-track segmented audio/video streams (`index.mpd`) requiring CloudFront cookie authentication. Downloaded via `yt-dlp` with automatic authentication header forwarding (`Cookie`, `Referer`, `User-Agent`), real-time progress parsing, and track multiplexing into `.mp4`. On Windows, background `yt-dlp` processes are spawned with `CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP` to isolate transfers from terminal interrupt signals.+- **Storage Location**: Defaults to `~/Downloads/MovieBox-TUI/`. Configurable via `/settings` (General → Download Folder).+- **Multi-Segment Engine**: Files are partitioned into concurrent byte ranges using HTTP RFC 7233 `Range: bytes=X-Y` requests.+- **Single-Stream Fallback**: If an upstream server or CDN does not support range requests (returns HTTP `200 OK` instead of `206 Partial Content`), the engine falls back to single-stream downloading without failing.-## External Tool Prerequisites+## File Lifecycle & State Files-Downloading from **MovieBox** requires `yt-dlp` and `ffmpeg` on the host system to demux and merge MPEG-DASH audio and video streams:+During download, files are saved with temporary extensions:-- **macOS**: Install via Homebrew: `brew install yt-dlp ffmpeg`-- **Linux**: Install via your system package manager (e.g. `sudo apt install yt-dlp ffmpeg`, `sudo pacman -S yt-dlp ffmpeg`)-- **Windows**: Install via WinGet or Scoop: `winget install yt-dlp.yt-dlp Gyan.FFmpeg`-- **Android / Termux**: Install via Termux package manager: `pkg install yt-dlp ffmpeg`+```text+destination.mp4.part # In-progress byte buffer+destination.mp4.part.json # Download state (ETag, Last-Modified, total size, segment offsets)+destination.mp4.assembling # Sequential segment assembly+destination.mp4 # Final verified output+```-If a MovieBox download is initiated without `yt-dlp` installed, MovieBox-TUI prevents execution and displays an OS-tailored notification with installation guidance. Progressive streams from other providers (CircleFTP, DhakaFlix, 4KHDHub, Addons) do not require `yt-dlp` or `ffmpeg`.-## File names and directories+Upon completion, temporary sidecars are verified and renamed atomically to the target filename.-`safe_file_stem` sanitizes titles for all platforms: control/whitespace/illegal-characters are replaced, Windows reserved names (`CON`, `COM1`-`COM9`, …) are avoided,-and length is capped.+## Download Controls-- **Series downloads:** Saved under `<base_dir>/Series/<Title>/Season <N>/<Title> - S<N:02>E<E:02>.<ext>` (and subtitle `<Title> - S<N:02>E<E:02>.<lang>.<sub_ext>`).-- **Movie downloads:** Saved under `<base_dir>/Movies/<Title>/<Title>.<ext>` (and subtitle `<Title>.<lang>.<sub_ext>`).-- **Default path:** Files go to the user's OS download directory (`~/Downloads/MovieBox-TUI`). On Android (Termux), the engine prefers shared `~/storage/downloads` when present, scoped strictly to verified Termux environments.-- **Custom path:** Users can set a custom download directory in `/settings` → General → Download Folder or reset to default. Target directories are validated with a write probe before saving, and the code creates the `MovieBox-TUI` subfolder hierarchy (`Movies/` and `Series/`). If custom storage becomes unavailable at runtime, the engine falls back to the default download location.-- **Path Containment:** Destination paths are validated against the canonical download base directory before file creation, with Windows verbatim `\\?\` prefix normalization, preventing directory escape.-## Contextual triggers & Seasons+- Press **`d`** on any stream in the Details screen to open the download confirmation dialog.+- Press **`x`** or **`X`** during an active download to cancel or pause the transfer. Partial `.part` data is preserved on disk for resumption.+- Downloads run cooperatively in the background, allowing you to browse or search without interrupting transfers.-- **Contextual trigger**: Pressing `d` (or clicking `[Download]`) while focused on the **Seasons** pane prompts to download all episodes of the selected season. Triggering download while on the **Episodes** or **Streams** pane prompts to download only that single episode.-- **Duplication prevention**: When starting a download or processing a season batch queue, the engine checks if the target media file is already completed on disk. Existing completed episodes are skipped.-- A season download enqueues every episode (`download_queue`) and processes them one at a time, each resolving its stream and subtitle. Progress is reported through `Action::UpdateDownload` and the status bar; failures pause and preserve partial data.-- Season downloads ask for the subtitle policy once per batch. The selected language, including an explicit `None` choice, is reused for every queued episode.+## Header Forwarding-Selected subtitle sidecars are saved next to the video using ISO 639-1 language codes (e.g. `.en.srt`, `.hi.srt`) and supported subtitle extensions (`.srt`, `.vtt`, `.ass`, `.ssa`, `.sub`).--## Download Bar & Progress Architecture--- **High-Contrast Responsive Bar**: Renders a proportional progress track (`[━━━━━────]` on modern terminals and `[=====>----]` on basic terminals) with prominent media title display (`⬇ Downloading: <Title>`), percentage badge, and separated transfer metrics (`<Size> | <Speed> | ETA <Time>`).-- **Monotonic DASH Normalization**: Multi-stream MPEG-DASH downloads via `yt-dlp` automatically normalize segmented tracks (video 0–90%, audio 90–98%, and track merger 99–100%) so that progress strictly increases and never resets backwards to 0% mid-download.-- **Throttled Updates**: Progress events are throttled to 250ms intervals, eliminating terminal flicker and event-channel flooding from high-frequency chunk streams.-- **Background Download Continuity**: Downloads continue running uninterrupted in the background when switching content providers (`Ctrl+P`) or toggling TV mode (`Ctrl+T`), keeping all active transfer workers and queues alive.-- **Isolated Cancellation Hitbox**: Cancellation is bound strictly to the `x` / `X` keyboard shortcut and the `[x] Cancel` button in the top-right corner of the download bar. Clicking anywhere else on the bar safely consumes the mouse event without interrupting active downloads.--## Outcomes--`DownloadCompleted` / `DownloadPaused` / `DownloadFailed` drive the UI status and-notifications. `ClearCache` and stale-file cleanup do not touch in-progress downloads.+Authenticated streams (such as MovieBox DASH manifests or 4KHDHub mirrors) automatically forward required headers (`User-Agent`, `Referer`, signed CloudFront cookies) to download workers, ensuring CDN transfers complete without `403 Forbidden` errors.diff --git a/docs/players.md b/docs/players.mdindex 199d84d..bd8347f 100644--- a/docs/players.md+++ b/docs/players.md@@ -1,83 +1,63 @@# Players-Playback is handed to an external player. `player.rs` detects available players and-builds the exact command; `tui/app/playback.rs` spawns it.--## Detection--`player::detect()` (powered by a centralized `probe_player_executable` engine) returns players in priority order, resolving paths dynamically with non-negative caching:--- macOS: IINA (if present), then mpv, then VLC (probing `/Applications`, `~/Applications`, Homebrew `/opt/homebrew/bin`, MacPorts `/opt/local/bin`, Nix profiles `~/.nix-profile/bin` and `/run/current-system/sw/bin`, standard `/bin`, and embedded app bundles `/Applications/IINA.app/Contents/MacOS/iina-cli` and `~/Applications/IINA.app/Contents/MacOS/iina-cli`).-- Linux: mpv, then VLC (probing native `$PATH`, user `.local/bin`, Flathub/Flatpak user & system exports `org.videolan.VLC` / `io.mpv.Mpv`, Snap `/snap/bin/*`, Nix profiles, standard `/bin`, and `flatpak run`).-- Windows: mpv, then VLC (probing executable-adjacent binaries, WinGet Links & Packages directory `%LOCALAPPDATA%\Microsoft\WinGet\Packages`, `%USERPROFILE%\Downloads` and `%USERPROFILE%\Desktop` extractions, `Program Files` including `mpv`, `mpv-player`, `mpv.net`, and `VideoLAN\VLC`, `LOCALAPPDATA\Programs`, portable drive roots `C:\mpv`, `C:\vlc`, `C:\tools`, Scoop shims & apps, Chocolatey, and Windows Registry `App Paths` and `Environment\Path`; zero-byte Windows Store App Execution Aliases in `WindowsApps` are intentionally excluded).-- Android/Termux: Android intent chooser (`termux-open`, `termux-open-url`, or `termux-am`), prioritized at index 0 ahead of CLI `mpv` and `vlc` to avoid selecting headless players lacking display servers. Streams play via external Android video players.--Resolution caches detected paths across runs while allowing newly installed players to be discovered dynamically when opening or navigating the Settings Hub (`/settings`), without requiring an application restart. A preferred player can be forced via `MOVIEBOX_PLAYER` env or `default_player` in config (e.g. `mpv`, `iina`, `vlc`, `android`), which reorders the list. The media player picker in the Settings Hub lists every detected player on your system and saves your selection to `config.json`. Playback launches directly using the preferred compatible player without intermediate modal dialogs.--## Command construction--| Player | Invocation | Notes |-| :--- | :--- | :--- |-| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [--ytdl-format=bestvideo[height<=H]+bestaudio/best..] --hls-bitrate=max [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Sets maximum adaptive stream bitrate and selected video/audio representation (`bestvideo[height<=H]`). Each non-UA, non-Referer header is passed as a separate `--http-header-fields` argument. Flatpak mpv is launched via `flatpak run` with `@@` file forwarding markers for local files. |-| VLC | `vlc --width=W --height=H --play-and-exit --adaptive-logic=highest [--adaptive-maxheight=H] [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Sets adaptive logic to highest representation within resolution limit (`--adaptive-maxheight=H`). Supports start time resume via `--start-time`. For CloudFront cookie-gated streams (MovieBox DASH), the URL is replaced by a loopback sidecar proxy address (`http://127.0.0.1:<port>/https/<host>/path`) that injects all auth headers server-side before forwarding chunks to VLC. Flatpak VLC wraps local files with `@@` markers. |-| IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. [--mpv-ytdl-format=bestvideo[height<=H]+bestaudio/best..] [--mpv-start=..] [--mpv-http-header-fields=..] [--mpv-sub-files=..] <url>` | Uses installed `iina-cli` with `--mpv-*` option forwarding; filters out unsupported Lua tracker scripts. Respects yt-dlp resolution caps when youtube-dl / yt-dlp is enabled in IINA Preferences. Falls back to `open -a IINA <url>` with an informational status warning if CLI is absent. |-| Android / Termux | `termux-open --chooser --content-type video/* <url>` (or `termux-open-url` / `termux-am`) | Opens an app chooser on the device, delegating playback to external apps (VLC, MX Player, Just Player, MPV Android). Requires `pkg install -y termux-tools termux-am`. Forwards `User-Agent`, `Referer`, and subtitles when using `termux-am`. |--Window size is derived from the live terminal size times the font cell size reported-by the image picker, then clamped to a fixed range.--## Headers--Playback sources (for example 4KHD and MovieBox) may carry `Referer`/`User-Agent` headers.-MovieBox DASH streams additionally carry signed `Cookie` headers for CloudFront authentication.-- mpv and IINA send headers via native CLI flags (`--user-agent`, `--referrer`, and `--http-header-fields`), and forward custom auth cookies via `--ytdl-raw-options-append` to yt-dlp hooks for DASH manifests.-while VLC maps them to `--http-referrer` / `--http-user-agent`. Android intent playback forwards `Referer`/`User-Agent` extras when using `am`/`termux-am`, and supports unauthenticated streams (CircleFTP, DhakaFlix, IPTV) and CDN streams natively.-The `supports_headers` gate in `app/playback.rs` validates whether a player can satisfy required stream headers. For VLC and Android Intent, signed CloudFront `Cookie` streams (such as MovieBox DASH manifests) are automatically supported via the detached loopback sidecar proxy (`--proxy-for-vlc`). The proxy injects the signed CloudFront cookies and auth headers server-side and streams chunks directly over localhost.-## Subtitles--- mpv receives the remote subtitle URL directly (`--sub-file=<url>`); mpv fetches it- with the stream headers applied.-- VLC and IINA download the subtitle to a temp file first, preserving the URL's- extension (srt/vtt/ass/…), and pass the local path. The download applies the source- headers. On failure a status is shown and playback continues without subtitles.-- Android intent playback downloads subtitles to shared storage (`~/storage/downloads/moviebox_subs` or `/sdcard/Download/moviebox_subs`) named clearly after the media title (e.g. `<Title> - S<N:02>E<E:02>.<ext>` or `<Title>.<ext>`), and passes local file paths to `am`/`termux-am` via `subtitles_location` and `subs` intent extras.- - Players supporting automatic subtitle intent binding (e.g. MX Player) load the file automatically.- - For players that do not auto-load external file paths from remote stream intents (e.g. VLC for Android, mpv-android), the file is immediately available in the player's subtitle file picker under `Download/moviebox_subs/`.- - Subtitles are retained during playback without premature deletion on intent command exit, and purged on a 24-hour retention cycle or via `/settings` → Clear Disk Cache.-- Desktop temp files are cleaned up after the player process exits and purged at startup if stale.--## Playback Tracking & Resume--When launching media with in-progress watch history, the player command automatically includes the starting position (`--start` / `--mpv-start` / `--start-time`).--- **Immediate Start Registration**: Media sessions are pre-registered into watch history (`record_start`) upon launch, ensuring that fast-exiting intent dispatchers (Android `termux-open` / `am start`, macOS `open -a IINA`) and unexpected terminal terminations retain history immediately.-- **Pre-Seeded State Files**: Before launching mpv or IINA, MovieBox-TUI creates a pending state file populated with metadata (`title`, `cover_url`, `stype`, `release_year`). If the application exits abruptly during playback, `reconcile_from_dir` self-heals and inserts new items into watch history without data loss.-- **Latched Lua Tracker (`moviebox_tracker.lua`)**: Observes `time-pos` and `duration` every 5 seconds. State file writes are atomic (`.tmp` file flushed and renamed with destination removal for Windows compatibility). Video completion at ≥ 90% or EOF is permanently latched, preventing player shutdown events from resetting completion status. Missing or live stream durations write JSON `null` to prevent invalid duration calculations.-- **Isolated Tracker vs Fallback Reconciliation**: Players with active Lua trackers (`mpv`, `iina-cli`) rely strictly on state file reconciliation, eliminating wall-clock progress overwrite races during pauses or seeks. Process elapsed time is used strictly as a guarded fallback for players without tracker scripts (e.g. VLC).-## Spawning--`launch_player` spawns the player with null stdin, piped stderr (plus piped stdout for-`PlayerKind::AndroidIntent` to intercept intent dispatcher error text), and its own-process group (Unix `process_group(0)`) or no-console flag (Windows `CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP`).--- **Concurrent Stderr Drain & Pipe Deadlock Prevention**: Stderr is read in a background thread concurrently with `child.wait()`, bounded by a 2-second timeout after process exit. This breaks pipe deadlocks when players (such as VLC with audio or output plugins) fork background subprocesses that inherit the pipe.-- **Clean Exit Normalization**: Routine exit states are normalized to avoid false crash reports:- - VLC exit code `1` with empty stderr (normal stream completion under `--play-and-exit`) is classified as clean exit (`PlayerExited`).- - Unix `SIGTERM` (signal 15) termination when the user closes player windows via the OS is treated as clean exit.- - Genuine non-zero failures with stderr diagnostics are surfaced directly as actionable player errors.- - When players exit without stderr diagnostics, exit codes are translated into actionable notifications (e.g. exit code `2` indicates `Stream Dead: Link expired or unreachable.`, exit code `1` indicates `Player Error: Check player configuration.`). Watch progress is reconciled only after a successful exit.--## Android / Termux Playback Architecture--On Android (Termux), terminal sessions do not have access to an X11 or Wayland display server by default:--- **Command-Line `mpv` (`pkg install mpv`)**: Operates in headless/audio-only mode. Video output cannot be rendered to the terminal screen and will fail or produce audio without video.-- **External Player Intent Dispatch**: Video playback is designed to open in dedicated Android video player applications (**VLC for Android**, **Just Player**, **MX Player**, or **MPV Android APK**).-- **Prerequisites**: Termux requires `pkg install -y termux-tools`.- - `termux-open` (from `termux-tools`) broadcasts an `android.intent.action.VIEW` intent to `TermuxOpenReceiver`, presenting Android's native app chooser without relying on background sockets.- - `termux-am` (from `termux-am`) attempts to connect to `am.sock` to pass custom stream headers and subtitles. If `am.sock` is unavailable or socket connection fails, MovieBox-TUI automatically falls back to `termux-open` transparently.-- **Actionable Mobile Diagnostics**: MovieBox-TUI parses intent dispatcher output and failure status codes, surfacing compact diagnostics formatted for mobile viewports:- - **Missing video player app**: Surfaces `No Player` (`Install a video player.`).- - **Missing intent tools**: Surfaces `Termux Setup` (`Run 'pkg install termux-tools'.`).- - **Headless CLI mpv**: Detects video output initialization failures and surfaces `CLI mpv` (`Switch to Android Player in /settings.`).- - **SELinux & Exit Code 126 Protection**: On Android 10+, executing `/system/bin/am` directly from an unrooted Termux environment causes Android's system shell to call `cmd activity`, which is blocked by SELinux when executing Termux app data binaries (`Permission denied`, exit code 126). MovieBox-TUI detects Termux environments, prevents illegal system `am` invocations, preserves `LD_PRELOAD` for Termux applet compatibility, strictly gates system `am` checks behind `target_os = "android"` (preventing GNU Automake collisions on desktop Linux), and surfaces actionable remediation notifications.+MovieBox-TUI delegates playback to external media players (`mpv`, `IINA`, `VLC`, or Android intent players).++## Detection Order++Players are detected in priority order and cached across runs:++- **macOS**: `IINA` → `mpv` → `VLC`+ - Searches `/Applications`, `~/Applications`, Homebrew, MacPorts, Nix, and native CLI tools.+- **Linux**: `mpv` → `VLC`+ - Searches `$PATH`, `~/.local/bin`, Flatpak exports (`io.mpv.Mpv`, `org.videolan.VLC`), and Snap.+- **Windows**: `mpv` → `VLC`+ - Searches `%LOCALAPPDATA%`, `Program Files`, WinGet packages, Scoop shims, Chocolatey, and Windows Registry `App Paths`.+- **Android / Termux**: `Android Intent`+ - Dispatches to external video players via `termux-open` or `am start`.++You can set a default player via `/settings` (Media Player), or override it with the `MOVIEBOX_PLAYER` environment variable.++## Player Invocations++### mpv+```bash+mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [OPTIONS] <url>+```+- **Tracking**: Injects `moviebox_tracker.lua` to track watch progress and update history every 5 seconds.+- **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`.+- **Subtitles**: Remote subtitles are loaded directly via `--sub-file=<url>`.++### VLC+```bash+vlc --width=W --height=H --play-and-exit --adaptive-logic=highest [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>`) that injects auth headers server-side.+- **Subtitles**: Remote subtitles are pre-downloaded to temporary storage and passed via `--sub-file=<path>`.++### IINA (macOS)+```bash+iina-cli --keep-running --no-stdin --mpv-autofit=WxH [OPTIONS] <url>+```+- Forwards `--mpv-*` arguments to internal mpv core.+- Falls back to `open -a IINA <url>` if CLI tools are unlinked.++### Android / Termux+```bash+termux-open --chooser --content-type video/* <url>+```+- Opens the system app chooser, delegating playback to installed Android players (VLC, MX Player, Just Player, mpv-android).+- Subtitles are saved to shared storage (`~/storage/downloads/moviebox_subs`) and passed via intent extras.++## Watch History & Resume++- **Position Resumption**: In-progress items launch with `--start=<seconds>` (`mpv`/`IINA`) or `--start-time=<seconds>` (`VLC`).+- **Completion Detection**: Reaching ≥ 90% or stream EOF marks media as completed.+- **State Reconciliation**: `mpv` and `IINA` sync playback progress via background IPC state files, preventing wall-clock drift during pauses or seeks.++## 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.+- 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/docs/providers.md b/docs/providers.mdindex e454a80..29129e3 100644--- a/docs/providers.md+++ b/docs/providers.md@@ -1,118 +1,41 @@-# Providers+# Streaming Providers-MovieBox-Tui aggregates several movie/stream providers plus user M3U playlists. Each-provider is an independent async client exposing a similar shape, normalized into the-shared typed models in `providers/models.rs` and the moviebox JSON schema used by the UI.+MovieBox-TUI searches and streams media across multiple independent providers.-## Provider kinds+## Available Providers-| Provider | Module | Description |-| :--- | :--- | :--- |-| **MovieBox** | `providers/moviebox` | Primary provider. Signed API requests with Edge-Cache and CloudFront DASH manifest resolution. |-| **FourKHdHub** | `providers/fourkhdhub` | 4K releases; hubcloud mirror resolver. |-| **BdixCircleFtp** | `providers/bdix/circleftp` | BDIX FTP directory scrapes. |-| **BdixDhakaFlix** | `providers/bdix/dhakaflix` | BDIX indexer. |-| **Addons** | `providers/addons` | Community HTTP addons (Cinemeta, streams). |+| Provider | Description |+| :--- | :--- |+| **MovieBox** | Primary streaming catalog with multi-language audio, seasons, and subtitles. |+| **4KHDHub** | High-bitrate 4K UHD and 1080p releases with fast CDN mirrors. |+| **Dramachi** | Asian dramas and series catalog. |+| **CircleFTP** | High-speed local BDIX mirror (Bangladesh ISPs). |+| **DhakaFlix** | Local BDIX media indexer (Bangladesh ISPs). |+| **Addons** | Community Stremio HTTP addons (Cinemeta catalog and streams). |-BDIX sources are local optical mirrors reachable from supported Bangladeshi ISPs.-On first startup, MovieBox-Tui automatically probes BDIX mirror endpoints on your local network-and enables available ones. Individual providers (MovieBox, 4KHDHub, CircleFTP, DhakaFlix) can-also be manually toggled in `/settings` (or `s`) → Content Modes. A manual re-probe can be-triggered via `/settings` → Maintenance → Re-check BDIX Network.-Active streaming providers can be cycled via `Ctrl+P` or visually selected by clicking the provider badge (`[MovieBox · ^P]`) on the landing search bar to open the anchored provider popup menu.-## Shared Provider Contract+## Switching Providers-Search, details, and episode-streams are dispatched per provider. Pluggable provider seams-in `providers/mod.rs` give every client a shared, strictly-typed async trait shape:+- **Cycle Provider**: Press **`Ctrl+P`** on the home screen to switch to the next provider.+- **Provider Menu**: Click the provider badge in the search bar (or press `Enter` on it) to open the provider selection menu.+- **Enable / Disable Providers**: Open `/settings` → **Content Modes** → **Streaming Sources** to toggle providers on or off.-- `Provider::id(&self) -> ProviderKind`: Returns the provider's unique identifier.-- `Provider::capabilities(&self) -> ProviderCapabilities`: Reports supported capabilities (`supports_search`, `supports_pagination`, `supports_series`, `supports_subtitles`, `supports_homepage`).-- `Provider::search(&self, query: &str, page: usize) -> Result<Vec<CatalogItem>, ProviderError>`: Dispatches search queries, returning strongly-typed `CatalogItem`s.-- `Provider::details(&self, id: &str) -> Result<MediaDetails, ProviderError>`: Dispatches metadata queries, returning strongly-typed `MediaDetails`.-- `ReleaseProvider::episode_streams(&self, id: &str, season: usize, episode: usize) -> Result<Vec<Release>, ProviderError>`: Returns the typed `Release` list for release-based providers.-- `ProviderError`: Standardized error boundary (`Network`, `RateLimited`, `NotFound`, `Parsing`, `Unavailable`) with `.user_message(provider)` generating clean UI toast notifications.+## BDIX Network Detection-### Strongly Typed Architecture & Binary Disk Caching+If you are connected through a Bangladeshi ISP supporting BDIX:+- MovieBox-TUI automatically tests local BDIX mirrors on startup and enables them if reachable.+- You can manually re-test your connection anytime via `/settings` → **Maintenance** → **Re-check BDIX Network**.-All internal state (`AppState`), UI screens (`details.rs`, `home.rs`), and the action event bus transport native Rust structs directly:-- `CatalogItem` / `SearchResult` for search results and discover catalogs.-- `MediaDetails` (with `Vec<Season>` and `Vec<AudioTrackOption>`) for media metadata.-- `Release` (with `Vec<SourceMirror>` and optional `resource_id`) for streams.-- `SubtitleOption` for external subtitles.+## Provider Architecture (For Developers)-Disk caching in `src/cache.rs` uses portable binary serialization via `rmp-serde` (MessagePack) with a 4-byte magic signature (`MBC1`) and versioned TTL envelope (`CacheEnvelope<T>`).+All providers implement a shared Rust trait in `src/providers/`:-Playback resolves to a `PlaybackSource { provider, url, headers, subtitle, source_label }`,-which `app/playback.rs::launch_player` feeds to the external player.+```rust+pub trait Provider: Send + Sync {+ fn id(&self) -> ProviderKind;+ fn capabilities(&self) -> ProviderCapabilities;+ async fn search(&self, query: &str, page: usize) -> Result<Vec<CatalogItem>, ProviderError>;+ async fn details(&self, id: &str) -> Result<MediaDetails, ProviderError>;+}+```-## Adding a New Provider--Adding a new streaming or BDIX provider to MovieBox TUI takes 3 simple steps:--1. **Define the Provider Variant (`src/providers/models.rs`)**:- Add the new variant to `ProviderKind` with its label, cache key, and serialization aliases.--2. **Implement the `Provider` Trait (`src/providers/<new_provider>/`)**:- Implement `Provider::id`, `Provider::capabilities`, `Provider::search`, and `Provider::details` for your client struct, returning typed domain models (`CatalogItem`, `MediaDetails`). If your provider resolves release streams, also implement `ReleaseProvider`.--3. **Register the Client in `MovieBoxService` (`src/service.rs`)**:- Add your client struct to `MovieBoxService`, instantiate it in `MovieBoxService::new()`, and map it in `capabilities`, `search_typed`, and `details_typed`. All search, details, and stream dispatches operate natively with zero JSON shims.--## MovieBox-- Base host pool + per-request HMAC-MD5 signature, client token, and a spoofed Android- device identity (`crypto.rs`) spoofing APK `v4.0.01.0813.03` (`version_codes: 50020117..50020121`)- to satisfy the backend gateway and prevent notice video substitution.-- Hosts are retried; a shared runtime token is re-initialized when all hosts fail.-- Mobile `User-Agent` generated by the crypto module is forwarded through playback and download- pipelines to satisfy CDN anti-bot checks.-- Stream resolution in `providers/moviebox/mod.rs` merges mobile DASH manifests (`play-info/v2`) and high-bitrate community/server releases (`/subject-api/resource`) with automatic deprecation notice URL filtering (`is_deprecation_notice_url`), deduplicating stream links and sorting releases by descending numeric quality and byte size.-- Multi-resolution discovery (`fetch_collection_resolutions`) dynamically discovers available- stream resolutions with descending quality sorting.-- Multi-resolution DASH manifests (`index.mpd`) and adaptive streams are labeled with a distinct- `[Multi]` badge, stripping confusing raw CDN resolution tags from release titles.-- Title normalization lives in `moviebox/title.rs` (`clean_moviebox_title`).-- **DASH Manifest Playback & Downloads**: Media streams are hosted on CloudFront as segmented MPEG-DASH manifests (`index.mpd`) protected by signed policy cookies. Stream playback forwards `Cookie`, `Referer`, and `User-Agent` headers to external players (`mpv`, `IINA`). Local downloads utilize `yt-dlp` with forwarded authentication headers to demux and assemble audio/video streams into `.mp4`.-## 4KHDHub--- Quality detection in `parser.rs::detect_quality` normalizes `4K`, `UHD`, `2160`, `1080`, `FHD`, `720`, `HD`, and `480` tokens, ensuring 4K/2160p releases are never treated as unknown resolution.-- Releases in `parser.rs::parse_releases` sort by numeric resolution (`resolution_u64()`) descending and file size descending, prioritizing 4K UHD BluRay REMUXes over lower-resolution encodes.-- `client.rs::resolve_release` resolves release mirrors concurrently using bounded-concurrency probing (`select_ok` in batches of 3) with a 3.5s per-probe timeout.-- Preflight probes issue a bounded range probe (`Range: bytes=0-8191`) and inspect response bodies for expired mirror errors (`"Failed to extract link"`, `"Token Expired"`, `"404"`) to fail fast on expired torrents.-- `hubcloud.rs` scores and prioritizes candidate streams based on `ResolutionIntent`:- - **Playback (`ResolutionIntent::Playback`)**: Prioritizes seekable multi-connection streaming CDNs (`pixel.hubcloud.` -> Google Video CDN, Cloudflare R2, PixelDrain API) while deprioritizing single-use download workers (`workers.dev`) to prevent HTTP 403 token-burn and player authentication popups.- - **Download (`ResolutionIntent::Download`)**: Permits both high-speed streaming CDNs and direct file download proxies for maximum throughput.-- **Mediator Redirector Resolution**: `hubcloud.rs::resolve_greenmotors` transparently unpacks intermediate JavaScript mediator domains (`greenmotors.club`, `greenmountmotors.`) using a multi-stage decoding pipeline (double Base64, ROT13, JSON extraction) to recover downstream `hubcloud.` and `hubdrive.` mirror endpoints without requiring an external browser engine.-- **Multilingual audio detection**: `parser.rs::detect_language` parses release titles and- metadata for 30+ regional and international languages (Hindi, Tamil, Telugu, Kannada,- Malayalam, Bengali, Marathi, Punjabi, Gujarati, Urdu, Japanese, Korean, Chinese, Spanish,- French, German, Italian, etc.) and formats all available audio tracks for stream display.-- Errors are mapped into `ProviderError::Unavailable` with user-actionable instructions guiding selection of alternate releases.--## Dramachi-- Asian drama, anime, and international movie provider backed by `https://api.nodeobjects.com/`.-- Zero authentication, cookies, or signing required.-- Direct HTTP byte-range video streaming (`Accept-Ranges: bytes`) over dynamic media CDNs (`https://{hostInfo.host}/cdn/{fileInfo.url}`).-- Audio dubs and rips are mapped into `AudioTrackOption` and resolved dynamically via composite subject IDs (`{title_id}::{rip}`).-- Movie and series streams play directly without proxy overhead (`direct_file: true`).--## BDIX-- `circleftp` and `dhakaflix` scrape FTP-style indexes; both are used behind the- Bangladesh-only gate.--## Community HTTP Addons--- `providers/addons` communicates with HTTP addon manifests (`/manifest.json`).-- Cinemeta provides catalog searches and metadata details (`/catalog`, `/meta`).-- Stream addons (e.g. HdHub, direct CDN manifests) resolve playable HTTP/HTTPS streams concurrently. See [addons-mode.md](addons-mode.md).--## M3U playlists (TV mode)--`providers/tv` parses an M3U playlist from an `https://` URL or a local file path.-Each channel yields `{ id, name, logo, group, stream_url }`; TV mode groups channels by-`group-title` and dedupes by `stream_url`. See [tv-mode.md](tv-mode.md).--## Error handling--Each provider defines its own `thiserror` enum (`ScraperError`, `FourKHdHubError`,-`DramachiError`, `CircleFtpError`, `DhakaFlixError`). Errors bubble to `app/requests.rs` handlers, which-surface them in the UI status bar and log the full detail (see [logging.md](logging.md)).+New providers implement `Provider` (and optionally `ReleaseProvider` for multi-mirror streams), then register in `src/service.rs`. Responses are automatically cached as MessagePack envelopes.diff --git a/docs/tv-mode.md b/docs/tv-mode.mdindex b1cac33..06dc131 100644--- a/docs/tv-mode.md+++ b/docs/tv-mode.md@@ -1,43 +1,35 @@# TV Mode-TV mode streams live channels from M3U playlists. You add playlists by URL or local-file path, and the app parses, groups, dedupes, and lets you search and play them.+TV mode streams live television channels from M3U playlists. Playlists can be loaded from remote URLs or local files.-## Entering TV mode+## Entering TV Mode-- `Ctrl+T` toggles Streaming / TV mode.-- On first entry with no playlists, the playlist manager opens.-- While in TV mode, type to filter channels by name or group, `Enter` to play,- `/list` for all channels, `/config` to manage playlists, `[r]` to reload.+- Press **`Ctrl+T`** to toggle between Streaming and TV mode.+- If no playlists are loaded on entry, the playlist manager opens automatically.+- Type in the search bar to filter channels by name or group; press `Enter` to play.-## Adding playlists+## Managing Playlists-1. `/config` opens the playlist manager.-2. Select `+ Add playlist`, type the URL or local file path, `Enter` to add.- - URL example: `https://example.com/playlist.m3u`- - File example: `~/playlists/mine.m3u`-3. Sources persist in `tv_config.json` (under the config dir). Local file playlists are- reread directly on every TV-mode entry; remote URL playlists may reuse a recent- cached snapshot for up to 24 hours. If `tv_config.json` encounters corrupt data on disk,- it is safely rotated to `tv_config.json.corrupt.{timestamp}` rather than deleted.-4. Highlight a source and press `d` (or `Enter`) to remove it; the list reloads.+1. Enter **`/config`** while in TV mode to open the playlist manager.+2. Select **`+ Add playlist`**, enter the URL or local file path, and press `Enter`.+ - **URL**: `https://example.com/playlist.m3u`+ - **File**: `~/playlists/channels.m3u` (supports `~/` tilde expansion and Windows paths)+3. Press **`r`** inside the manager to reload all playlist sources.+4. Highlight an entry and press **`d`** (or `Delete`) to remove it.+5. Press **`Esc`** to close the manager.-## Parsing and search+Playlists are saved to `tv_config.json` in your configuration directory.-`src/providers/tv/` parses each source (http(s) or local file), extracting channel id,-name, logo, `group-title`, and stream URL. Playlist lines are pre-counted to preallocate vector capacity, eliminating dynamic heap reallocations during large 50,000+ channel imports. Both remote downloads and local files enforce a maximum 15MB size limit (`MAX_PLAYLIST_BYTES`), rejecting oversized playlists before parsing to prevent memory exhaustion. Channels are **deduped by stream URL**-across all playlists. The search box filters by name or group; the status bar reports-how many channels were imported and which playlists failed.+## Channel Parsing & Safeguards-## Playback+- **Size Limits**: Files and downloads larger than 15 MB are rejected to prevent excessive memory consumption.+- **Deduplication**: Channels sharing identical stream URLs across multiple playlists are deduplicated.+- **Attributes**: Parses `#EXTINF:` tags for `tvg-id`, `tvg-logo`, `group-title`, and channel name.-`Enter` on a channel launches the default player with the channel URL (via the same-`launch_player` path as movies). Channel logos are cached under the `iptv` image-namespace. Live streams without a finite duration (`duration_seconds: None`) are automatically exempted from the in-progress Continue Watching shelf, preventing unfinishable entries from accumulating in watch history.+## Playback & Commands-## Commands in TV mode--- `/list` — display all loaded TV channels.-- `[r]` key — reload all active M3U playlist sources.-- Global commands (`/settings`, `/clear`, `/help`, `/exit`) are active across all modes.-- Streaming-only commands (e.g. `/browse`, `/history`, `/favorites`) display guidance notifications prompting you to switch to streaming mode (`Ctrl+S`).+- **Playback**: Press `Enter` on a channel to launch your default media player. Live streams without fixed durations are exempted from watch history.+- **Commands**:+ - **`/list`**: View all loaded TV channels.+ - **`r`**: Reload all active playlists.+ - **`/config`**: Open the playlist manager.diff --git a/src/download.rs b/src/download.rsindex 6b2c672..12f810a 100644--- a/src/download.rs+++ b/src/download.rs@@ -947,4 +947,72 @@ mod tests {let err_paused = DownloadError::Paused;assert_eq!(err_paused.user_message(), "Download paused.");}++ #[tokio::test]+ async fn test_download_forwards_custom_headers_and_content_to_local_server() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ use tokio::net::TcpListener;++ 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}/video.mp4");++ let server = tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = [0u8; 1024];+ let n = socket.read(&mut buf).await.unwrap();+ let req = String::from_utf8_lossy(&buf[..n]);+ let lower = req.to_lowercase();+ assert!(lower.contains("user-agent: moviebox-custom-ua"));+ assert!(lower.contains("referer: https://custom.referer.test/"));+ assert!(lower.contains("x-auth-token: secret-token-123"));+ let body = b"test video binary chunk stream";+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: video/mp4\r\nConnection: close\r\n\r\n",+ body.len()+ );+ socket.write_all(response.as_bytes()).await.unwrap();+ socket.write_all(body).await.unwrap();+ });++ let temp_dir = std::env::temp_dir().join(format!("mbx_dl_test_{}", std::process::id()));+ tokio::fs::create_dir_all(&temp_dir).await.unwrap();+ let dest_file = temp_dir.join("test_video.mp4");++ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert(+ reqwest::header::USER_AGENT,+ "MovieBox-Custom-UA".parse().unwrap(),+ );+ headers.insert(+ reqwest::header::REFERER,+ "https://custom.referer.test/".parse().unwrap(),+ );+ headers.insert(+ reqwest::header::HeaderName::from_static("x-auth-token"),+ "secret-token-123".parse().unwrap(),+ );++ let client = crate::net::streaming_client_builder()+ .default_headers(headers)+ .build()+ .unwrap();++ let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let mut progress_count = 0usize;++ let res = download(&client, &url, &dest_file, cancel, |_prog| {+ progress_count += 1;+ })+ .await;++ server.await.unwrap();+ assert!(matches!(res, Ok(DownloadOutcome::Completed { .. })));+ assert!(dest_file.exists());+ let saved = tokio::fs::read(&dest_file).await.unwrap();+ assert_eq!(saved, b"test video binary chunk stream");+ assert!(progress_count > 0);++ let _ = tokio::fs::remove_dir_all(&temp_dir).await;+ }}diff --git a/src/player.rs b/src/player.rsindex bf625c6..5d6c3b3 100644--- a/src/player.rs+++ b/src/player.rs@@ -1839,4 +1839,70 @@ mod tests {};assert!(configured_executable("MOVIEBOX_VLC_PATH").is_none());}++ #[test]+ fn test_mpv_command_headers_and_arguments_assembly() {+ let headers = vec![+ ("User-Agent".to_string(), "MovieBox-Tui/0.1.23".to_string()),+ ("Referer".to_string(), "https://upstream.cdn/".to_string()),+ ("Origin".to_string(), "https://upstream.cdn".to_string()),+ ];+ let cmd = mpv_command(+ "https://upstream.cdn/stream.m3u8",+ Some("/tmp/test.srt"),+ &headers,+ false,+ Some((1920, 1080)),+ Some(120),+ None,+ None,+ );+ let args: Vec<String> = cmd+ .get_args()+ .map(|a| a.to_string_lossy().into_owned())+ .collect();++ 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.iter().any(|a| a.starts_with("--http-header-fields="))+ || args+ .iter()+ .any(|a| a.starts_with("--ytdl-raw-options-append="))+ );+ assert_eq!(+ args.last().map(String::as_str),+ Some("https://upstream.cdn/stream.m3u8")+ );+ }++ #[test]+ fn test_vlc_command_cookie_header_filtering() {+ let headers = vec![+ ("User-Agent".to_string(), "VLC-Agent".to_string()),+ ("Referer".to_string(), "https://cdn.example.com".to_string()),+ ("Cookie".to_string(), "CloudFront-Signature=abc".to_string()),+ ];+ let cmd = vlc_command(+ "http://127.0.0.1:4567/proxy/manifest.mpd",+ None,+ &headers,+ None,+ None,+ None,+ );+ let args: Vec<String> = cmd+ .get_args()+ .map(|a| a.to_string_lossy().into_owned())+ .collect();++ assert!(args.contains(&"--http-user-agent=VLC-Agent".to_string()));+ assert!(args.contains(&"--http-referrer=https://cdn.example.com".to_string()));+ assert!(!args.iter().any(|a| a.contains("CloudFront-Signature")));+ assert_eq!(+ args.last().map(String::as_str),+ Some("http://127.0.0.1:4567/proxy/manifest.mpd")+ );+ }}diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rsindex e12d8d8..c3bcfc5 100644--- a/tests/tui_acceptance.rs+++ b/tests/tui_acceptance.rs@@ -70,18 +70,6 @@ async fn test_download_subtitle_popup_renders_in_app_draw() {assert!(content.contains("English"));}-#[tokio::test]-async fn test_tui_startup_and_home_screen_rendering() {- let backend = TestBackend::new(100, 30);- let mut terminal = Terminal::new(backend).unwrap();- let mut app = App::new();-- terminal.draw(|frame| app.draw(frame)).unwrap();- let buffer = terminal.backend().buffer();- assert_eq!(buffer.area.width, 100);- assert_eq!(buffer.area.height, 30);-}-#[tokio::test]async fn test_tui_all_theme_rendering() {for theme_kind in ThemeKind::ALL {