Skip to content

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

refactor(core): harden production readiness, layout bounds, and safety invariants

Samir Hossains068f4384e418
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e72f43..77da8c3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,32 @@
### Fixed
+- **Crash Hardening & Bounds Safety**:
+ - Fixed potential `usize` arithmetic underflow on empty search results in navigation handler (`.saturating_sub(1)`).
+ - Fixed potential `usize` arithmetic underflow on empty player picker navigation.
+ - Guarded JWT token split indexing with safe `.get(1)` pattern matching in MovieBox session parser.
+ - Hardened string slicing against non-ASCII UTF-8 character boundary hazards in DhakaFlix title/year parsing.
+ - Bounded help modal line-window slicing index to prevent out-of-bounds panics under constrained terminal heights.
+ - Clamped confirmation dialog action-row coordinate calculation to modal bounds on small screens.
+- **UI Layout & Mouse Synchronization**:
+ - Extracted shared `split_main_and_download` layout helper, eliminating constraint divergence between mouse hit testing and rendering passes.
+ - Synchronized details screen workflow step mouse hit-detection with dynamic text layout bounds.
+ - Replaced byte length count with display Unicode width for notification toast badge column derivations.
+ - Fixed addon manager badge column calculation to derive from visual Unicode width.
+ - Fixed provider selection popup list scroll state retention in Home screen rendering.
+- **Concurrency, Architecture & Network Safety**:
+ - Resolved architectural layer violation where provider modules directly imported text utilities from TUI presentation layer.
+ - Tracked pagination search, stream pool initialization, and episode prefetch tasks in `RequestTaskHandles` for prompt cancellation on navigation.
+ - Offloaded synchronous filesystem writes and directory creations in playback, download, and startup paths to background threads.
+ - Throttled high-frequency download progress channel event dispatch to 100ms intervals.
+ - Filtered forwarded Stremio addon stream HTTP headers against strict allowlist to prevent SSRF or credential leakage.
+ - Hardened network URL reachability probe to enforce HTTP 2xx/3xx status verification.
+ - Enforced response body size limits on remote IPTV M3U playlists (15 MB).
+ - Propagated DhakaFlix network errors instead of silently swallowing empty streams.
+ - Fixed `next_provider` navigation to handle currently disabled active providers correctly.
+ - Consolidated `/exit` slash command in autocomplete candidate suggestions.
+ - Centralized BDIX codec, resolution, and audio language heuristics into shared module.
+ - Pruned unused structs and dead code in CircleFTP and Addon models.
- **VLC Sidecar Proxy Correctness**:
- Replaced `reqwest::Client::timeout(30s)` (a hard deadline over the entire response body) with `connect_timeout(15s)` only; per-chunk idle timeout (60s) now signals stalled transfers without terminating long-running video streams mid-playback.
- Introduced a `ConnectionGuard` RAII wrapper ensuring `active_connections` is atomically decremented even when a connection handler task panics, eliminating a counter leak that kept the sidecar alive indefinitely under 24/7 operation.
diff --git a/src/net.rs b/src/net.rs
index 3a2a80a..da2dbf1 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -82,17 +82,21 @@ pub async fn probe_url(url: &str, timeout: std::time::Duration) -> bool {
else {
return false;
};
- if client.head(url).send().await.is_ok() {
- return true;
+ if let Ok(resp) = client.head(url).send().await {
+ if resp.status().is_success() || resp.status().is_redirection() {
+ return true;
+ }
}
- client.get(url).send().await.is_ok()
+ if let Ok(resp) = client.get(url).send().await {
+ return resp.status().is_success() || resp.status().is_redirection();
+ }
+ false
}
pub fn is_http_url(source: &str) -> bool {
let trimmed = source.trim();
trimmed.starts_with("http://") || trimmed.starts_with("https://")
}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/providers/addons/adapter.rs b/src/providers/addons/adapter.rs
index daf3d03..21d945f 100644
--- a/src/providers/addons/adapter.rs
+++ b/src/providers/addons/adapter.rs
@@ -15,7 +15,7 @@ pub fn meta_to_search_result(item: &MetaItem) -> SearchResult {
.as_deref()
.or(item.year.as_deref())
.or(item.released.as_deref())
- .map(crate::tui::text::extract_4digit_year)
+ .map(crate::providers::models::extract_4digit_year)
.unwrap_or_default();
let title = if !item.name.trim().is_empty() {
@@ -47,7 +47,7 @@ pub fn meta_to_catalog_item(item: &MetaItem) -> CatalogItem {
.as_deref()
.or(item.year.as_deref())
.or(item.released.as_deref())
- .map(crate::tui::text::extract_4digit_year)
+ .map(crate::providers::models::extract_4digit_year)
.filter(|y| !y.is_empty());
let title = if !item.name.trim().is_empty() {
@@ -116,7 +116,7 @@ pub fn meta_detail_to_media_details(detail: &MetaDetail) -> MediaDetails {
.or(detail.year.as_deref())
.or(detail.released.as_deref())
.unwrap_or_default();
- let year = crate::tui::text::extract_4digit_year(year_raw);
+ let year = crate::providers::models::extract_4digit_year(year_raw);
let year = if !year.is_empty() {
Some(year)
} else if !year_raw.is_empty() {
@@ -561,18 +561,29 @@ pub fn stream_item_to_release(
.filter(|s| !s.is_empty())
.unwrap_or_else(|| format!("{addon_name} Stream"));
- let filename = crate::tui::text::clean_stream_text(&raw_filename);
+ let filename = crate::providers::models::clean_stream_text(&raw_filename);
let raw_source_label =
detect_stream_host(addon_name, stream_name_str, title_str, desc_str, url);
- let source_label = crate::tui::text::clean_stream_text(&raw_source_label);
- let language = language.map(|l| crate::tui::text::clean_stream_text(&l));
+ let source_label = crate::providers::models::clean_stream_text(&raw_source_label);
+ let language = language.map(|l| crate::providers::models::clean_stream_text(&l));
let mut headers = Vec::new();
if let Some(hints) = &stream.behavior_hints
&& let Some(hdr_map) = &hints.headers
{
+ const ALLOWED_HEADERS: &[&str] = &[
+ "user-agent",
+ "referer",
+ "origin",
+ "range",
+ "x-forwarded-for",
+ "accept",
+ "accept-language",
+ ];
for (k, v) in hdr_map {
- headers.push((k.clone(), v.clone()));
+ if ALLOWED_HEADERS.contains(&k.to_ascii_lowercase().as_str()) {
+ headers.push((k.clone(), v.clone()));
+ }
}
}
diff --git a/src/providers/addons/models.rs b/src/providers/addons/models.rs
index 9d116e5..833e34b 100644
--- a/src/providers/addons/models.rs
+++ b/src/providers/addons/models.rs
@@ -398,11 +398,6 @@ pub struct MetaDetail {
pub videos: Vec<MetaVideo>,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct MetaDetailResponse {
- pub meta: Option<MetaDetail>,
-}
-
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StreamBehaviorHints {
#[serde(rename = "notWebReady", default)]
@@ -424,12 +419,6 @@ pub struct StreamItem {
pub behavior_hints: Option<StreamBehaviorHints>,
}
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
-pub struct StreamResponse {
- #[serde(default)]
- pub streams: Vec<StreamItem>,
-}
-
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InstalledAddon {
pub manifest_url: String,
diff --git a/src/providers/bdix/circleftp/client.rs b/src/providers/bdix/circleftp/client.rs
index 13a7294..f24c514 100644
--- a/src/providers/bdix/circleftp/client.rs
+++ b/src/providers/bdix/circleftp/client.rs
@@ -213,45 +213,12 @@ impl CircleFtpClient {
let r#type = json.get("type").and_then(|v| v.as_str()).unwrap_or("");
let quality_str = json.get("quality").and_then(|v| v.as_str()).unwrap_or("HD");
- let quality = if quality_str.to_lowercase().contains("1080p") {
- Some("1080p".to_string())
- } else if quality_str.to_lowercase().contains("720p") {
- Some("720p".to_string())
- } else if quality_str.to_lowercase().contains("4k")
- || quality_str.to_lowercase().contains("2160p")
- {
- Some("4k".to_string())
- } else {
- Some(quality_str.to_string())
- };
+ let quality = crate::providers::bdix::common::detect_resolution(quality_str)
+ .or_else(|| Some(quality_str.to_string()));
let title_str = json.get("title").and_then(|v| v.as_str()).unwrap_or("");
-
- let t_lower = title_str.to_lowercase();
-
- let codec = [
- ("x264", "x264"),
- ("h264", "x264"),
- ("x265", "HEVC"),
- ("hevc", "HEVC"),
- ("av1", "AV1"),
- ]
- .iter()
- .find(|(k, _)| t_lower.contains(k))
- .map(|(_, v)| v.to_string());
-
- let language = [
- ("hindi", "Hindi"),
- ("bengali", "Bengali"),
- ("bangla", "Bengali"),
- ("english", "English"),
- ("tamil", "Tamil"),
- ("telugu", "Telugu"),
- ("malayalam", "Malayalam"),
- ]
- .iter()
- .find(|(k, _)| t_lower.contains(k))
- .map(|(_, v)| v.to_string());
+ let codec = crate::providers::bdix::common::detect_codec(title_str);
+ let language = crate::providers::bdix::common::detect_audio_language(title_str);
if r#type == "series" {
if let (Some(target_s), Some(target_e)) = (season, episode) {
diff --git a/src/providers/bdix/circleftp/parser.rs b/src/providers/bdix/circleftp/parser.rs
index 9ae6d52..2f0982b 100644
--- a/src/providers/bdix/circleftp/parser.rs
+++ b/src/providers/bdix/circleftp/parser.rs
@@ -19,20 +19,6 @@ pub struct CircleFtpSearchResponse {
pub posts: Option<Vec<CircleFtpPost>>,
}
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CircleFtpSeason {
- pub season_name: Option<String>,
- pub episodes: Option<Vec<CircleFtpEpisode>>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CircleFtpEpisode {
- pub title: Option<String>,
- pub link: Option<String>,
-}
-
pub fn circleftp_search_to_catalog(response: &CircleFtpSearchResponse) -> Vec<CatalogItem> {
let mut items = Vec::new();
if let Some(posts) = &response.posts {
diff --git a/src/providers/bdix/common.rs b/src/providers/bdix/common.rs
new file mode 100644
index 0000000..d56e4eb
--- /dev/null
+++ b/src/providers/bdix/common.rs
@@ -0,0 +1,48 @@
+pub fn detect_audio_language(text: &str) -> Option<String> {
+ let lower = text.to_lowercase();
+ if lower.contains("hindi") {
+ Some("Hindi".to_string())
+ } else if lower.contains("bengali") || lower.contains("bangla") {
+ Some("Bengali".to_string())
+ } else if lower.contains("tamil") {
+ Some("Tamil".to_string())
+ } else if lower.contains("telugu") {
+ Some("Telugu".to_string())
+ } else if lower.contains("dual") {
+ Some("Dual Audio".to_string())
+ } else if lower.contains("multi") {
+ Some("Multi Audio".to_string())
+ } else if lower.contains("english") {
+ Some("English".to_string())
+ } else {
+ None
+ }
+}
+
+pub fn detect_resolution(text: &str) -> Option<String> {
+ let lower = text.to_lowercase();
+ if lower.contains("2160p") || lower.contains("4k") {
+ Some("4K".to_string())
+ } else if lower.contains("1080p") {
+ Some("1080p".to_string())
+ } else if lower.contains("720p") {
+ Some("720p".to_string())
+ } else if lower.contains("480p") {
+ Some("480p".to_string())
+ } else {
+ None
+ }
+}
+
+pub fn detect_codec(text: &str) -> Option<String> {
+ let lower = text.to_lowercase();
+ if lower.contains("x265") || lower.contains("hevc") {
+ Some("HEVC".to_string())
+ } else if lower.contains("x264") || lower.contains("h264") {
+ Some("x264".to_string())
+ } else if lower.contains("av1") {
+ Some("AV1".to_string())
+ } else {
+ None
+ }
+}
diff --git a/src/providers/bdix/dhakaflix/client.rs b/src/providers/bdix/dhakaflix/client.rs
index 28a2f36..a12d065 100644
--- a/src/providers/bdix/dhakaflix/client.rs
+++ b/src/providers/bdix/dhakaflix/client.rs
@@ -23,13 +23,17 @@ fn parse_title_and_year(raw_title: &str) -> (String, Option<String>) {
let mut year = None;
if let Some(start) = title.rfind('(') {
- if let Some(end) = title[start..].find(')') {
- let year_str = &title[start + 1..start + end];
- let extracted = crate::tui::text::extract_4digit_year(year_str);
- if extracted.len() == 4 && year_str.trim().len() == 4 {
- year = Some(extracted);
- title = title[..start].trim().to_string();
- return (title, year);
+ if let Some(rel_end) = title.get(start..).and_then(|s| s.find(')')) {
+ let end = start + rel_end;
+ if let (Some(year_slice), Some(title_slice)) =
+ (title.get(start + 1..end), title.get(..start))
+ {
+ let extracted = crate::providers::models::extract_4digit_year(year_slice);
+ if extracted.len() == 4 && year_slice.trim().len() == 4 {
+ year = Some(extracted);
+ title = title_slice.trim().to_string();
+ return (title, year);
+ }
}
}
}
@@ -40,7 +44,10 @@ fn parse_title_and_year(raw_title: &str) -> (String, Option<String>) {
];
for q in qualities {
if lower.ends_with(q) {
- title = title[..title.len() - q.len()].trim().to_string();
+ let trim_len = title.len().saturating_sub(q.len());
+ if let Some(prefix) = title.get(..trim_len) {
+ title = prefix.trim().to_string();
+ }
break;
}
}
@@ -352,91 +359,62 @@ impl DhakaFlixClient {
}
});
- if let Ok(resp) = self.client.post(&api_url).json(&body).send().await {
- if let Ok(json) = resp.json::<serde_json::Value>().await {
- if let Some(items_arr) = json.get("items").and_then(|v| v.as_array()) {
- for item in items_arr {
- if let (Some(item_href), Some(size)) = (
- item.get("href").and_then(|v| v.as_str()),
- item.get("size").and_then(|v| v.as_u64()),
- ) {
- let filename = item_href
- .split('/')
- .next_back()
- .unwrap_or("Unknown")
- .to_string();
- let filename_decoded =
- percent_encoding::percent_decode_str(&filename)
- .decode_utf8_lossy()
- .to_string();
-
- let f_lower = filename_decoded.to_lowercase();
- if !f_lower.ends_with(".mkv")
- && !f_lower.ends_with(".mp4")
- && !f_lower.ends_with(".avi")
- && !f_lower.ends_with(".webm")
- {
- continue;
- }
-
- let quality = if f_lower.contains("1080p") {
- Some("1080p".to_string())
- } else if filename_decoded.to_lowercase().contains("720p") {
- Some("720p".to_string())
- } else if filename_decoded.to_lowercase().contains("2160p")
- || filename_decoded.to_lowercase().contains("4k")
- {
- Some("4K".to_string())
- } else {
- Some("HD".to_string())
- };
-
- let mut language = None;
- let mut codec = None;
-
- if f_lower.contains("hindi") {
- language = Some("Hindi".to_string());
- } else if f_lower.contains("bengali") || f_lower.contains("bangla")
- {
- language = Some("Bengali".to_string());
- } else if f_lower.contains("tamil") {
- language = Some("Tamil".to_string());
- } else if f_lower.contains("telugu") {
- language = Some("Telugu".to_string());
- } else if f_lower.contains("dual") {
- language = Some("Dual Audio".to_string());
- } else if f_lower.contains("multi") {
- language = Some("Multi Audio".to_string());
- } else if f_lower.contains("english") {
- language = Some("English".to_string());
- }
-
- if f_lower.contains("hevc") || f_lower.contains("x265") {
- codec = Some("HEVC".to_string());
- } else if f_lower.contains("x264") || f_lower.contains("h264") {
- codec = Some("x264".to_string());
- } else if f_lower.contains("av1") {
- codec = Some("AV1".to_string());
- }
-
- releases.push(Release {
- provider: ProviderKind::BdixDhakaFlix,
- filename: filename_decoded,
- quality,
- codec,
- language,
- size_bytes: Some(size),
- season: None,
- episode: None,
- mirrors: vec![crate::providers::models::SourceMirror {
- label: "DhakaFlix".to_string(),
- resolver_url: format!("{}{}", base_url, item_href),
- headers: vec![],
- direct_file: true,
- }],
- resource_id: None,
- });
+ let resp = self
+ .client
+ .post(&api_url)
+ .json(&body)
+ .send()
+ .await?
+ .error_for_status()?;
+ if let Ok(json) = resp.json::<serde_json::Value>().await {
+ if let Some(items_arr) = json.get("items").and_then(|v| v.as_array()) {
+ for item in items_arr {
+ if let (Some(item_href), Some(size)) = (
+ item.get("href").and_then(|v| v.as_str()),
+ item.get("size").and_then(|v| v.as_u64()),
+ ) {
+ let filename = item_href
+ .split('/')
+ .next_back()
+ .unwrap_or("Unknown")
+ .to_string();
+ let filename_decoded = percent_encoding::percent_decode_str(&filename)
+ .decode_utf8_lossy()
+ .to_string();
+
+ let f_lower = filename_decoded.to_lowercase();
+ if !f_lower.ends_with(".mkv")
+ && !f_lower.ends_with(".mp4")
+ && !f_lower.ends_with(".avi")
+ && !f_lower.ends_with(".webm")
+ {
+ continue;
}
+
+ let quality =
+ crate::providers::bdix::common::detect_resolution(&f_lower)
+ .or_else(|| Some("HD".to_string()));
+ let language =
+ crate::providers::bdix::common::detect_audio_language(&f_lower);
+ let codec = crate::providers::bdix::common::detect_codec(&f_lower);
+
+ releases.push(Release {
+ provider: ProviderKind::BdixDhakaFlix,
+ filename: filename_decoded,
+ quality,
+ codec,
+ language,
+ size_bytes: Some(size),
+ season: None,
+ episode: None,
+ mirrors: vec![crate::providers::models::SourceMirror {
+ label: "DhakaFlix".to_string(),
+ resolver_url: format!("{}{}", base_url, item_href),
+ headers: vec![],
+ direct_file: true,
+ }],
+ resource_id: None,
+ });
}
}
}
diff --git a/src/providers/bdix/mod.rs b/src/providers/bdix/mod.rs
index a516823..f445ae6 100644
--- a/src/providers/bdix/mod.rs
+++ b/src/providers/bdix/mod.rs
@@ -1,2 +1,3 @@
pub mod circleftp;
+pub mod common;
pub mod dhakaflix;
diff --git a/src/providers/fourkhdhub/parser.rs b/src/providers/fourkhdhub/parser.rs
index 0ffbcad..72c6b60 100644
--- a/src/providers/fourkhdhub/parser.rs
+++ b/src/providers/fourkhdhub/parser.rs
@@ -277,7 +277,7 @@ fn find_metadata(document: &Html, label: &str) -> Option<String> {
}
fn first_four_digit_year(value: &str) -> Option<String> {
- let year = crate::tui::text::extract_4digit_year(value);
+ let year = crate::providers::models::extract_4digit_year(value);
(!year.is_empty()).then_some(year)
}
diff --git a/src/providers/models.rs b/src/providers/models.rs
index 4dfb20f..b3a1694 100644
--- a/src/providers/models.rs
+++ b/src/providers/models.rs
@@ -326,3 +326,45 @@ impl From<&str> for ProviderError {
Self::Unavailable(msg.to_string())
}
}
+
+pub fn strip_emojis(input: &str) -> String {
+ input
+ .chars()
+ .filter(|&c| {
+ let u = c as u32;
+ !((0x1F000..=0x1FAFF).contains(&u)
+ || (0x2600..=0x27BF).contains(&u)
+ || (0x2300..=0x23FF).contains(&u)
+ || (0x2B00..=0x2BFF).contains(&u)
+ || (0xFE00..=0xFE0F).contains(&u)
+ || u == 0x200D)
+ })
+ .collect::<String>()
+}
+
+pub fn clean_stream_text(input: &str) -> String {
+ let without_emojis = strip_emojis(input);
+ let mut cleaned = String::new();
+ let mut last_was_space = false;
+ for c in without_emojis.chars() {
+ if c.is_whitespace() {
+ if !last_was_space && !cleaned.is_empty() {
+ cleaned.push(' ');
+ last_was_space = true;
+ }
+ } else {
+ cleaned.push(c);
+ last_was_space = false;
+ }
+ }
+ cleaned.trim().to_string()
+}
+
+pub fn extract_4digit_year(raw: &str) -> String {
+ raw.as_bytes()
+ .windows(4)
+ .find(|window| window.iter().all(u8::is_ascii_digit) && matches!(window[0], b'1' | b'2'))
+ .and_then(|window| std::str::from_utf8(window).ok())
+ .map(str::to_string)
+ .unwrap_or_default()
+}
diff --git a/src/providers/moviebox/adapt.rs b/src/providers/moviebox/adapt.rs
index d7442a3..c6c3909 100644
--- a/src/providers/moviebox/adapt.rs
+++ b/src/providers/moviebox/adapt.rs
@@ -91,7 +91,7 @@ pub fn moviebox_subject_json_to_catalog_item(s: &serde_json::Value) -> Option<Ca
.or_else(|| s.get("year"))
.or_else(|| s.get("releaseInfo"))
.and_then(|y| y.as_str())
- .map(crate::tui::text::extract_4digit_year)
+ .map(crate::providers::models::extract_4digit_year)
.filter(|y| !y.is_empty());
let poster_url = s
@@ -270,7 +270,7 @@ pub fn moviebox_details_json_to_media_details(
.get("releaseDate")
.or_else(|| subject.get("year"))
.and_then(|y| y.as_str())
- .map(crate::tui::text::extract_4digit_year)
+ .map(crate::providers::models::extract_4digit_year)
.filter(|y| !y.is_empty());
let description = subject
diff --git a/src/providers/moviebox/session.rs b/src/providers/moviebox/session.rs
index e7af328..465b881 100644
--- a/src/providers/moviebox/session.rs
+++ b/src/providers/moviebox/session.rs
@@ -50,10 +50,9 @@ impl MovieBoxSession {
pub fn parse_jwt_claims(token: &str) -> (Option<String>, Option<u64>) {
let parts: Vec<&str> = token.split('.').collect();
- if parts.len() < 2 {
+ let Some(&payload_b64) = parts.get(1) else {
return (None, None);
- }
- let payload_b64 = parts[1];
+ };
let pad_len = (4 - (payload_b64.len() % 4)) % 4;
let padded = format!("{}{}", payload_b64, "=".repeat(pad_len));
diff --git a/src/providers/tv/parser.rs b/src/providers/tv/parser.rs
index 4937c70..666ab5d 100644
--- a/src/providers/tv/parser.rs
+++ b/src/providers/tv/parser.rs
@@ -48,14 +48,16 @@ impl M3UParser {
}
if needs_download {
- let res = self
- .client
- .get(trimmed)
- .send()
- .await?
- .error_for_status()?
- .text()
- .await?;
+ let resp = self.client.get(trimmed).send().await?.error_for_status()?;
+ if let Some(cl) = resp.content_length() {
+ if cl > 15 * 1024 * 1024 {
+ return Err("remote playlist exceeds maximum 15MB size limit".into());
+ }
+ }
+ let res = resp.text().await?;
+ if res.len() > 15 * 1024 * 1024 {
+ return Err("remote playlist exceeds maximum 15MB size limit".into());
+ }
let _ = crate::cache::atomic_write_file_async(&file_path, res.as_bytes()).await;
res
} else {
@@ -84,14 +86,16 @@ impl M3UParser {
if is_remote && channels.is_empty() {
let file_path = self.cache_dir.join(cache_filename(trimmed));
let _ = tokio::fs::remove_file(&file_path).await;
- let fresh = self
- .client
- .get(trimmed)
- .send()
- .await?
- .error_for_status()?
- .text()
- .await?;
+ let resp = self.client.get(trimmed).send().await?.error_for_status()?;
+ if let Some(cl) = resp.content_length() {
+ if cl > 15 * 1024 * 1024 {
+ return Err("remote playlist exceeds maximum 15MB size limit".into());
+ }
+ }
+ let fresh = resp.text().await?;
+ if fresh.len() > 15 * 1024 * 1024 {
+ return Err("remote playlist exceeds maximum 15MB size limit".into());
+ }
let fresh_channels = self.parse_m3u(&fresh);
if fresh_channels.is_empty() {
return Ok(fresh_channels);
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 1c352fa..86541b6 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -381,12 +381,19 @@ impl App {
}
} else {
let progress_sender = sender.clone();
+ let mut last_progress_send = std::time::Instant::now();
let result = crate::download::download(
&client,
&link,
&destination,
cancel,
move |progress| {
+ if last_progress_send.elapsed() < std::time::Duration::from_millis(100)
+ && progress.downloaded < progress.total.unwrap_or_default()
+ {
+ return;
+ }
+ last_progress_send = std::time::Instant::now();
let total = progress.total.unwrap_or_default();
let percentage = if total > 0 {
progress.downloaded as f64 / total as f64 * 100.0
diff --git a/src/tui/app/mod.rs b/src/tui/app/mod.rs
index 910a237..61f9b86 100644
--- a/src/tui/app/mod.rs
+++ b/src/tui/app/mod.rs
@@ -25,6 +25,8 @@ pub struct RequestTaskHandles {
pub suggest: Option<tokio::task::JoinHandle<()>>,
pub homepage: Option<tokio::task::JoinHandle<()>>,
pub download: Option<tokio::task::JoinHandle<()>>,
+ pub stream_pool_init: Option<tokio::task::JoinHandle<()>>,
+ pub episode_prefetch: Option<tokio::task::JoinHandle<()>>,
}
impl RequestTaskHandles {
@@ -63,6 +65,18 @@ impl RequestTaskHandles {
}
}
+ pub fn cancel_stream_pool_init(&mut self) {
+ if let Some(h) = self.stream_pool_init.take() {
+ h.abort();
+ }
+ }
+
+ pub fn cancel_episode_prefetch(&mut self) {
+ if let Some(h) = self.episode_prefetch.take() {
+ h.abort();
+ }
+ }
+
pub fn cancel_all(&mut self) {
self.cancel_search();
self.cancel_details();
@@ -70,6 +84,8 @@ impl RequestTaskHandles {
self.cancel_suggest();
self.cancel_homepage();
self.cancel_download();
+ self.cancel_stream_pool_init();
+ self.cancel_episode_prefetch();
}
}
@@ -251,17 +267,19 @@ impl App {
let Some(path) = crate::config::tv_path() else {
return;
};
- if let Some(app_dir) = path.parent()
- && std::fs::create_dir_all(app_dir).is_err()
- {
- return;
- }
let Ok(json) = serde_json::to_string_pretty(&self.state.tv_playlists) else {
return;
};
- if let Err(error) = crate::cache::atomic_write_file(&path, json.as_bytes()) {
- log::warn!("failed to save tv playlists: {error}");
- }
+ tokio::task::spawn_blocking(move || {
+ if let Some(app_dir) = path.parent()
+ && std::fs::create_dir_all(app_dir).is_err()
+ {
+ return;
+ }
+ if let Err(error) = crate::cache::atomic_write_file(&path, json.as_bytes()) {
+ log::warn!("failed to save tv playlists: {error}");
+ }
+ });
}
fn load_tv_playlists_from_config(&mut self) {
diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rs
index 130a77c..07e3ceb 100644
--- a/src/tui/app/mouse.rs
+++ b/src/tui/app/mouse.rs
@@ -4,7 +4,7 @@ use crate::tui::{
overlay::NotificationKind,
state::{BrowsePreset, DetailsPane, InputMode, Screen},
};
-use ratatui::layout::{Constraint, Direction, Layout, Rect};
+use ratatui::layout::{Constraint, Layout, Rect};
impl App {
pub(super) fn handle_mouse(&mut self, col: u16, row: u16) -> Option<Action> {
@@ -44,11 +44,7 @@ impl App {
}
if self.state.download_progress.is_some() {
- let chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([Constraint::Min(1), Constraint::Length(3)])
- .split(area);
- let dl_area = chunks[1];
+ let [_, dl_area] = crate::tui::app::App::split_main_and_download(area);
if dl_area.contains(ratatui::layout::Position::new(col, row)) {
let cancel_rect = Rect {
x: dl_area.right().saturating_sub(14),
@@ -986,6 +982,7 @@ impl App {
available_panes.push(DetailsPane::Episodes);
}
+ let streams_count = self.state.selected_resources.len();
let layout = crate::tui::screens::details::details_screen_layout(
area,
self.state.selected_details.as_ref(),
@@ -1000,13 +997,19 @@ impl App {
}
if workflow_area.height > 0 && row == workflow_area.y {
- let count = available_panes.len() + 1;
- let section_w = area.width / count as u16;
- let pane_idx = (col / section_w.max(1)) as usize;
- if pane_idx < available_panes.len() {
- self.state.details_pane = available_panes[pane_idx];
- } else {
- self.state.details_pane = DetailsPane::Streams;
+ let (_, ranges) = crate::tui::screens::details::workflow_step_ranges(
+ area.width,
+ &self.state,
+ &details,
+ has_languages,
+ is_series,
+ streams_count,
+ );
+ for (pane, start_x, end_x) in ranges {
+ if col >= start_x && col < end_x {
+ self.state.details_pane = pane;
+ return None;
+ }
}
return None;
}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index 2256dc4..4f79c05 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -139,7 +139,10 @@ impl App {
let context = self.request_context();
let request_id = self.state.active_search_request;
self.state.is_loading = true;
- tokio::spawn(async move {
+ if let Some(h) = self.request_tasks.search.take() {
+ h.abort();
+ }
+ self.request_tasks.search = Some(tokio::spawn(async move {
let q = query.clone();
let provider = context.provider;
if let Ok(Some(cached)) = tokio::task::spawn_blocking(move || {
@@ -193,7 +196,7 @@ impl App {
.ok();
}
}
- });
+ }));
}
}
}
@@ -291,14 +294,15 @@ impl App {
let sender = self.action_sender.clone();
let context = self.request_context();
let request_id = self.state.active_resource_request;
- tokio::spawn(async move {
+ self.request_tasks.cancel_episode_prefetch();
+ self.request_tasks.episode_prefetch = Some(tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(120)).await;
sender
.send(Action::EpisodeStreamsReady(
context, request_id, id, se, ep, streams,
))
.ok();
- });
+ }));
} else {
self.state.selected_resources.clear();
self.state.is_loading = true;
@@ -484,10 +488,13 @@ impl App {
Action::MoveUp => {
if self.state.player_picker_popup {
+ if self.state.available_players.is_empty() {
+ return None;
+ }
let i = match self.state.player_picker_state.selected() {
Some(i) => {
if i == 0 {
- self.state.available_players.len() - 1
+ self.state.available_players.len().saturating_sub(1)
} else {
i - 1
}
@@ -571,9 +578,13 @@ impl App {
Action::MoveDown => {
if self.state.player_picker_popup {
+ if self.state.available_players.is_empty() {
+ return None;
+ }
+ let max_idx = self.state.available_players.len().saturating_sub(1);
let i = match self.state.player_picker_state.selected() {
Some(i) => {
- if i >= self.state.available_players.len() - 1 {
+ if i >= max_idx {
0
} else {
i + 1
@@ -609,10 +620,14 @@ impl App {
self.state.favorites_landing_state.select(Some(0));
return None;
}
+ if self.state.search_results.is_empty() {
+ return None;
+ }
let current = self.state.search_list_state.selected().unwrap_or(0);
let down_step = self.result_grid_columns();
- let next = (current + down_step).min(self.state.search_results.len() - 1);
- if next != current && !self.state.search_results.is_empty() {
+ let max_idx = self.state.search_results.len().saturating_sub(1);
+ let next = (current + down_step).min(max_idx);
+ if next != current {
self.state.search_list_state.select(Some(next));
if let Some(res) = self.state.search_results.get(next) {
self.action_sender
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 1c5ec3b..9b7b3f8 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -270,12 +270,14 @@ impl App {
false,
);
if let Ok(serialized) = serde_json::to_string(&initial_state) {
- if let Err(e) = std::fs::write(&state_path, serialized) {
- log::warn!(
- "failed to write initial playback state to {}: {e}",
- crate::logging::sanitize_path(&state_path)
- );
- }
+ tokio::task::spawn_blocking(move || {
+ if let Err(e) = std::fs::write(&state_path, serialized) {
+ log::warn!(
+ "failed to write initial playback state to {}: {e}",
+ crate::logging::sanitize_path(&state_path)
+ );
+ }
+ });
}
}
}
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 81f1f22..239fd7e 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -1193,7 +1193,8 @@ impl App {
}
let service = self.service.clone();
let sender = self.action_sender.clone();
- tokio::spawn(async move {
+ self.request_tasks.cancel_stream_pool_init();
+ self.request_tasks.stream_pool_init = Some(tokio::spawn(async move {
let resolutions = service
.fetch_collection_resolutions(&subject_id)
.await
@@ -1201,7 +1202,7 @@ impl App {
sender
.send(Action::StreamPoolInitialized(subject_id, resolutions))
.ok();
- });
+ }));
}
Action::StreamPoolInitialized(subject_id, resolutions) => {
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index f51628c..50ec435 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -507,14 +507,9 @@ impl App {
let mut download_area = None;
if self.state.download_progress.is_some() {
- use ratatui::layout::{Constraint, Direction, Layout};
- let chunks = Layout::default()
- .direction(Direction::Vertical)
- .constraints([Constraint::Min(0), Constraint::Length(3)])
- .split(main_area);
-
- main_area = chunks[0];
- download_area = Some(chunks[1]);
+ let [m, d] = Self::split_main_and_download(main_area);
+ main_area = m;
+ download_area = Some(d);
}
match self.state.active_screen {
@@ -531,6 +526,7 @@ impl App {
}
self.draw_download_gauge(frame, download_area);
+
self.draw_settings_modal(frame, area);
self.draw_sources_picker(frame, area);
self.draw_theme_picker(frame, area);
@@ -548,6 +544,15 @@ impl App {
);
}
+ pub fn split_main_and_download(area: ratatui::layout::Rect) -> [ratatui::layout::Rect; 2] {
+ use ratatui::layout::{Constraint, Direction, Layout};
+ let chunks = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([Constraint::Min(0), Constraint::Length(3)])
+ .split(area);
+ [chunks[0], chunks[1]]
+ }
+
fn draw_resize_badge(&self, frame: &mut Frame, area: Rect) -> bool {
if let Some((_, w, h)) = self.state.last_resize_time {
let sep = if self.state.basic_terminal { "x" } else { "×" };
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index e1d339b..c3a3f70 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -64,17 +64,8 @@ impl SlashCommand {
let lower = query.to_ascii_lowercase();
let mut results = Vec::new();
- let candidates: [(&str, Self); 7] = [
- ("/settings", Self::Settings),
- ("/browse", Self::Browse),
- ("/history", Self::History),
- ("/favorites", Self::Favorites),
- ("/clear", Self::Clear),
- ("/help", Self::Help),
- ("/list", Self::List),
- ];
-
- for (name, cmd) in candidates {
+ for cmd in Self::ALL {
+ let name = cmd.name();
if !cmd.is_available(state) {
continue;
}
@@ -157,6 +148,7 @@ mod tests {
"/favorites".to_string(),
"/clear".to_string(),
"/help".to_string(),
+ "/exit".to_string(),
]
);
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index 9bc6e84..0f9759f 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -125,7 +125,7 @@ pub fn download_confirm_layout(
}
pub fn download_confirm_action_row(popup: Rect, summary_lines: usize) -> u16 {
- popup.y + summary_lines as u16 + 1
+ (popup.y + summary_lines as u16 + 1).min(popup.bottom().saturating_sub(1))
}
pub fn picker(
@@ -214,6 +214,24 @@ pub fn picker_with_lines<'a>(
}
}
+pub fn browse_category_badge_text(label: &str) -> &'static str {
+ let lower = label.to_ascii_lowercase();
+ if lower.contains("movie")
+ || lower.contains("top rated (all-time)")
+ || lower.contains("top rated (recent")
+ {
+ "[MOVIES]"
+ } else if lower.contains("series")
+ || lower.contains("airing")
+ || lower.contains("show")
+ || lower.contains("tv")
+ {
+ "[SERIES]"
+ } else {
+ "[DISCOVER]"
+ }
+}
+
pub fn browse_category_badge<'a>(label: &str, theme: &'a Theme) -> (Span<'a>, &'static str) {
let lower = label.to_ascii_lowercase();
if lower.contains("movie")
@@ -328,7 +346,7 @@ pub fn notifications(
!notification.message.is_empty() && notification.message != notification.title;
let title_w = crate::tui::text::width(&notification.title).saturating_add(6);
- let badge_w = badge.len().saturating_add(6);
+ let badge_w = crate::tui::text::width(badge).saturating_add(6);
let raw_msg_w = if has_message {
crate::tui::text::width(&notification.message).saturating_add(6)
} else {
@@ -559,7 +577,7 @@ pub fn notification_rects(
!notification.message.is_empty() && notification.message != notification.title;
let title_w = crate::tui::text::width(&notification.title).saturating_add(6);
- let badge_w = badge.len().saturating_add(6);
+ let badge_w = crate::tui::text::width(badge).saturating_add(6);
let raw_msg_w = if has_message {
crate::tui::text::width(&notification.message).saturating_add(6)
} else {
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index b8a2b3e..cb9931a 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -1740,51 +1740,14 @@ fn render_workflow(
if area.height == 0 || area.width == 0 {
return;
}
- let compact = area.width < 100;
- let mut steps = Vec::new();
-
- if has_languages {
- let active_idx = details
- .dubs
- .iter()
- .position(|dub| {
- dub.subject_id == state.active_subject_id.as_deref().unwrap_or_default()
- })
- .or_else(|| state.language_list_state.selected())
- .unwrap_or(0);
-
- let language = details
- .dubs
- .get(active_idx)
- .map(|dub| clean_language_name(&dub.language))
- .unwrap_or_else(|| "Choose".to_string());
- steps.push((
- crate::tui::state::DetailsPane::Languages,
- format!("Audio: {language}"),
- ));
- }
- if is_series {
- steps.push((
- crate::tui::state::DetailsPane::Seasons,
- if compact {
- format!("S{}", state.selected_season)
- } else {
- format!("Season {}", state.selected_season)
- },
- ));
-
- let ep_label = if compact {
- format!("E{}", state.selected_episode)
- } else {
- format!("Episode {}", state.selected_episode)
- };
-
- steps.push((crate::tui::state::DetailsPane::Episodes, ep_label));
- }
- steps.push((
- crate::tui::state::DetailsPane::Streams,
- format!("Streams: {streams_count}"),
- ));
+ let (steps, _step_ranges) = workflow_step_ranges(
+ area.width,
+ state,
+ details,
+ has_languages,
+ is_series,
+ streams_count,
+ );
if area.width < 60 {
let position = steps
@@ -1854,6 +1817,96 @@ fn render_workflow(
);
}
+pub type WorkflowStep = (crate::tui::state::DetailsPane, String);
+pub type WorkflowRange = (crate::tui::state::DetailsPane, u16, u16);
+
+pub fn workflow_step_ranges(
+ area_width: u16,
+ state: &AppState,
+ details: &MediaDetails,
+ has_languages: bool,
+ is_series: bool,
+ streams_count: usize,
+) -> (Vec<WorkflowStep>, Vec<WorkflowRange>) {
+ let compact = area_width < 100;
+ let mut steps = Vec::new();
+
+ if has_languages {
+ let active_idx = details
+ .dubs
+ .iter()
+ .position(|dub| {
+ dub.subject_id == state.active_subject_id.as_deref().unwrap_or_default()
+ })
+ .or_else(|| state.language_list_state.selected())
+ .unwrap_or(0);
+
+ let language = details
+ .dubs
+ .get(active_idx)
+ .map(|dub| clean_language_name(&dub.language))
+ .unwrap_or_else(|| "Choose".to_string());
+ steps.push((
+ crate::tui::state::DetailsPane::Languages,
+ format!("Audio: {language}"),
+ ));
+ }
+ if is_series {
+ steps.push((
+ crate::tui::state::DetailsPane::Seasons,
+ if compact {
+ format!("S{}", state.selected_season)
+ } else {
+ format!("Season {}", state.selected_season)
+ },
+ ));
+
+ let ep_label = if compact {
+ format!("E{}", state.selected_episode)
+ } else {
+ format!("Episode {}", state.selected_episode)
+ };
+
+ steps.push((crate::tui::state::DetailsPane::Episodes, ep_label));
+ }
+ steps.push((
+ crate::tui::state::DetailsPane::Streams,
+ format!("Streams: {streams_count}"),
+ ));
+
+ let sep_len = if state.basic_terminal { 3 } else { 5 };
+ let marker_len = 2; // "> " or "› "
+ let mut total_w = 0;
+ for (idx, (pane, label)) in steps.iter().enumerate() {
+ if idx > 0 {
+ total_w += sep_len;
+ }
+ if *pane == state.details_pane {
+ total_w += marker_len;
+ }
+ total_w += crate::tui::text::width(label) as u16;
+ }
+
+ let start_x = area_width.saturating_sub(total_w) / 2;
+ let mut current_x = start_x;
+ let mut ranges = Vec::new();
+
+ for (idx, (pane, label)) in steps.iter().enumerate() {
+ if idx > 0 {
+ current_x += sep_len;
+ }
+ let step_start = current_x;
+ let mut step_w = crate::tui::text::width(label) as u16;
+ if *pane == state.details_pane {
+ step_w += marker_len;
+ }
+ current_x += step_w;
+ ranges.push((*pane, step_start, current_x));
+ }
+
+ (steps, ranges)
+}
+
fn footer_group(
key: &'static str,
action: &str,
diff --git a/src/tui/screens/help.rs b/src/tui/screens/help.rs
index 1a1d694..582cc74 100644
--- a/src/tui/screens/help.rs
+++ b/src/tui/screens/help.rs
@@ -118,7 +118,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {
if !two_columns && all_lines.len() > capacity {
let max_scroll = all_lines.len().saturating_sub(capacity);
let scroll = state.help_scroll.min(max_scroll);
- let window: Vec<Line> = all_lines[scroll..scroll + capacity.min(all_lines.len())].to_vec();
+ let end = (scroll + capacity).min(all_lines.len());
+ let window: Vec<Line> = all_lines[scroll..end].to_vec();
let position = if max_scroll > 0 {
format!(" · {}/{}", scroll + 1, max_scroll)
} else {
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 3d25c48..fdb2df6 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -2056,20 +2056,24 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let mut badges = Vec::new();
let mut badges_w = 0;
if a.is_core() {
- badges.push(ratatui::text::Span::styled("[Core] ", theme.lavender));
- badges_w += 7;
+ let label = "[Core] ";
+ badges_w += crate::tui::text::width(label);
+ badges.push(ratatui::text::Span::styled(label, theme.lavender));
}
if a.provides_meta {
- badges.push(ratatui::text::Span::styled("[Meta] ", theme.sapphire));
- badges_w += 7;
+ let label = "[Meta] ";
+ badges_w += crate::tui::text::width(label);
+ badges.push(ratatui::text::Span::styled(label, theme.sapphire));
}
if a.provides_stream {
- badges.push(ratatui::text::Span::styled("[Streams] ", theme.rating));
- badges_w += 10;
+ let label = "[Streams] ";
+ badges_w += crate::tui::text::width(label);
+ badges.push(ratatui::text::Span::styled(label, theme.rating));
}
if a.provides_catalog {
- badges.push(ratatui::text::Span::styled("[Catalog]", theme.teal));
- badges_w += 9;
+ let label = "[Catalog]";
+ badges_w += crate::tui::text::width(label);
+ badges.push(ratatui::text::Span::styled(label, theme.teal));
}
let prefix_w = 2;
let check_w = 4;
@@ -2135,20 +2139,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
.iter()
.map(|label| {
let (_, spacing) = crate::tui::overlay::browse_category_badge(label, theme);
- let badge_str = if label.to_ascii_lowercase().contains("movie")
- || label.to_ascii_lowercase().contains("top rated (all-time)")
- || label.to_ascii_lowercase().contains("top rated (recent")
- {
- "[MOVIES]"
- } else if label.to_ascii_lowercase().contains("series")
- || label.to_ascii_lowercase().contains("airing")
- || label.to_ascii_lowercase().contains("show")
- || label.to_ascii_lowercase().contains("tv")
- {
- "[SERIES]"
- } else {
- "[DISCOVER]"
- };
+ let badge_str = crate::tui::overlay::browse_category_badge_text(label);
format!(" {badge_str}{spacing}{label} ")
})
.collect();
@@ -2482,7 +2473,7 @@ fn render_provider_popup(
frame: &mut Frame,
area: Rect,
search_bar_area: Rect,
- state: &AppState,
+ state: &mut AppState,
theme: &Theme,
) {
if !state.show_provider_popup || search_bar_area.width == 0 {
@@ -2542,8 +2533,7 @@ fn render_provider_popup(
state.basic_terminal,
))
.highlight_symbol("");
- let mut list_state = state.provider_list_state;
- frame.render_stateful_widget(list, inner_area, &mut list_state);
+ frame.render_stateful_widget(list, inner_area, &mut state.provider_list_state);
}
pub fn search_results_layout(area: Rect) -> (Rect, Rect) {
@@ -2954,7 +2944,7 @@ mod tests {
.draw(|frame| {
let area = Rect::new(0, 0, 80, 24);
let search_bar = Rect::new(10, 2, 60, 3);
- render_provider_popup(frame, area, search_bar, &state, &theme);
+ render_provider_popup(frame, area, search_bar, &mut state, &theme);
})
.unwrap();
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 268f69a..4ae1fe2 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -583,11 +583,13 @@ impl AppState {
if available_providers.is_empty() {
return self.active_provider;
}
- let current = available_providers
+ match available_providers
.iter()
.position(|provider| *provider == self.active_provider)
- .unwrap_or(0);
- available_providers[(current + 1) % available_providers.len()]
+ {
+ None => available_providers[0],
+ Some(current) => available_providers[(current + 1) % available_providers.len()],
+ }
}
pub fn notify(
diff --git a/src/tui/text.rs b/src/tui/text.rs
index bbde58d..681a09a 100644
--- a/src/tui/text.rs
+++ b/src/tui/text.rs
@@ -435,38 +435,7 @@ pub fn format_subtitle_label(name: &str) -> String {
}
}
-pub fn strip_emojis(input: &str) -> String {
- input
- .chars()
- .filter(|&c| {
- let u = c as u32;
- !((0x1F000..=0x1FAFF).contains(&u)
- || (0x2600..=0x27BF).contains(&u)
- || (0x2300..=0x23FF).contains(&u)
- || (0x2B00..=0x2BFF).contains(&u)
- || (0xFE00..=0xFE0F).contains(&u)
- || u == 0x200D)
- })
- .collect::<String>()
-}
-
-pub fn clean_stream_text(input: &str) -> String {
- let without_emojis = strip_emojis(input);
- let mut cleaned = String::new();
- let mut last_was_space = false;
- for c in without_emojis.chars() {
- if c.is_whitespace() {
- if !last_was_space && !cleaned.is_empty() {
- cleaned.push(' ');
- last_was_space = true;
- }
- } else {
- cleaned.push(c);
- last_was_space = false;
- }
- }
- cleaned.trim().to_string()
-}
+pub use crate::providers::models::{clean_stream_text, strip_emojis};
pub const CTRL_S_STR: &str = if cfg!(target_os = "macos") {
"^S"
@@ -530,14 +499,7 @@ pub fn wrap_text(text: &str, max_width: usize) -> Vec<String> {
}
pub use crate::net::is_http_url;
-pub fn extract_4digit_year(raw: &str) -> String {
- raw.as_bytes()
- .windows(4)
- .find(|window| window.iter().all(u8::is_ascii_digit) && matches!(window[0], b'1' | b'2'))
- .and_then(|window| std::str::from_utf8(window).ok())
- .map(str::to_string)
- .unwrap_or_default()
-}
+pub use crate::providers::models::extract_4digit_year;
pub fn format_duration(secs: u64) -> String {
let h = secs / 3600;
diff --git a/tests/settings_hub.rs b/tests/settings_hub.rs
index df368c3..a93b827 100644
--- a/tests/settings_hub.rs
+++ b/tests/settings_hub.rs
@@ -47,6 +47,7 @@ fn test_settings_command_parsing_and_aliases() {
"/favorites".to_string(),
"/clear".to_string(),
"/help".to_string(),
+ "/exit".to_string(),
]
);