Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
refactor: optimize IPTV cache handling, upgrade install script, and transition search protocols to LRU cache
Samir Hossains66cd4b00cbef
diff --git a/Cargo.lock b/Cargo.lockindex d84669d..0bc24e1 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1954,7 +1954,7 @@ dependencies = [[[package]]name = "moviebox-tui"-version = "0.1.5"+version = "0.1.6"dependencies = ["base64","chrono",diff --git a/Cargo.toml b/Cargo.tomlindex 0b35564..bcf152a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,7 +1,7 @@[package]name = "moviebox-tui"exclude = ["assets/", ".github/", "scripts/", "install.sh", "install.ps1"]-version = "0.1.5"+version = "0.1.6"edition = "2024"description = "A terminal client for finding and streaming movies, TV shows, and anime from the MovieBox catalog."repository = "https://github.com/mesamirh/MovieBox-Tui"diff --git a/README.md b/README.mdindex c61d6e5..03f8973 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@# MovieBox-Tui-Stream and download movies, TV shows, and anime from the terminal.+Stream and download movies, TV shows, anime, and watch live TV from the terminal.[](https://crates.io/crates/moviebox-tui)[](https://crates.io/crates/moviebox-tui)@@ -23,7 +23,7 @@ Stream and download movies, TV shows, and anime from the terminal.## What is this?-**MovieBox-Tui** is a terminal-based streaming client. It interfaces with the MovieBox API to search catalogs, resolve stream URLs, and open them in your local video player (`mpv`, `IINA`, or `VLC`).+**MovieBox-Tui** is a terminal-based streaming client. It interfaces with the MovieBox to search catalogs, resolve stream URLs, and open them in your local video player (`mpv`, `IINA`, or `VLC`).No browser or configuration is required. Search for a title, select a video quality, and press enter to play or download the stream.@@ -78,6 +78,7 @@ No browser or configuration is required. Search for a title, select a video qual- Download videos straight to your disk using multiple connections to max out your internet speed. You get live speed and ETA updates while you wait.- **Subtitles included:** It automatically grabs the `.srt` subtitle files to match your video.- **Download entire seasons:** Queue up a whole season at once. Just tell it what language you want for the subtitles, and it handles the rest automatically.+- **Live TV Mode:** Press `Ctrl+T` to switch to TV mode and watch thousands of live IPTV channels from around the world straight from your terminal.- **Works on your terminal:** Whether you're on macOS, Linux, or Windows, it just works. If your terminal supports it, you'll get actual image posters; otherwise, it falls back nicely to text.---@@ -150,18 +151,27 @@ Here's how to get around:- **Select:** Press <kbd>Enter</kbd> to view details, pick episodes, or start playing a video.- **Switch Player:** Press <kbd>o</kbd> on a stream if you want to open it in a different video player.- **Download:** Press <kbd>d</kbd> on any episode or season to save it to your disk (you'll get to pick your subtitles first).+- **Live TV:** Press <kbd>Ctrl+T</kbd> to toggle Live TV mode and browse IPTV channels.- **Refresh:** Press <kbd>r</kbd> if a stream link expires and needs to be re-fetched.- **Help:** Need a quick reminder? Press <kbd>?</kbd> anywhere to see the cheat sheet.-- **Quit:** Press <kbd>q</kbd> or mash <kbd>Esc</kbd> to exit.+- **Quit:** Press <kbd>q</kbd> to exit (use <kbd>Esc</kbd> to go back or clear search).### Handy Slash CommandsYou can type these special commands straight into the search bar:-- `/discover` or `/home` - See what's trending right now.-- `/movies`, `/shows`, `/anime` - Jump straight to a specific category.++**General commands:**- `/clear-cache` - Free up disk space by wiping downloaded images and cache.- `/update` - Check to see if there's a new version of the app.- `/toggle-update` - Turn automatic background update checking on or off.+**Streaming Mode commands:**+- `/discover` or `/home` - See what's trending right now.+- `/movies`, `/shows`, `/anime` - Jump straight to a specific category.++**Live TV Mode commands:**+- `/list` - Show the list of available live channels.+- `/config` - Open the TV configuration menu to add your own m3u playlists.+---## Contributing@@ -178,6 +188,12 @@ Just try to follow [Conventional Commits](https://www.conventionalcommits.org/)---+## Credits++Live TV channel playlists are graciously provided by [iptv-org/iptv](https://github.com/iptv-org/iptv).++---+## SupportIf this TUI makes your movie nights better and you want to support its development, crypto tips are always super appreciated:diff --git a/install.ps1 b/install.ps1index 8ebb05a..7d04269 100644--- a/install.ps1+++ b/install.ps1@@ -1,35 +1,45 @@$ErrorActionPreference = 'Stop'-Write-Host "Installing MovieBox-Tui..." -ForegroundColor Cyan--$Url = "https://github.com/mesamirh/MovieBox-Tui/releases/latest/download/MovieBox_Windows_x64.zip"$InstallDir = "$env:USERPROFILE\AppData\Local\MovieBox-Tui"+$ExePath = "$InstallDir\moviebox-tui.exe"$ZipFile = "$env:TEMP\MovieBox_Windows_x64.zip"+$Url = "https://github.com/mesamirh/MovieBox-Tui/releases/latest/download/MovieBox_Windows_x64.zip"++$IsUpdate = Test-Path $ExePath-Write-Host "Downloading latest release..."+if ($IsUpdate) {+ Write-Host ">> Updating MovieBox-Tui to the latest version..." -ForegroundColor Yellow+} else {+ Write-Host ">> Installing MovieBox-Tui..." -ForegroundColor Blue+}++Write-Host ">> Downloading latest release..." -ForegroundColor BlueInvoke-WebRequest -Uri $Url -OutFile $ZipFile -UseBasicParsingif (!(Test-Path $InstallDir)) {New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null}-Write-Host "Extracting..."+Write-Host ">> Extracting files..." -ForegroundColor BlueExpand-Archive -Path $ZipFile -DestinationPath $InstallDir -Force-if (Test-Path "$InstallDir\moviebox-tui.exe") {- Remove-Item "$InstallDir\moviebox-tui.exe" -Force -ErrorAction SilentlyContinue+if ($IsUpdate) {+ Remove-Item $ExePath -Force -ErrorAction SilentlyContinue}Rename-Item -Path "$InstallDir\MovieBox.exe" -NewName "moviebox-tui.exe" -Force -ErrorAction SilentlyContinue-Remove-Item $ZipFile -Force$UserPath = [Environment]::GetEnvironmentVariable("PATH", "User")if ($UserPath -notmatch [regex]::Escape($InstallDir)) {- Write-Host "Adding to PATH..."+ Write-Host ">> Adding to PATH..." -ForegroundColor Blue$NewPath = "$UserPath;$InstallDir"[Environment]::SetEnvironmentVariable("PATH", $NewPath, "User")Write-Host "Warning: Please restart your PowerShell window for the PATH changes to take effect." -ForegroundColor Yellow}-Write-Host "Success! You can now run 'moviebox-tui' from anywhere." -ForegroundColor Green+if ($IsUpdate) {+ Write-Host "Success! MovieBox-Tui has been updated. Run 'moviebox-tui' to start." -ForegroundColor Green+} else {+ Write-Host "Success! MovieBox-Tui is installed. Run 'moviebox-tui' to start." -ForegroundColor Green+}diff --git a/install.sh b/install.shindex aab6250..48b1f4b 100644--- a/install.sh+++ b/install.sh@@ -1,7 +1,21 @@#!/bin/bashset -e-echo "Installing MovieBox-Tui..."+RED='\033[0;31m'+GREEN='\033[0;32m'+BLUE='\033[0;34m'+YELLOW='\033[1;33m'+NC='\033[0m'++INSTALL_DIR="/usr/local/bin"+BIN_NAME="moviebox-tui"+APP_PATH="$INSTALL_DIR/$BIN_NAME"++if command -v "$BIN_NAME" &> /dev/null; then+ echo -e "${YELLOW}>> Updating MovieBox-Tui to the latest version...${NC}"+else+ echo -e "${BLUE}>> Installing MovieBox-Tui...${NC}"+fiOS="$(uname -s)"ARCH="$(uname -m)"@@ -12,28 +26,44 @@ elif [ "$OS" = "Linux" ]; thenif [ "$ARCH" = "x86_64" ]; thenFILE="MovieBox_Linux_x64.tar.gz"else- echo "Error: Unsupported Linux architecture: $ARCH. Only x86_64 is supported currently."+ echo -e "${RED}Error: Unsupported Linux architecture ($ARCH). Only x86_64 is supported.${NC}"exit 1fielse- echo "Error: Unsupported OS: $OS"+ echo -e "${RED}Error: Unsupported OS ($OS).${NC}"exit 1fiURL="https://github.com/mesamirh/MovieBox-Tui/releases/latest/download/$FILE"TMP_DIR=$(mktemp -d)-echo "Downloading latest release for $OS..."-curl -fsSL "$URL" -o "$TMP_DIR/$FILE"+echo -e "${BLUE}>> Downloading latest release...${NC}"+if ! curl -fsSL --progress-bar "$URL" -o "$TMP_DIR/$FILE"; then+ echo -e "${RED}Error: Failed to download release.${NC}"+ rm -rf "$TMP_DIR"+ exit 1+fi-echo "Extracting..."+echo -e "${BLUE}>> Extracting...${NC}"tar -xzf "$TMP_DIR/$FILE" -C "$TMP_DIR"-INSTALL_DIR="/usr/local/bin"-echo "Installing to $INSTALL_DIR (may require sudo password)..."-sudo mv "$TMP_DIR/moviebox" "$INSTALL_DIR/moviebox-tui"-sudo chmod +x "$INSTALL_DIR/moviebox-tui"+echo -e "${BLUE}>> Moving binary to $INSTALL_DIR...${NC}"+if [ -w "$INSTALL_DIR" ]; then+ mv "$TMP_DIR/moviebox" "$APP_PATH"+else+ sudo mv "$TMP_DIR/moviebox" "$APP_PATH"+fi++if [ -w "$APP_PATH" ]; then+ chmod +x "$APP_PATH"+else+ sudo chmod +x "$APP_PATH"+firm -rf "$TMP_DIR"-echo "Success! You can now run 'moviebox-tui' from anywhere in your terminal."+if command -v "$BIN_NAME" &> /dev/null; then+ echo -e "${GREEN}Success! MovieBox-Tui has been updated. Run 'moviebox-tui' to start.${NC}"+else+ echo -e "${GREEN}Success! MovieBox-Tui is installed. Run 'moviebox-tui' to start.${NC}"+fidiff --git a/src/cache.rs b/src/cache.rsindex 13068d9..674baad 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -5,7 +5,7 @@ use std::time::SystemTime;const CACHE_EXPIRY_SECS: u64 = 24 * 60 * 60;pub fn get_cache_dir(subdir: &str) -> PathBuf {- let mut path = dirs::cache_dir().unwrap_or_else(|| std::env::temp_dir());+ let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);path.push("moviebox-tui");path.push(subdir);if !path.exists() {@@ -143,7 +143,7 @@ pub fn invalidate_stream_cache(subject_id: &str, season: usize, episode: usize)}pub fn clear_all_cache() {- let mut path = dirs::cache_dir().unwrap_or_else(|| std::env::temp_dir());+ let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);path.push("moviebox-tui");if path.exists() {let _ = fs::remove_dir_all(&path);diff --git a/src/providers/iptv_org/m3u.rs b/src/providers/iptv_org/m3u.rsindex 4ab51c7..377f465 100644--- a/src/providers/iptv_org/m3u.rs+++ b/src/providers/iptv_org/m3u.rs@@ -1,8 +1,8 @@-use std::path::PathBuf;+use regex::Regex;+use serde::{Deserialize, Serialize};use std::fs;+use std::path::PathBuf;use std::time::SystemTime;-use serde::{Deserialize, Serialize};-use regex::Regex;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct Channel {@@ -17,16 +17,26 @@ pub struct M3UParser {cache_dir: PathBuf,}+impl Default for M3UParser {+ fn default() -> Self {+ Self::new()+ }+}+impl M3UParser {pub fn new() -> Self {- let mut cache_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));- cache_dir.push(".moviebox");+ let mut cache_dir = dirs::cache_dir().unwrap_or_else(|| PathBuf::from("."));+ cache_dir.push("moviebox-tui");cache_dir.push("tv_playlists");- fs::create_dir_all(&cache_dir).ok();+ std::fs::create_dir_all(&cache_dir).ok();Self { cache_dir }}- pub async fn fetch_playlist(&self, url: &str, filename: &str) -> Result<Vec<Channel>, Box<dyn std::error::Error>> {+ pub async fn fetch_playlist(+ &self,+ url: &str,+ filename: &str,+ ) -> Result<Vec<Channel>, Box<dyn std::error::Error>> {let file_path = self.cache_dir.join(filename);let mut needs_download = true;@@ -83,7 +93,7 @@ impl M3UParser {if let Some(caps) = group_title_re.captures(line) {current_channel.group = caps.get(1).map_or("", |m| m.as_str()).to_string();}-+if let Some(idx) = line.rfind(',') {current_channel.name = line[idx + 1..].trim().to_string();}diff --git a/src/providers/mod.rs b/src/providers/mod.rsindex d6b5b1a..a42d096 100644--- a/src/providers/mod.rs+++ b/src/providers/mod.rs@@ -1,2 +1,2 @@-pub mod moviebox;pub mod iptv_org;+pub mod moviebox;diff --git a/src/tui/app.rs b/src/tui/app.rsindex f3d15a2..47b8b73 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -336,11 +336,11 @@ impl App {{use chrono::Timelike;let hour = chrono::Local::now().hour();- let greeting_time = if hour >= 5 && hour < 12 {+ let greeting_time = if (5..12).contains(&hour) {"Good morning"- } else if hour >= 12 && hour < 17 {+ } else if (12..17).contains(&hour) {"Good afternoon"- } else if hour >= 17 && hour < 21 {+ } else if (17..21).contains(&hour) {"Good evening"} else {"Working late"@@ -400,7 +400,10 @@ impl App {} else {0};- animated_text = greeting.chars().take(display_len.min(greeting_len)).collect::<String>();+ animated_text = greeting+ .chars()+ .take(display_len.min(greeting_len))+ .collect::<String>();} else {let mut t = (tick_u - greeting_cycle) % total_ticks;for p in prompts.iter() {@@ -418,7 +421,8 @@ impl App {} else {0};- animated_text = p.chars().take(display_len.min(p_len)).collect::<String>();+ animated_text =+ p.chars().take(display_len.min(p_len)).collect::<String>();break;} else {t -= cycle;@@ -433,14 +437,16 @@ impl App {let current_query = self.state.search_query.trim().to_string();if current_query != self.state.last_suggest_query&& self.state.last_search_edit.elapsed()- >= std::time::Duration::from_millis(100)+ >= std::time::Duration::from_millis(350){self.state.last_suggest_query = current_query.clone();if !current_query.is_empty() {if self.state.is_tv_mode {-let q = current_query.to_lowercase();- self.state.search_suggestions = self.state.tv_channels.iter()+ self.state.search_suggestions = self+ .state+ .tv_channels+ .iter().filter(|c| c.name.to_lowercase().contains(&q)).take(10).map(|c| c.name.clone())@@ -578,9 +584,11 @@ impl App {Some(i) => i - 1,};self.state.suggest_index = Some(next_idx);- self.state.search_query =- self.state.search_suggestions[next_idx].clone();- self.state.last_suggest_query = self.state.search_query.trim().to_string();+ if let Some(sug) = self.state.search_suggestions.get(next_idx) {+ self.state.search_query = sug.clone();+ self.state.last_suggest_query =+ self.state.search_query.trim().to_string();+ }}KeyCode::Down if !self.state.search_suggestions.is_empty() => {let max_idx = self.state.search_suggestions.len() - 1;@@ -590,9 +598,11 @@ impl App {Some(i) => i + 1,};self.state.suggest_index = Some(next_idx);- self.state.search_query =- self.state.search_suggestions[next_idx].clone();- self.state.last_suggest_query = self.state.search_query.trim().to_string();+ if let Some(sug) = self.state.search_suggestions.get(next_idx) {+ self.state.search_query = sug.clone();+ self.state.last_suggest_query =+ self.state.search_query.trim().to_string();+ }}_ => {}},@@ -605,7 +615,11 @@ impl App {if self.state.tv_wizard_step == 1 {self.state.tv_wizard_step = 0;self.state.tv_wizard_selected_idx = 0;- self.state.tv_wizard_options = vec!["Grouped by category".to_string(), "Grouped by language".to_string(), "Grouped by broadcast area".to_string()];+ self.state.tv_wizard_options = vec![+ "Grouped by category".to_string(),+ "Grouped by language".to_string(),+ "Grouped by broadcast area".to_string(),+ ];} else {self.state.tv_config_popup = false;}@@ -614,11 +628,17 @@ impl App {if self.state.tv_wizard_selected_idx > 0 {self.state.tv_wizard_selected_idx -= 1;} else {- self.state.tv_wizard_selected_idx = self.state.tv_wizard_options.len().saturating_sub(1);+ self.state.tv_wizard_selected_idx = self+ .state+ .tv_wizard_options+ .len()+ .saturating_sub(1);}}KeyCode::Down => {- if self.state.tv_wizard_selected_idx < self.state.tv_wizard_options.len().saturating_sub(1) {+ if self.state.tv_wizard_selected_idx+ < self.state.tv_wizard_options.len().saturating_sub(1)+ {self.state.tv_wizard_selected_idx += 1;} else {self.state.tv_wizard_selected_idx = 0;@@ -626,63 +646,112 @@ impl App {}KeyCode::Char(' ') => {if self.state.tv_wizard_step == 1 {- let opt = self.state.tv_wizard_options[self.state.tv_wizard_selected_idx].clone();- if self.state.tv_wizard_selections.contains(&opt) {- self.state.tv_wizard_selections.remove(&opt);- } else {- self.state.tv_wizard_selections.insert(opt);+ if let Some(opt) = self+ .state+ .tv_wizard_options+ .get(self.state.tv_wizard_selected_idx)+ .cloned()+ {+ if self.state.tv_wizard_selections.contains(&opt) {+ self.state.tv_wizard_selections.remove(&opt);+ } else {+ self.state.tv_wizard_selections.insert(opt);+ }}}}KeyCode::Enter => {if self.state.tv_wizard_step == 0 {- let selected_group = self.state.tv_wizard_options[self.state.tv_wizard_selected_idx].clone();- self.state.tv_wizard_step = 1;- self.state.tv_wizard_selected_idx = 0;- if selected_group == "Grouped by category" {- self.state.tv_wizard_options = crate::tui::iptv_data::CATEGORIES.iter().map(|s| s.to_string()).collect();- } else if selected_group == "Grouped by language" {- self.state.tv_wizard_options = crate::tui::iptv_data::LANGUAGES.iter().map(|(n, _)| n.to_string()).collect();- } else {- self.state.tv_wizard_options = crate::tui::iptv_data::COUNTRIES.iter().map(|(n, _)| n.to_string()).collect();+ if let Some(selected_group) = self+ .state+ .tv_wizard_options+ .get(self.state.tv_wizard_selected_idx)+ .cloned()+ {+ self.state.tv_wizard_step = 1;+ self.state.tv_wizard_selected_idx = 0;+ if selected_group == "Grouped by category" {+ self.state.tv_wizard_options =+ crate::tui::iptv_data::CATEGORIES+ .iter()+ .map(|s| s.to_string())+ .collect();+ } else if selected_group == "Grouped by language" {+ self.state.tv_wizard_options =+ crate::tui::iptv_data::LANGUAGES+ .iter()+ .map(|(n, _)| n.to_string())+ .collect();+ } else {+ self.state.tv_wizard_options =+ crate::tui::iptv_data::COUNTRIES+ .iter()+ .map(|(n, _)| n.to_string())+ .collect();+ }}} else {self.state.tv_config_popup = false;-+self.state.is_loading = true;- self.state.status_message = "Fetching TV channels...".to_string();+ self.state.status_message =+ "Fetching TV channels...".to_string();self.state.status_timer = 150;-+let mut urls_to_fetch = Vec::new();for sel in &self.state.tv_wizard_selections {- if crate::tui::iptv_data::CATEGORIES.contains(&sel.as_str()) {+ if crate::tui::iptv_data::CATEGORIES+ .contains(&sel.as_str())+ {urls_to_fetch.push(format!("https://iptv-org.github.io/iptv/categories/{}.m3u", sel.to_lowercase()));- } else if let Some((_, code)) = crate::tui::iptv_data::LANGUAGES.iter().find(|(n, _)| n == sel) {+ } else if let Some((_, code)) =+ crate::tui::iptv_data::LANGUAGES+ .iter()+ .find(|(n, _)| n == sel)+ {urls_to_fetch.push(format!("https://iptv-org.github.io/iptv/languages/{}.m3u", code));- } else if let Some((_, code)) = crate::tui::iptv_data::COUNTRIES.iter().find(|(n, _)| n == sel) {+ } else if let Some((_, code)) =+ crate::tui::iptv_data::COUNTRIES+ .iter()+ .find(|(n, _)| n == sel)+ {urls_to_fetch.push(format!("https://iptv-org.github.io/iptv/countries/{}.m3u", code));}}-+let sender = self.action_sender.clone();tokio::spawn(async move {- let mut config_path = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("."));- config_path.push(".moviebox");+ let mut config_path = dirs::config_dir()+ .unwrap_or_else(|| {+ std::path::PathBuf::from(".")+ });+ config_path.push("moviebox-tui");std::fs::create_dir_all(&config_path).ok();config_path.push("tv_config.json");- if let Ok(json) = serde_json::to_string(&urls_to_fetch) {+ if let Ok(json) =+ serde_json::to_string(&urls_to_fetch)+ {std::fs::write(&config_path, json).ok();}- let parser = crate::providers::iptv_org::m3u::M3UParser::new();+ let parser =+ crate::providers::iptv_org::m3u::M3UParser::new(+ );let mut all_channels = Vec::new();for url in urls_to_fetch {- let filename = url.split('/').last().unwrap_or("playlist.m3u");- if let Ok(channels) = parser.fetch_playlist(&url, filename).await {+ let filename = url+ .split('/')+ .next_back()+ .unwrap_or("playlist.m3u");+ if let Ok(channels) =+ parser.fetch_playlist(&url, filename).await+ {all_channels.extend(channels);}}- sender.send(Action::TvChannelsLoaded(all_channels)).ok();+ sender+ .send(Action::TvChannelsLoaded(all_channels))+ .ok();});}}@@ -715,24 +784,32 @@ impl App {KeyCode::Char('q') => {self.action_sender.send(Action::Quit).ok();}- KeyCode::Char('r') => {- self.action_sender.send(Action::Refresh).ok();- }- KeyCode::Char('o') | KeyCode::Char('O') if self.state.input_mode == InputMode::Normal && self.state.is_tv_mode => {- let idx_opt = self.state.search_list_state.selected();- if let Some(idx) = idx_opt {- if let Some(item) = self.state.search_results.get(idx) {- self.action_sender.send(Action::ShowPlayerPicker(item.id.clone(), None)).ok();+ KeyCode::Char('r') => {+ self.action_sender.send(Action::Refresh).ok();+ }+ KeyCode::Char('o') | KeyCode::Char('O')+ if self.state.input_mode == InputMode::Normal+ && self.state.is_tv_mode =>+ {+ let idx_opt = self.state.search_list_state.selected();+ if let Some(idx) = idx_opt {+ if let Some(item) = self.state.search_results.get(idx) {+ self.action_sender+ .send(Action::ShowPlayerPicker(+ item.id.clone(),+ None,+ ))+ .ok();+ }}}- }KeyCode::Char(c)if (key.modifiers.is_empty()|| key.modifiers == KeyModifiers::SHIFT) =>{self.state.input_mode = InputMode::Editing;self.state.search_query.push(c);-+self.state.search_suggestions.clear();self.state.suggest_index = None;self.state.status_message = String::new();@@ -898,13 +975,14 @@ impl App {self.state.search_results.clear();self.state.status_message = "Initializing Moviebox TV Mode...".to_string();self.state.status_timer = 200;-+let sender = self.action_sender.clone();tokio::spawn(async move {- let mut config_path = dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("."));- config_path.push(".moviebox");+ let mut config_path =+ dirs::config_dir().unwrap_or_else(|| std::path::PathBuf::from("."));+ config_path.push("moviebox-tui");config_path.push("tv_config.json");-+let mut loaded_urls = Vec::new();if let Ok(content) = std::fs::read_to_string(&config_path) {if let Ok(urls) = serde_json::from_str::<Vec<String>>(&content) {@@ -918,7 +996,7 @@ impl App {let parser = crate::providers::iptv_org::m3u::M3UParser::new();let mut all_channels = Vec::new();for url in loaded_urls {- let filename = url.split('/').last().unwrap_or("playlist.m3u");+ let filename = url.split('/').next_back().unwrap_or("playlist.m3u");if let Ok(channels) = parser.fetch_playlist(&url, filename).await {all_channels.extend(channels);}@@ -944,7 +1022,8 @@ impl App {Action::TvChannelsLoaded(channels) => {self.state.tv_channels = channels;self.state.is_loading = false;- self.state.status_message = format!("Loaded {} TV channels.", self.state.tv_channels.len());+ self.state.status_message =+ format!("Loaded {} TV channels.", self.state.tv_channels.len());self.state.status_timer = 150;}Action::GoBack => {@@ -997,10 +1076,16 @@ impl App {let query = self.state.search_query.trim().to_string();if self.state.is_tv_mode {if query.is_empty() {- self.state.status_message = "TV Mode channels are loaded from local config.".to_string();+ self.state.status_message =+ "TV Mode channels are loaded from local config.".to_string();self.state.status_timer = 150;} else {- self.action_sender.send(Action::Search { query, force_refresh: true }).ok();+ self.action_sender+ .send(Action::Search {+ query,+ force_refresh: true,+ })+ .ok();}} else if !query.is_empty() {self.action_sender@@ -1065,17 +1150,19 @@ impl App {}Action::Suggest(query) => {if query.starts_with('/') {- let mut commands = vec![- "/discover",- "/movies",- "/tvshows",- "/search",- "/clear-cache",- "/quit",- ];+ let mut commands = vec!["/clear-cache", "/update", "/toggle-update", "/github"];if self.state.is_tv_mode {commands.push("/list");commands.push("/config");+ } else {+ commands.extend(vec![+ "/discover",+ "/home",+ "/movies",+ "/shows",+ "/tvshows",+ "/anime",+ ]);}let mut suggestions = vec![];for cmd in commands {@@ -1095,7 +1182,7 @@ impl App {}return None;}-+if self.state.is_tv_mode {return None;}@@ -1234,16 +1321,27 @@ impl App {self.state.search_query.clear();return None;}- if matches!(lower_query.as_str(), "/home" | "/discover" | "/movies" | "/shows" | "/anime") {- self.state.status_message = "Switch to streaming mode to use this command".to_string();+ if matches!(+ lower_query.as_str(),+ "/home" | "/discover" | "/movies" | "/shows" | "/tvshows" | "/anime"+ ) {+ self.state.status_message =+ "Switch to streaming mode to use this command".to_string();self.state.status_timer = 150;self.state.search_query.clear();return None;}let q = lower_query.clone();- self.state.search_results = self.state.tv_channels.iter()- .filter(|c| q == "/list" || c.name.to_lowercase().contains(&q) || c.group.to_lowercase().contains(&q))+ self.state.search_results = self+ .state+ .tv_channels+ .iter()+ .filter(|c| {+ q == "/list"+ || c.name.to_lowercase().contains(&q)+ || c.group.to_lowercase().contains(&q)+ }).map(|c| SearchResult {id: c.stream_url.clone(),title: c.name.clone(),@@ -1254,10 +1352,20 @@ impl App {}).collect();self.state.is_loading = false;- self.state.search_list_state.select(if self.state.search_results.is_empty() { None } else { Some(0) });-+ self.state+ .search_list_state+ .select(if self.state.search_results.is_empty() {+ None+ } else {+ Some(0)+ });+if !self.state.search_results.is_empty() {- let results_to_fetch = self.state.search_results.iter().take(15)+ let results_to_fetch = self+ .state+ .search_results+ .iter()+ .take(15).map(|r| (r.id.clone(), r.stype, r.cover_url.clone())).collect::<Vec<_>>();let sender = self.action_sender.clone();@@ -1266,17 +1374,33 @@ impl App {let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(4));for (id, _stype, cover_url) in results_to_fetch {if let Some(url) = cover_url {- if url.is_empty() { continue; }+ if url.is_empty() {+ continue;+ }let permit = sem.clone().acquire_owned().await.ok();let tx = sender.clone();let client = req_client.clone();tokio::spawn(async move {let _permit = permit;- if let Ok(resp) = client.get(&url).header("User-Agent", "MovieBox-Tui/1.0").send().await {+ if let Ok(resp) = client+ .get(&url)+ .header("User-Agent", "MovieBox-Tui/1.0")+ .send()+ .await+ {if let Ok(bytes) = resp.bytes().await {let bytes_clone = bytes.clone();- if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes_clone)).await {- tx.send(Action::SearchPosterLoaded(id, Some(std::sync::Arc::new(img)))).ok();+ if let Ok(Ok(img)) =+ tokio::task::spawn_blocking(move || {+ image::load_from_memory(&bytes_clone)+ })+ .await+ {+ tx.send(Action::SearchPosterLoaded(+ id,+ Some(std::sync::Arc::new(img)),+ ))+ .ok();}}}@@ -1291,7 +1415,7 @@ impl App {let tab_id = match lower_query.as_str() {"/home" | "/discover" => Some("0"),"/movies" => Some("2"),- "/shows" => Some("5"),+ "/shows" | "/tvshows" => Some("5"),"/anime" => Some("8"),_ => None,};@@ -1389,7 +1513,12 @@ impl App {tokio::spawn(async move {match client.get_homepage(&tab_id, page).await {Ok(res) => {- crate::cache::set_homepage_cache(&tab_id, page, &res);+ let r_clone = res.clone();+ let t_clone = tab_id.clone();+ let p_clone = page;+ tokio::task::spawn_blocking(move || {+ crate::cache::set_homepage_cache(&t_clone, p_clone, &r_clone);+ });sender.send(Action::HomepageSuccess {tab_id,@@ -1943,7 +2072,10 @@ impl App {.send(Action::FetchPreview(res.id.clone())).ok();}- } else if !self.state.is_tv_mode && !self.state.is_loading && !self.state.search_results.is_empty() {+ } else if !self.state.is_tv_mode+ && !self.state.is_loading+ && !self.state.search_results.is_empty()+ {let next_page = self.state.current_page + 1;if self.state.is_homepage_mode {self.action_sender@@ -2006,7 +2138,9 @@ impl App {crate::tui::state::DetailsPane::Episodes => {let current = self.state.episode_list_state.selected().unwrap_or(0);if let Some(season_idx) = self.state.season_list_state.selected() {- if let Some(ep_numbers) = self.state.available_episode_numbers.get(season_idx) {+ if let Some(ep_numbers) =+ self.state.available_episode_numbers.get(season_idx)+ {if current + 1 < ep_numbers.len() {self.state.episode_list_state.select(Some(current + 1));self.trigger_episode_fetch();@@ -2171,12 +2305,14 @@ impl App {let sub_name = self.state.subtitle_list.get(idx).map(|(n, _)| n.clone());let sub_url = self.state.subtitle_list.get(idx).map(|(_, u)| u.clone());let sub_url_final = sub_url.filter(|s| !s.is_empty());-+if self.state.download_queue_total > 0 {self.state.season_subtitle_preference = sub_name.filter(|n| n != "None");}-- self.action_sender.send(Action::DownloadStream(sub_url_final)).ok();++ self.action_sender+ .send(Action::DownloadStream(sub_url_final))+ .ok();return None;}if self.state.active_screen == Screen::Home {@@ -2185,7 +2321,9 @@ impl App {idx_opt.and_then(|idx| self.state.search_results.get(idx).cloned());if let Some(item) = item_opt {if self.state.is_tv_mode || item.stype == 3 {- self.action_sender.send(Action::LaunchMpv(item.id.clone(), None)).ok();+ self.action_sender+ .send(Action::LaunchMpv(item.id.clone(), None))+ .ok();return None;}self.state.active_screen = Screen::Details;@@ -2254,17 +2392,33 @@ impl App {if self.state.is_tv_mode {self.state.preview_loading = false;if !self.state.image_cache.contains(&id) {- if let Some(channel) = self.state.tv_channels.iter().find(|c| c.stream_url == id) {+ if let Some(channel) =+ self.state.tv_channels.iter().find(|c| c.stream_url == id)+ {let cover_url = channel.logo.clone();if !cover_url.is_empty() {let tx = self.action_sender.clone();let client = self.client.http_client().clone();let id2 = id.clone();tokio::spawn(async move {- if let Ok(resp) = client.get(&cover_url).header("User-Agent", "MovieBox-Tui/1.0").send().await {+ if let Ok(resp) = client+ .get(&cover_url)+ .header("User-Agent", "MovieBox-Tui/1.0")+ .send()+ .await+ {if let Ok(bytes) = resp.bytes().await {- if let Ok(Ok(img)) = tokio::task::spawn_blocking(move || image::load_from_memory(&bytes)).await {- tx.send(Action::SearchPosterLoaded(id2, Some(std::sync::Arc::new(img)))).ok();+ if let Ok(Ok(img)) =+ tokio::task::spawn_blocking(move || {+ image::load_from_memory(&bytes)+ })+ .await+ {+ tx.send(Action::SearchPosterLoaded(+ id2,+ Some(std::sync::Arc::new(img)),+ ))+ .ok();}}}@@ -2646,7 +2800,7 @@ impl App {.headers().get(reqwest::header::CONTENT_DISPOSITION).and_then(|v| v.to_str().ok())- .and_then(|s| s.split('.').last())+ .and_then(|s| s.split('.').next_back()).unwrap_or("mp4").to_string();(size, ranges, ext)@@ -2694,15 +2848,15 @@ impl App {}if let Some(sub_url) = subtitle_url {- let sub_ext = sub_url.split('.').last().unwrap_or("srt");+ let sub_ext = sub_url.split('.').next_back().unwrap_or("srt");let sub_ext = if sub_ext.len() <= 4 { sub_ext } else { "srt" };-+let mut sub_filename = filename.clone();if let Some(dot_idx) = sub_filename.rfind('.') {sub_filename.truncate(dot_idx);}sub_filename.push_str(&format!(".{}", sub_ext));-+let sub_target = target_dir.join(&sub_filename);let sub_client = client.clone();tokio::spawn(async move {@@ -3190,7 +3344,7 @@ impl App {Action::ConfirmDownloadEpisode => {self.state.show_episode_download_confirm = false;-+let subject_id = self.state.selected_details@@ -3234,16 +3388,16 @@ impl App {self.state.show_season_download_confirm = false;self.state.season_subtitle_preference = None;let season_num = self.state.selected_season;-+let season_array_idx = self.state.available_seasons.iter().position(|s| {s.get("se").and_then(|v| v.as_i64()).unwrap_or(0) as usize == season_num});-+if let Some(idx) = season_array_idx {if idx < self.state.available_episode_numbers.len() {let ep_numbers = self.state.available_episode_numbers[idx].clone();self.state.download_queue.clear();-+for ep in ep_numbers {self.state.download_queue.push_back((season_num, ep));}@@ -3284,10 +3438,8 @@ impl App {.and_then(|v| {if let Some(s) = v.as_str() {Some(s.to_string())- } else if let Some(n) = v.as_i64() {- Some(n.to_string())} else {- None+ v.as_i64().map(|n| n.to_string())}}).unwrap_or_default();@@ -3489,8 +3641,10 @@ impl App {self.state.status_timer = 150;}Action::InitStreamPool(subject_id) => {- let mut pool = crate::tui::state::SubjectStreamPool::default();- pool.available_resolutions = vec![];+ let pool = crate::tui::state::SubjectStreamPool {+ available_resolutions: vec![],+ ..Default::default()+ };self.state.stream_pool.insert(subject_id.clone(), pool);self.trigger_episode_fetch();@@ -3508,8 +3662,10 @@ impl App {});}Action::StreamPoolInitialized(subject_id, resolutions) => {- let mut pool = crate::tui::state::SubjectStreamPool::default();- pool.available_resolutions = resolutions;+ let pool = crate::tui::state::SubjectStreamPool {+ available_resolutions: resolutions,+ ..Default::default()+ };self.state.stream_pool.insert(subject_id.clone(), pool);let (se, ep) = if let Some(details) = &self.state.selected_details {@@ -3568,6 +3724,7 @@ impl App {} => {self.state.is_loading = true;self.state.is_fetching_streams = true;+ self.state.selected_resources = None;if let Some(pool) = self.state.stream_pool.get_mut(&subject_id) {if !force_refresh {@@ -3614,7 +3771,12 @@ impl App {.send(Action::SetStatus("Loaded from cache.".to_string())).ok();sender- .send(Action::EpisodeStreamsReady(subject_id.clone(), season, episode, cached))+ .send(Action::EpisodeStreamsReady(+ subject_id.clone(),+ season,+ episode,+ cached,+ )).ok();return;}@@ -3873,16 +4035,23 @@ impl App {if self.state.is_waiting_for_download_stream {self.state.is_waiting_for_download_stream = false;-+let is_season_queue = self.state.download_queue_total > 0;if is_season_queue {- let subject_id = self.state.selected_details.as_ref().and_then(|d| d.get("id")).and_then(|i| i.as_str()).unwrap_or("").to_string();+ let subject_id = self+ .state+ .selected_details+ .as_ref()+ .and_then(|d| d.get("id"))+ .and_then(|i| i.as_str())+ .unwrap_or("")+ .to_string();if let Some(rid) = self.get_selected_resource_id() {let client = self.client.clone();let sender = self.action_sender.clone();let pref = self.state.season_subtitle_preference.clone();let no_pref = pref.is_none();-+tokio::spawn(async move {if let Ok(res) = client.get_ext_captions(&subject_id, &rid).await {if no_pref {@@ -3891,7 +4060,10 @@ impl App {let mut sub_url = None;if let Some(list) = res.as_array() {for sub in list {- if let (Some(lang), Some(url)) = (sub.get("language").and_then(|l| l.as_str()), sub.get("url").and_then(|u| u.as_str())) {+ if let (Some(lang), Some(url)) = (+ sub.get("language").and_then(|l| l.as_str()),+ sub.get("url").and_then(|u| u.as_str()),+ ) {if lang == pref_lang {sub_url = Some(url.to_string());break;@@ -3908,7 +4080,7 @@ impl App {return None;}}-+self.action_sender.send(Action::DownloadStream(None)).ok();}}@@ -3980,7 +4152,9 @@ impl App {self.state.player_picker_popup = false;tokio::spawn(async move {let mut local_sub = sub.clone();- if kind == crate::tui::state::PlayerKind::Vlc || kind == crate::tui::state::PlayerKind::Iina {+ if kind == crate::tui::state::PlayerKind::Vlc+ || kind == crate::tui::state::PlayerKind::Iina+ {if let Some(s_url) = sub {if let Ok(resp) = reqwest::get(&s_url).await {if let Ok(bytes) = resp.bytes().await {@@ -3991,7 +4165,7 @@ impl App {.unwrap_or_default().as_millis()));- if std::fs::write(&temp_path, bytes).is_ok() {+ if tokio::fs::write(&temp_path, bytes).await.is_ok() {local_sub = Some(temp_path.to_string_lossy().to_string());}}@@ -4250,8 +4424,9 @@ impl App {self.state.updater_done = true;self.state.updater_progress = Some(1.0);- let exe = std::env::current_exe().unwrap();- let _ = std::process::Command::new(exe).spawn();+ if let Ok(exe) = std::env::current_exe() {+ let _ = std::process::Command::new(exe).spawn();+ }return Some(());}Action::UpdateFailure(_err) => {diff --git a/src/tui/event.rs b/src/tui/event.rsindex 53d32dd..595d649 100644--- a/src/tui/event.rs+++ b/src/tui/event.rs@@ -36,10 +36,8 @@ impl EventHandler {Ok(CrosstermEvent::FocusGained) => {let _ = event_sender.send(Action::FocusChange);}- Ok(CrosstermEvent::Resize(w, h)) => {- if event_sender.send(Action::Resize(w, h)).is_err() {- break;- }+ Ok(CrosstermEvent::Resize(w, h)) if event_sender.send(Action::Resize(w, h)).is_err() => {+ break;}_ => {}}diff --git a/src/tui/iptv_data.rs b/src/tui/iptv_data.rsindex 17606f3..6205b7c 100644--- a/src/tui/iptv_data.rs+++ b/src/tui/iptv_data.rs@@ -1,5 +1,38 @@-pub const CATEGORIES: &[&str] = &["Animation", "Auto", "Business", "Classic", "Comedy", "Cooking", "Culture", "Documentary", "Education", "Entertainment", "Family", "General", "Interactive", "Kids", "Legislative", "Lifestyle", "Movies", "Music", "News", "Outdoor", "Public", "Relax", "Religious", "Science", "Series", "Shop", "Sports", "Travel", "Weather", "XXX", "Undefined"];-pub const LANGUAGES: &[(&str, &str)] = &[ ("Ghotuo", "aaa"),+pub const CATEGORIES: &[&str] = &[+ "Animation",+ "Auto",+ "Business",+ "Classic",+ "Comedy",+ "Cooking",+ "Culture",+ "Documentary",+ "Education",+ "Entertainment",+ "Family",+ "General",+ "Interactive",+ "Kids",+ "Legislative",+ "Lifestyle",+ "Movies",+ "Music",+ "News",+ "Outdoor",+ "Public",+ "Relax",+ "Religious",+ "Science",+ "Series",+ "Shop",+ "Sports",+ "Travel",+ "Weather",+ "XXX",+ "Undefined",+];+pub const LANGUAGES: &[(&str, &str)] = &[+ ("Ghotuo", "aaa"),("Alumu-Tesu", "aab"),("Ari", "aac"),("Amal", "aad"),@@ -2605,7 +2638,10 @@ pub const LANGUAGES: &[(&str, &str)] = &[ ("Ghotuo", "aaa"),("Imroing", "imr"),("Marsian", "ims"),("Milyan", "imy"),- ("Interlingua (International Auxiliary Language Association)", "ina"),+ (+ "Interlingua (International Auxiliary Language Association)",+ "ina",+ ),("Inga", "inb"),("Indonesian", "ind"),("Degexit'an", "ing"),@@ -7893,7 +7929,8 @@ pub const LANGUAGES: &[(&str, &str)] = &[ ("Ghotuo", "aaa"),("Dimili", "zza"),("Zuojiang Zhuang", "zzj"),];-pub const COUNTRIES: &[(&str, &str)] = &[ ("Afghanistan", "af"),+pub const COUNTRIES: &[(&str, &str)] = &[+ ("Afghanistan", "af"),("Aland", "ax"),("Albania", "al"),("Algeria", "dz"),diff --git a/src/tui/mod.rs b/src/tui/mod.rsindex ae4cfb5..f0cb3ea 100644--- a/src/tui/mod.rs+++ b/src/tui/mod.rs@@ -1,7 +1,7 @@pub mod action;pub mod app;-pub mod iptv_data;pub mod event;+pub mod iptv_data;pub mod state;pub mod theme;pub mod screens {diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rsindex df406e5..a07f927 100644--- a/src/tui/screens/details.rs+++ b/src/tui/screens/details.rs@@ -818,7 +818,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let msg = if type_val == 2 {format!("Download Episode {} of Season {}?", ep_idx, season_idx)} else {- format!("Download this Movie?")+ "Download this Movie?".to_string()};let yes_text = if state.episode_download_confirm_yes_selected {diff --git a/src/tui/screens/help.rs b/src/tui/screens/help.rsindex 845b996..7762be1 100644--- a/src/tui/screens/help.rs+++ b/src/tui/screens/help.rs@@ -42,22 +42,67 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {Span::styled("Select / Submit", theme.text),]),Line::from(vec![]),- Line::from(vec![Span::styled(- " Stream Controls",- theme.header.add_modifier(ratatui::style::Modifier::BOLD),- )]),- Line::from(vec![- Span::styled(" [Enter] ", theme.header),- Span::styled(if state.is_tv_mode { "Play Channel" } else { "Play with default player" }, theme.text),- ]),];- if !state.is_tv_mode {- help_text.splice(44..44, vec![+ if state.is_tv_mode {+ help_text.extend(vec![+ Line::from(vec![Span::styled(+ " TV Controls",+ theme.header.add_modifier(ratatui::style::Modifier::BOLD),+ )]),+ Line::from(vec![+ Span::styled(" [Enter] ", theme.header),+ Span::styled("Play Channel", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" /list ", theme.header),+ Span::styled("Show Available Channels", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" /config ", theme.header),+ Span::styled("Open TV Config Popup", theme.text),+ ]),+ Line::from(vec![]),+ Line::from(vec![Span::styled(+ " System",+ theme.header.add_modifier(ratatui::style::Modifier::BOLD),+ )]),+ Line::from(vec![+ Span::styled(" [r] ", theme.header),+ Span::styled("Refresh Channels/Search", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" /clear-cache ", theme.header),+ Span::styled("Clear App Cache", theme.text),+ ]),+ ]);+ } else {+ help_text.extend(vec![+ Line::from(vec![Span::styled(+ " Playback & Download",+ theme.header.add_modifier(ratatui::style::Modifier::BOLD),+ )]),+ Line::from(vec![+ Span::styled(" [Enter] ", theme.header),+ Span::styled("Play with Default Player", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" [o] ", theme.header),+ Span::styled("Open Player Picker", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" [d] ", theme.header),+ Span::styled("Download Video", theme.text),+ ]),+ Line::from(vec![]),Line::from(vec![Span::styled(" Discover & Search",theme.header.add_modifier(ratatui::style::Modifier::BOLD),)]),+ Line::from(vec![+ Span::styled(" /home ", theme.header),+ Span::styled("Trending & Featured", theme.text),+ ]),Line::from(vec![Span::styled(" /discover ", theme.header),Span::styled("Trending & Featured", theme.text),@@ -78,62 +123,30 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {Span::styled(" /github ", theme.header),Span::styled("Open GitHub Repo", theme.text),]),- Line::from(vec![- Span::styled(" /update ", theme.header),- Span::styled("Check for updates", theme.text),- ]),- Line::from(vec![- Span::styled(" /toggle-update ", theme.header),- Span::styled("Toggle auto updates", theme.text),- ]),- Line::from(vec![- Span::styled(" /clear-cache ", theme.header),- Span::styled("Clear app cache", theme.text),- ]),Line::from(vec![]),- ]);-- help_text.extend(vec![- Line::from(vec![- Span::styled(" [o] ", theme.header),- Span::styled("Open Player Picker", theme.text),- ]),- Line::from(vec![- Span::styled(" [d] ", theme.header),- Span::styled("Download Video", theme.text),- ]),- ]);- }-- if state.is_tv_mode {- help_text.extend(vec![Line::from(vec![Span::styled(- " TV Commands",+ " System",theme.header.add_modifier(ratatui::style::Modifier::BOLD),)]),Line::from(vec![- Span::styled(" /list ", theme.header),- Span::styled("Show available channels", theme.text),+ Span::styled(" [r] ", theme.header),+ Span::styled("Refresh Streams/Search", theme.text),]),Line::from(vec![- Span::styled(" /config ", theme.header),- Span::styled("Open TV Config Popup", theme.text),+ Span::styled(" /update ", theme.header),+ Span::styled("Check for Updates", theme.text),+ ]),+ Line::from(vec![+ Span::styled(" /toggle-update ", theme.header),+ Span::styled("Toggle Auto Updates", theme.text),]),Line::from(vec![Span::styled(" /clear-cache ", theme.header),- Span::styled("Clear app cache", theme.text),+ Span::styled("Clear App Cache", theme.text),]),- Line::from(vec![]),]);}- help_text.extend(vec![- Line::from(vec![- Span::styled(" [r] ", theme.header),- Span::styled("Refresh Streams/Search", theme.text),- ]),- ]);-let height = help_text.len() as u16 + 2;let margin_y = area.height.saturating_sub(height) / 2;diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex fe9fe51..f01c506 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -20,19 +20,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)if state.input_mode == InputMode::Editing {if show_cursor {- format!(- "{}{}{}█",- search_prefix,- animated_text,- if animated_text.is_empty() { "" } else { "" }- )+ format!("{}{}{}█", search_prefix, animated_text, "")} else {- format!(- "{}{}{} ",- search_prefix,- animated_text,- if animated_text.is_empty() { "" } else { "" }- )+ format!("{}{}{} ", search_prefix, animated_text, "")}} else {if show_cursor {@@ -86,26 +76,30 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)██╔████╔██║ ██║ ██║ ██║ ██║ ██║ █████╗ ██████╔╝ ██║ ██║ ╚███╔╝██║╚██╔╝██║ ██║ ██║ ╚██╗ ██╔╝ ██║ ██╔══╝ ██╔══██╗ ██║ ██║ ██╔██╗ TV██║ ╚═╝ ██║ ╚██████╔╝ ╚████╔╝ ██║ ███████╗ ██████╔╝ ╚██████╔╝ ██╔╝ ██╗-╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝".to_string()+╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"+ .to_string()} else {r"███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ███████╗ ██████╗ ██████╗ ██╗ ██╗████╗ ████║ ██╔═══██╗ ██║ ██║ ██║ ██╔════╝ ██╔══██╗ ██╔═══██╗ ╚██╗██╔╝██╔████╔██║ ██║ ██║ ██║ ██║ ██║ █████╗ ██████╔╝ ██║ ██║ ╚███╔╝██║╚██╔╝██║ ██║ ██║ ╚██╗ ██╔╝ ██║ ██╔══╝ ██╔══██╗ ██║ ██║ ██╔██╗██║ ╚═╝ ██║ ╚██████╔╝ ╚████╔╝ ██║ ███████╗ ██████╔╝ ╚██████╔╝ ██╔╝ ██╗-╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝".to_string()+╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"+ .to_string()}} else {if state.is_tv_mode {r" __ __ ___ __ __ ___ ___ ___ ___ __ __| \/ |/ _ \ \ \ / /|_ _|| __|| _ ) / _ \ \ \/ /| |\/| | (_) | \ V / | | | _| | _ \| (_) | > < TV- |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ ".to_string()+ |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ "+ .to_string()} else {r" __ __ ___ __ __ ___ ___ ___ ___ __ __| \/ |/ _ \ \ \ / /|_ _|| __|| _ ) / _ \ \ \/ /| |\/| | (_) | \ V / | | | _| | _ \| (_) | > <- |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ ".to_string()+ |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ "+ .to_string()}};@@ -117,8 +111,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)if state.is_tv_mode { 57 } else { 55 }};--let vertical_chunks = Layout::default().direction(Direction::Vertical).constraints([@@ -217,16 +209,33 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)}let legend_line = ratatui::text::Line::from(vec![- ratatui::text::Span::styled("[Ctrl+T] ", theme.shortcut),- ratatui::text::Span::styled(if state.is_tv_mode { "TV Mode " } else { "Streaming Mode " }, theme.text_dim),- ratatui::text::Span::styled("[Type] ", theme.shortcut),- ratatui::text::Span::styled("Search ", theme.text_dim),- ratatui::text::Span::styled("[↑↓] ", theme.shortcut),- ratatui::text::Span::styled("Browse ", theme.text_dim),- ratatui::text::Span::styled("[?] ", theme.shortcut),- ratatui::text::Span::styled("Help ", theme.text_dim),- ratatui::text::Span::styled("[Esc] ", theme.shortcut),- ratatui::text::Span::styled("Quit", theme.text_dim),+ ratatui::text::Span::styled("[", theme.text_dim),+ ratatui::text::Span::styled("Ctrl+T", theme.shortcut),+ ratatui::text::Span::styled("] ", theme.text_dim),+ ratatui::text::Span::styled(+ if state.is_tv_mode {+ "TV Mode "+ } else {+ "Streaming Mode "+ },+ theme.text,+ ),+ ratatui::text::Span::styled("[", theme.text_dim),+ ratatui::text::Span::styled("Type", theme.shortcut),+ ratatui::text::Span::styled("] ", theme.text_dim),+ ratatui::text::Span::styled("Search ", theme.text),+ ratatui::text::Span::styled("[", theme.text_dim),+ ratatui::text::Span::styled("↑↓", theme.shortcut),+ ratatui::text::Span::styled("] ", theme.text_dim),+ ratatui::text::Span::styled("Browse ", theme.text),+ ratatui::text::Span::styled("[", theme.text_dim),+ ratatui::text::Span::styled("?", theme.shortcut),+ ratatui::text::Span::styled("] ", theme.text_dim),+ ratatui::text::Span::styled("Help ", theme.text),+ ratatui::text::Span::styled("[", theme.text_dim),+ ratatui::text::Span::styled("q", theme.shortcut),+ ratatui::text::Span::styled("] ", theme.text_dim),+ ratatui::text::Span::styled("Quit", theme.text),]);let legend = Paragraph::new(legend_line).alignment(Alignment::Center);@@ -341,11 +350,10 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let row_height = state.poster_rows;state.visible_items = (chunks[1].height as usize) / (row_height as usize);- let rows: Vec<Row> = state+ let rows = state.search_results.iter()- .map(|_| Row::new(vec![Cell::from("")]).height(row_height))- .collect();+ .map(|_| Row::new(vec![Cell::from("")]).height(row_height));let table = Table::new(rows, [Constraint::Percentage(100)]).block(list_block);@@ -421,7 +429,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)if state.image_supported {let target_dims = (poster_area.width, state.poster_rows);let needs_protocol =- state.search_poster_protocols.get(&res.id).map(|(d, _)| *d)+ state.search_poster_protocols.peek(&res.id).map(|(d, _)| *d)!= Some(target_dims);if needs_protocol {if let Some(picker) = &mut state.image_picker {@@ -433,11 +441,11 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)) {state.search_poster_protocols- .insert(res.id.clone(), (target_dims, proto));+ .put(res.id.clone(), (target_dims, proto));}}}- if let Some((_, proto)) = state.search_poster_protocols.get(&res.id) {+ if let Some((_, proto)) = state.search_poster_protocols.peek(&res.id) {let p_area = Rect {height: poster_area.height.min(state.poster_rows),..poster_area@@ -661,7 +669,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let content_height = state.tv_wizard_options.len() as u16;let max_height = area.height.saturating_sub(17).max(6);let popup_height = (content_height + 4).clamp(6, max_height);-+let popup_area = ratatui::layout::Rect {x: area.width.saturating_sub(44) / 2,y: 13.min(area.height.saturating_sub(popup_height)),@@ -669,60 +677,76 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)height: popup_height,};let popup_block = ratatui::widgets::Block::default()- .title(if state.tv_wizard_step == 0 { " TV Setup: Select Grouping " } else { " TV Setup: Select Items " })+ .title(if state.tv_wizard_step == 0 {+ " TV Setup: Select Grouping "+ } else {+ " TV Setup: Select Items "+ }).title_alignment(ratatui::layout::Alignment::Center).borders(ratatui::widgets::Borders::ALL).border_type(ratatui::widgets::BorderType::Rounded).border_style(theme.border_focus).style(ratatui::style::Style::default());-+let inner_area = popup_block.inner(popup_area);frame.render_widget(popup_block, popup_area);- let items: Vec<ratatui::widgets::ListItem> = state.tv_wizard_options.iter().map(|opt| {- let is_checked = state.tv_wizard_selections.contains(opt);-- let checkbox = if state.tv_wizard_step == 1 {- if is_checked { "[x] " } else { "[ ] " }- } else {- ""- };-- let line = ratatui::text::Line::from(vec![- ratatui::text::Span::styled(format!("{}{}", checkbox, opt), theme.text)- ]);- ratatui::widgets::ListItem::new(line)- }).collect();+ let items: Vec<ratatui::widgets::ListItem> = state+ .tv_wizard_options+ .iter()+ .map(|opt| {+ let is_checked = state.tv_wizard_selections.contains(opt);++ let checkbox = if state.tv_wizard_step == 1 {+ if is_checked { "[x] " } else { "[ ] " }+ } else {+ ""+ };++ let line = ratatui::text::Line::from(vec![ratatui::text::Span::styled(+ format!("{}{}", checkbox, opt),+ theme.text,+ )]);+ ratatui::widgets::ListItem::new(line)+ })+ .collect();let list = ratatui::widgets::List::new(items)- .highlight_style(- theme.highlight.add_modifier(ratatui::style::Modifier::BOLD)- )+ .highlight_style(theme.highlight.add_modifier(ratatui::style::Modifier::BOLD)).highlight_symbol(if state.basic_terminal { "> " } else { "▌ " });-+let mut list_area = inner_area;list_area.height = list_area.height.saturating_sub(1);-+let mut list_state = ratatui::widgets::ListState::default();list_state.select(Some(state.tv_wizard_selected_idx));-+frame.render_stateful_widget(list, list_area, &mut list_state);- let scrollbar = ratatui::widgets::Scrollbar::new(ratatui::widgets::ScrollbarOrientation::VerticalRight)- .begin_symbol(Some("▲"))- .end_symbol(Some("▼"))- .track_symbol(Some("│"))- .thumb_symbol("█");-- let mut scrollbar_state = ratatui::widgets::ScrollbarState::new(state.tv_wizard_options.len().saturating_sub(list_area.height as usize))- .position(list_state.offset());-+ let scrollbar =+ ratatui::widgets::Scrollbar::new(ratatui::widgets::ScrollbarOrientation::VerticalRight)+ .begin_symbol(Some("▲"))+ .end_symbol(Some("▼"))+ .track_symbol(Some("│"))+ .thumb_symbol("█");++ let mut scrollbar_state = ratatui::widgets::ScrollbarState::new(+ state+ .tv_wizard_options+ .len()+ .saturating_sub(list_area.height as usize),+ )+ .position(list_state.offset());+frame.render_stateful_widget(scrollbar,- list_area.inner(ratatui::layout::Margin { vertical: 0, horizontal: 0 }),+ list_area.inner(ratatui::layout::Margin {+ vertical: 0,+ horizontal: 0,+ }),&mut scrollbar_state,);-+let hint_area = ratatui::layout::Rect {x: inner_area.x,y: inner_area.y + inner_area.height.saturating_sub(1),@@ -738,7 +762,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)ratatui::widgets::Paragraph::new(hint).alignment(ratatui::layout::Alignment::Center).style(theme.text_dim),- hint_area+ hint_area,);}diff --git a/src/tui/state.rs b/src/tui/state.rsindex 34aa647..74221fe 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -63,7 +63,7 @@ pub struct AppState {pub cached_animated_text: String,pub search_posters: lru::LruCache<String, std::sync::Arc<image::DynamicImage>>,pub search_poster_protocols:- std::collections::HashMap<String, ((u16, u16), ratatui_image::protocol::Protocol)>,+ lru::LruCache<String, ((u16, u16), ratatui_image::protocol::Protocol)>,pub search_list_state: TableState,pub selected_details: Option<serde_json::Value>,@@ -143,7 +143,6 @@ pub struct AppState {pub basic_terminal: bool,pub username: String,-pub is_tv_mode: bool,pub tv_config_popup: bool,pub tv_channels: Vec<crate::providers::iptv_org::m3u::Channel>,@@ -169,7 +168,7 @@ impl Default for AppState {current_tab_id: String::new(),current_page: 1,search_posters: lru::LruCache::new(std::num::NonZeroUsize::new(30).unwrap()),- search_poster_protocols: std::collections::HashMap::new(),+ search_poster_protocols: lru::LruCache::new(std::num::NonZeroUsize::new(30).unwrap()),search_list_state: TableState::default(),basic_terminal: {let term = std::env::var("TERM").unwrap_or_default();@@ -215,13 +214,11 @@ impl Default for AppState {image_supported: {let term = std::env::var("TERM").unwrap_or_default();let term_program = std::env::var("TERM_PROGRAM").unwrap_or_default();- if term_program == "Apple_Terminal" || term == "dumb" || term == "linux" {- false- } else if std::env::var("TMUX").is_ok() || std::env::var("SSH_TTY").is_ok() {- false- } else {- true- }+ !(term_program == "Apple_Terminal"+ || term == "dumb"+ || term == "linux"+ || std::env::var("TMUX").is_ok()+ || std::env::var("SSH_TTY").is_ok())},poster_rows: 3,image_cache: lru::LruCache::new(std::num::NonZeroUsize::new(10).unwrap()),@@ -266,16 +263,19 @@ impl Default for AppState {.or_else(|_| std::env::var("USERNAME")).unwrap_or_else(|_| "Friend".to_string()).split('\\')- .last()+ .next_back().unwrap_or("Friend").to_string(),-is_tv_mode: false,tv_config_popup: false,tv_channels: Vec::new(),tv_wizard_step: 0,- tv_wizard_options: vec!["Grouped by category".to_string(), "Grouped by language".to_string(), "Grouped by broadcast area".to_string()],+ tv_wizard_options: vec![+ "Grouped by category".to_string(),+ "Grouped by language".to_string(),+ "Grouped by broadcast area".to_string(),+ ],tv_wizard_selected_idx: 0,tv_wizard_selections: std::collections::HashSet::new(),}