Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
feat: implement IPTV mode with channel fetching and selection wizard
Samir Hossainsba664e88a573
diff --git a/Cargo.lock b/Cargo.lockindex f03b756..d84669d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1969,6 +1969,7 @@ dependencies = ["rand 0.10.2","ratatui","ratatui-image",+ "regex","reqwest","self_update","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 34fb700..0b35564 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -26,6 +26,7 @@ open = "5.4.0"rand = "0.10.2"ratatui = "0.30.2"ratatui-image = { version = "11.0.6", default-features = false, features = ["crossterm", "image-defaults"] }+regex = "1.13.1"reqwest = { version = "0.13.4", default-features = false, features = ["json", "rustls"] }self_update = { version = "0.44.0", default-features = false, features = ["archive-tar", "archive-zip", "rustls", "reqwest"] }serde = { version = "1.0.228", features = ["derive"] }diff --git a/src/cache.rs b/src/cache.rsindex 22003d1..6b08093 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -2,7 +2,7 @@ use std::fs;use std::path::PathBuf;use std::time::SystemTime;-const CACHE_EXPIRY_SECS: u64 = 24 * 60 * 60; // 24 hours+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());diff --git a/src/providers/iptv_org/m3u.rs b/src/providers/iptv_org/m3u.rsnew file mode 100644index 0000000..4ab51c7--- /dev/null+++ b/src/providers/iptv_org/m3u.rs@@ -0,0 +1,109 @@+use std::path::PathBuf;+use std::fs;+use std::time::SystemTime;+use serde::{Deserialize, Serialize};+use regex::Regex;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Channel {+ pub id: String,+ pub name: String,+ pub logo: String,+ pub group: String,+ pub stream_url: String,+}++pub struct M3UParser {+ cache_dir: PathBuf,+}++impl M3UParser {+ pub fn new() -> Self {+ let mut cache_dir = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));+ cache_dir.push(".moviebox");+ cache_dir.push("tv_playlists");+ 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>> {+ let file_path = self.cache_dir.join(filename);+ let mut needs_download = true;++ if file_path.exists() {+ if let Ok(metadata) = fs::metadata(&file_path) {+ if let Ok(modified) = metadata.modified() {+ if let Ok(duration) = SystemTime::now().duration_since(modified) {+ if duration.as_secs() < 24 * 3600 {+ needs_download = false;+ }+ }+ }+ }+ }++ let content = if needs_download {+ let client = reqwest::Client::new();+ let res = client.get(url).send().await?.text().await?;+ fs::write(&file_path, &res).ok();+ res+ } else {+ fs::read_to_string(&file_path)?+ };++ Ok(self.parse_m3u(&content))+ }++ fn parse_m3u(&self, content: &str) -> Vec<Channel> {+ let mut channels = Vec::new();+ let mut current_channel = Channel {+ id: String::new(),+ name: String::new(),+ logo: String::new(),+ group: String::new(),+ stream_url: String::new(),+ };++ let tvg_id_re = Regex::new(r#"tvg-id="([^"]*)""#).unwrap();+ let tvg_logo_re = Regex::new(r#"tvg-logo="([^"]*)""#).unwrap();+ let group_title_re = Regex::new(r#"group-title="([^"]*)""#).unwrap();++ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() {+ continue;+ }+ if line.starts_with("#EXTINF:") {+ if let Some(caps) = tvg_id_re.captures(line) {+ current_channel.id = caps.get(1).map_or("", |m| m.as_str()).to_string();+ }+ if let Some(caps) = tvg_logo_re.captures(line) {+ current_channel.logo = caps.get(1).map_or("", |m| m.as_str()).to_string();+ }+ 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();+ }+ } else if !line.starts_with('#') {+ current_channel.stream_url = line.to_string();+ if current_channel.id.is_empty() {+ current_channel.id = current_channel.name.clone();+ }+ channels.push(current_channel.clone());++ current_channel = Channel {+ id: String::new(),+ name: String::new(),+ logo: String::new(),+ group: String::new(),+ stream_url: String::new(),+ };+ }+ }++ channels+ }+}diff --git a/src/providers/iptv_org/mod.rs b/src/providers/iptv_org/mod.rsnew file mode 100644index 0000000..b206bd7--- /dev/null+++ b/src/providers/iptv_org/mod.rs@@ -0,0 +1 @@+pub mod m3u;diff --git a/src/providers/mod.rs b/src/providers/mod.rsindex 9169905..d6b5b1a 100644--- a/src/providers/mod.rs+++ b/src/providers/mod.rs@@ -1 +1,2 @@pub mod moviebox;+pub mod iptv_org;diff --git a/src/tui/action.rs b/src/tui/action.rsindex ab13b10..7a45bcd 100644--- a/src/tui/action.rs+++ b/src/tui/action.rs@@ -10,6 +10,8 @@ pub enum Action {SelectLanguage(usize),Resize(u16, u16),ToggleHelp,+ ToggleTvMode,+ TvChannelsLoaded(Vec<crate::providers::iptv_org::m3u::Channel>),Search {query: String,force_refresh: bool,diff --git a/src/tui/app.rs b/src/tui/app.rsindex e908084..f576dcb 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -426,7 +426,17 @@ impl App {{self.state.last_suggest_query = current_query.clone();if !current_query.is_empty() {- self.action_sender.send(Action::Suggest(current_query)).ok();+ if self.state.is_tv_mode {++ let q = current_query.to_lowercase();+ self.state.search_suggestions = self.state.tv_channels.iter()+ .filter(|c| c.name.to_lowercase().contains(&q))+ .take(10)+ .map(|c| c.name.clone())+ .collect();+ } else {+ self.action_sender.send(Action::Suggest(current_query)).ok();+ }} else {self.state.search_suggestions.clear();}@@ -495,6 +505,10 @@ impl App {self.action_sender.send(Action::Quit).ok();return Some(());}+ if let KeyCode::Char('t') = key.code {+ self.action_sender.send(Action::ToggleTvMode).ok();+ return None;+ }}if let KeyCode::Char('x') | KeyCode::Char('X') = key.code@@ -571,48 +585,112 @@ impl App {},InputMode::Normal => match self.state.active_screen {Screen::Startup => {}- Screen::Home => match key.code {- KeyCode::Esc => {- self.action_sender.send(Action::GoBack).ok();- }- KeyCode::Up => {- self.action_sender.send(Action::MoveUp).ok();- }- KeyCode::Down => {- self.action_sender.send(Action::MoveDown).ok();- }- KeyCode::Left => {- self.action_sender.send(Action::MoveLeft).ok();- }- KeyCode::Right => {- self.action_sender.send(Action::MoveRight).ok();- }- KeyCode::Enter => {- self.action_sender.send(Action::Submit).ok();- }- KeyCode::Char('?') => {- self.action_sender.send(Action::ToggleHelp).ok();- }- KeyCode::Char('q') => {- self.action_sender.send(Action::Quit).ok();+ Screen::Home => {+ if self.state.tv_config_popup {+ match key.code {+ KeyCode::Esc => {+ if self.state.tv_wizard_step == 1 {+ self.state.tv_wizard_step = 0;+ self.state.tv_wizard_selected_idx = 0;+ } else {+ self.state.tv_config_popup = false;+ self.state.is_tv_mode = false;+ }+ }+ KeyCode::Up => {+ 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);+ }+ }+ KeyCode::Down => {+ 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;+ }+ }+ 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);+ }+ }+ }+ KeyCode::Enter => {+ if self.state.tv_wizard_step == 0 {+ self.state.tv_wizard_step = 1;+ self.state.tv_wizard_selected_idx = 0;+ self.state.tv_wizard_options = vec!["us".to_string(), "uk".to_string(), "ca".to_string(), "news".to_string(), "sports".to_string()];+ } else {+ self.state.tv_config_popup = false;++ self.state.is_loading = true;+ self.state.status_message = "Fetching TV channels...".to_string();+ self.state.status_timer = 150;++ let sender = self.action_sender.clone();+ tokio::spawn(async move {+ let parser = crate::providers::iptv_org::m3u::M3UParser::new();+ let mut all_channels = Vec::new();+ if let Ok(channels) = parser.fetch_playlist("https://iptv-org.github.io/iptv/countries/us.m3u", "us.m3u").await {+ all_channels.extend(channels);+ }+ sender.send(Action::TvChannelsLoaded(all_channels)).ok();+ });+ }+ }+ _ => {}+ }+ return None;}+ match key.code {+ KeyCode::Esc => {+ self.action_sender.send(Action::GoBack).ok();+ }+ KeyCode::Up => {+ self.action_sender.send(Action::MoveUp).ok();+ }+ KeyCode::Down => {+ self.action_sender.send(Action::MoveDown).ok();+ }+ KeyCode::Left => {+ self.action_sender.send(Action::MoveLeft).ok();+ }+ KeyCode::Right => {+ self.action_sender.send(Action::MoveRight).ok();+ }+ KeyCode::Enter => {+ self.action_sender.send(Action::Submit).ok();+ }+ KeyCode::Char('?') => {+ self.action_sender.send(Action::ToggleHelp).ok();+ }+ KeyCode::Char('q') => {+ self.action_sender.send(Action::Quit).ok();+ }KeyCode::Char('r') => {self.action_sender.send(Action::Refresh).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();- self.state.status_timer = 150;+ 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();+ self.state.status_timer = 150;+ }+ _ => {}}- _ => {}- },+ }Screen::Details => match key.code {KeyCode::Char('y') | KeyCode::Char('Y') => {if self.state.show_season_download_confirm {@@ -760,6 +838,39 @@ impl App {self.state.show_help = !self.state.show_help;}}+ Action::ToggleTvMode => {+ self.state.is_tv_mode = !self.state.is_tv_mode;+ if self.state.is_tv_mode {+ self.state.tv_config_popup = true;+ self.state.search_query.clear();+ self.state.search_results.clear();+ } else {+ self.state.tv_config_popup = false;+ self.state.search_query.clear();+ self.state.search_results.clear();+ }+ }+ 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_timer = 150;++++ self.state.search_results = self.state.tv_channels.iter()+ .take(20)+ .map(|c| SearchResult {+ id: c.id.clone(),+ title: c.name.clone(),+ stype: 1,+ release_year: c.group.clone(),+ cover_url: Some(c.logo.clone()),+ season: 1,+ })+ .collect();+ self.state.search_list_state.select(if self.state.search_results.is_empty() { None } else { Some(0) });+ }Action::GoBack => {if self.state.player_picker_popup {self.state.player_picker_popup = false;@@ -970,6 +1081,24 @@ impl App {query,force_refresh,} => {+ if self.state.is_tv_mode {+ let q = query.to_lowercase();+ self.state.search_results = self.state.tv_channels.iter()+ .filter(|c| c.name.to_lowercase().contains(&q) || c.group.to_lowercase().contains(&q))+ .map(|c| SearchResult {+ id: c.id.clone(),+ title: c.name.clone(),+ stype: 1,+ release_year: c.group.clone(),+ cover_url: Some(c.logo.clone()),+ season: 1,+ })+ .collect();+ self.state.is_loading = false;+ self.state.search_list_state.select(if self.state.search_results.is_empty() { None } else { Some(0) });+ return None;+ }+let lower_query = query.trim().to_lowercase();if lower_query == "/github" {let _ = open::that("https://github.com/mesamirh/MovieBox-Tui");@@ -1334,6 +1463,7 @@ impl App {}}}+Action::SearchFailure(err) => {self.state.is_loading = false;self.state.status_message = format!("Search failed: {}", err);@@ -1944,6 +2074,14 @@ impl App {}}Action::FetchDetails(id, force_refresh) => {+ if self.state.is_tv_mode {+ if let Some(channel) = self.state.tv_channels.iter().find(|c| c.id == id) {+ let stream_url = channel.stream_url.clone();+ self.action_sender.send(Action::ShowPlayerPicker(stream_url, Some(channel.name.clone()))).ok();+ }+ return None;+ }+self.state.poster_protocol = None;self.state.is_loading = true;self.state@@ -3624,8 +3762,7 @@ impl App {self.state.download_status = stat;self.state.dirty = true;}- // If the download just finished (cleared to None) and there are more items in queue,- // automatically trigger the next download in the sequence.+if prog.is_none() && !self.state.download_queue.is_empty() {self.action_sender.send(Action::ProcessDownloadQueue).ok();}diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex 2fb428e..5570e74 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -65,7 +65,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let is_narrow = area.width < 60 || state.basic_terminal;let is_wide = area.width >= 100 && !state.basic_terminal;- let logo_height = if is_narrow {+ let mut logo_height = if is_narrow {2} else if is_wide {6@@ -73,22 +73,40 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)4};- let logo_text = if is_narrow {- "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █"+ if state.is_tv_mode {+ logo_height += 1;+ }++ let mut logo_text = if is_narrow {+ "█▀▄▀█ █▀█ █ █ █ █▀▀ █▀▄ █▀█ ▀▄▀\n█ ▀ █ █▄█ ▀▄▀ █ ██▄ █▄▀ █▄█ █ █".to_string()} else if is_wide {r"███╗ ███╗ ██████╗ ██╗ ██╗ ██╗ ███████╗ ██████╗ ██████╗ ██╗ ██╗████╗ ████║ ██╔═══██╗ ██║ ██║ ██║ ██╔════╝ ██╔══██╗ ██╔═══██╗ ╚██╗██╔╝██╔████╔██║ ██║ ██║ ██║ ██║ ██║ █████╗ ██████╔╝ ██║ ██║ ╚███╔╝██║╚██╔╝██║ ██║ ██║ ╚██╗ ██╔╝ ██║ ██╔══╝ ██╔══██╗ ██║ ██║ ██╔██╗██║ ╚═╝ ██║ ╚██████╔╝ ╚████╔╝ ██║ ███████╗ ██████╔╝ ╚██████╔╝ ██╔╝ ██╗-╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"+╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚═╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝".to_string()} else {r" __ __ ___ __ __ ___ ___ ___ ___ __ __| \/ |/ _ \ \ \ / /|_ _|| __|| _ ) / _ \ \ \/ /| |\/| | (_) | \ V / | | | _| | _ \| (_) | > <- |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ "+ |_| |_|\___/ \_/ |___||___||___/ \___/ /_/\_\ ".to_string()};+ let logo_width: u16 = if is_narrow {+ 31+ } else if is_wide {+ 73+ } else {+ 55+ };++ if state.is_tv_mode {+ let padding = logo_width.saturating_sub(11) / 2;+ let pad_str = " ".repeat(padding as usize);+ logo_text.push_str(&format!("\n{}[ TV MODE ]", pad_str));+ }+let vertical_chunks = Layout::default().direction(Direction::Vertical).constraints([@@ -104,13 +122,6 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)]).split(area);- let logo_width = if is_narrow {- 31- } else if is_wide {- 73- } else {- 55- };let pad = area.width.saturating_sub(logo_width) / 2;let horizontal_chunks = Layout::default().direction(Direction::Horizontal)@@ -192,7 +203,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)frame.render_widget(search_bar, search_bar_area);let legend_line = ratatui::text::Line::from(vec![- ratatui::text::Span::styled(" [Type] ", theme.shortcut),+ ratatui::text::Span::styled(" [Ctrl+T] ", theme.shortcut),+ ratatui::text::Span::styled("TV 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),@@ -628,4 +641,70 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)frame.render_widget(list, dropdown_area);}}+ if state.tv_config_popup {+ let content_height = state.tv_wizard_options.len() as u16;+ let popup_height = (content_height + 4).clamp(6, area.height.saturating_sub(4).max(6));++ let popup_area = ratatui::layout::Rect {+ x: area.width.saturating_sub(60) / 2,+ y: area.height.saturating_sub(popup_height) / 2,+ width: 60,+ 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 " })+ .borders(ratatui::widgets::Borders::ALL)+ .border_style(theme.border_focus)+ .style(ratatui::style::Style::default().bg(theme.base));++ let inner_area = popup_block.inner(popup_area);+ frame.render_widget(ratatui::widgets::Clear, popup_area);+ frame.render_widget(popup_block, popup_area);++ let items: Vec<ratatui::widgets::ListItem> = state.tv_wizard_options.iter().enumerate().map(|(i, opt)| {+ let is_selected = i == state.tv_wizard_selected_idx;+ let is_checked = state.tv_wizard_selections.contains(opt);++ let prefix = if is_selected { "> " } else { " " };+ let checkbox = if state.tv_wizard_step == 1 {+ if is_checked { "[x] " } else { "[ ] " }+ } else {+ ""+ };++ let style = if is_selected { theme.highlight } else { theme.text };+ let line = ratatui::text::Line::from(vec![+ ratatui::text::Span::styled(format!("{}{}{}", prefix, checkbox, opt), style)+ ]);+ ratatui::widgets::ListItem::new(line)+ }).collect();++ let list = ratatui::widgets::List::new(items);++ 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 hint_area = ratatui::layout::Rect {+ x: inner_area.x,+ y: inner_area.y + inner_area.height.saturating_sub(1),+ width: inner_area.width,+ height: 1,+ };+ let hint = if state.tv_wizard_step == 0 {+ " [Enter] Select [Esc] Cancel "+ } else {+ " [Space] Toggle [Enter] Confirm [Esc] Back "+ };+ frame.render_widget(+ ratatui::widgets::Paragraph::new(hint)+ .alignment(ratatui::layout::Alignment::Center)+ .style(theme.text_dim),+ hint_area+ );+ }}diff --git a/src/tui/state.rs b/src/tui/state.rsindex 455a798..34aa647 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -142,6 +142,15 @@ pub struct AppState {pub pending_open_with: bool,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>,+ pub tv_wizard_step: usize,+ pub tv_wizard_options: Vec<String>,+ pub tv_wizard_selected_idx: usize,+ pub tv_wizard_selections: std::collections::HashSet<String>,}impl Default for AppState {@@ -211,7 +220,7 @@ impl Default for AppState {} else if std::env::var("TMUX").is_ok() || std::env::var("SSH_TTY").is_ok() {false} else {- true // Let ratatui_image::picker::Picker query the terminal itself+ true}},poster_rows: 3,@@ -260,6 +269,15 @@ impl Default for AppState {.last().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_selected_idx: 0,+ tv_wizard_selections: std::collections::HashSet::new(),}}}