Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
refactor(core): centralize atomic file writing, md5 hex digest, and text extraction helpers
Samir Hossains7f44c2c2ac8b
diff --git a/src/cache.rs b/src/cache.rsindex 816de4e..36037df 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -33,6 +33,59 @@ fn read_json_cache(path: &PathBuf, expiry_secs: u64) -> Option<serde_json::ValueNone}+pub fn md5_hex(value: &str) -> String {+ use md5::{Digest, Md5};+ let mut hasher = Md5::new();+ hasher.update(value.as_bytes());+ let result = hasher.finalize();+ let mut safe_query = String::with_capacity(32);+ for b in result {+ use std::fmt::Write;+ let _ = write!(&mut safe_query, "{:02x}", b);+ }+ safe_query+}++pub fn atomic_write_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).ok();+ }+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos();+ let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));+ std::fs::write(&temporary, bytes)?;+ if std::fs::rename(&temporary, path).is_err() {+ let _ = std::fs::remove_file(path);+ if let Err(error) = std::fs::rename(&temporary, path) {+ let _ = std::fs::remove_file(&temporary);+ return Err(error);+ }+ }+ Ok(())+}++pub async fn atomic_write_file_async(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {+ if let Some(parent) = path.parent() {+ tokio::fs::create_dir_all(parent).await.ok();+ }+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_nanos();+ let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));+ tokio::fs::write(&temporary, bytes).await?;+ if tokio::fs::rename(&temporary, path).await.is_err() {+ let _ = tokio::fs::remove_file(path).await;+ if let Err(error) = tokio::fs::rename(&temporary, path).await {+ let _ = tokio::fs::remove_file(&temporary).await;+ return Err(error);+ }+ }+ Ok(())+}+fn write_json_cache(path: &PathBuf, data: &serde_json::Value) {if data.is_null() {return;@@ -44,27 +97,11 @@ fn write_json_cache(path: &PathBuf, data: &serde_json::Value) {);return;};- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));- if fs::write(&temporary, content).is_err() {+ if let Err(error) = atomic_write_file(path, &content) {log::warn!(- "failed to write cache to {}",- crate::logging::sanitize_path(&temporary)+ "failed to commit cache to {}: {error}",+ crate::logging::sanitize_path(path));- return;- }- if fs::rename(&temporary, path).is_err() {- let _ = fs::remove_file(path);- if fs::rename(&temporary, path).is_err() {- log::warn!(- "failed to commit cache to {}",- crate::logging::sanitize_path(path)- );- let _ = fs::remove_file(temporary);- }}}@@ -81,16 +118,7 @@ fn stream_payload_has_results(data: &serde_json::Value) -> bool {}fn hash_key(value: &str) -> String {- use md5::{Digest, Md5};- let mut hasher = Md5::new();- hasher.update(value.as_bytes());- let result = hasher.finalize();- let mut safe_query = String::with_capacity(32);- for b in result {- use std::fmt::Write;- let _ = write!(&mut safe_query, "{:02x}", b);- }- safe_query+ md5_hex(value)}pub fn get_provider_cache_dir(provider: ProviderKind, subdir: &str) -> PathBuf {@@ -355,27 +383,11 @@ pub fn get_namespaced_image_cache(namespace: &str, id: &str) -> Option<Vec<u8>>pub fn set_namespaced_image_cache(namespace: &str, id: &str, bytes: &[u8]) {let path = get_namespaced_image_path(namespace, id);- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));- if std::fs::write(&temporary, bytes).is_err() {+ if let Err(error) = atomic_write_file(&path, bytes) {log::warn!(- "failed to write image cache to {}",- crate::logging::sanitize_path(&temporary)+ "failed to commit image cache to {}: {error}",+ crate::logging::sanitize_path(&path));- return;- }- if std::fs::rename(&temporary, &path).is_err() {- let _ = std::fs::remove_file(&path);- if std::fs::rename(&temporary, &path).is_err() {- log::warn!(- "failed to commit image cache to {}",- crate::logging::sanitize_path(&path)- );- let _ = std::fs::remove_file(temporary);- }}}diff --git a/src/config.rs b/src/config.rsindex 465018d..b7ba3d1 100644--- a/src/config.rs+++ b/src/config.rs@@ -106,21 +106,8 @@ pub fn save(config: &Config) {"default_player": config.default_player,"download_dir": config.download_dir});- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));- if let Err(error) = std::fs::write(&temporary, json.to_string()) {+ if let Err(error) = crate::cache::atomic_write_file(&path, json.to_string().as_bytes()) {log::warn!("failed to write config: {error}");- return;- }- if std::fs::rename(&temporary, &path).is_err() {- let _ = std::fs::remove_file(&path);- if let Err(error) = std::fs::rename(&temporary, &path) {- let _ = std::fs::remove_file(&temporary);- log::warn!("failed to commit config: {error}");- }}}@@ -155,20 +142,7 @@ pub fn save_addons(addons: &[InstalledAddon]) {let Ok(json) = serde_json::to_string_pretty(addons) else {return;};- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-addons-{}-{stamp}", std::process::id()));- if let Err(error) = std::fs::write(&temporary, json) {+ if let Err(error) = crate::cache::atomic_write_file(&path, json.as_bytes()) {log::warn!("failed to write addons config: {error}");- return;- }- if std::fs::rename(&temporary, &path).is_err() {- let _ = std::fs::remove_file(&path);- if let Err(error) = std::fs::rename(&temporary, &path) {- let _ = std::fs::remove_file(&temporary);- log::warn!("failed to commit addons config: {error}");- }}}diff --git a/src/history.rs b/src/history.rsindex a698424..56948b4 100644--- a/src/history.rs+++ b/src/history.rs@@ -53,21 +53,8 @@ impl HistoryManager {pub fn save(&self) {if let Some(path) = Self::history_file_path() {if let Ok(content) = serde_json::to_string(self) {- let stamp = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));- if let Err(error) = fs::write(&temporary, content) {+ if let Err(error) = crate::cache::atomic_write_file(&path, content.as_bytes()) {log::warn!("failed to save watch history: {error}");- return;- }- if fs::rename(&temporary, &path).is_err() {- let _ = fs::remove_file(&path);- if let Err(error) = fs::rename(&temporary, &path) {- let _ = fs::remove_file(&temporary);- log::warn!("failed to commit watch history: {error}");- }}}}diff --git a/src/providers/addons/adapter.rs b/src/providers/addons/adapter.rsindex 348afea..71fca93 100644--- a/src/providers/addons/adapter.rs+++ b/src/providers/addons/adapter.rs@@ -12,12 +12,7 @@ pub fn meta_to_search_result(item: &MetaItem) -> SearchResult {.as_deref().or(item.year.as_deref()).or(item.released.as_deref())- .map(|s| {- s.chars()- .filter(|c| c.is_ascii_digit())- .take(4)- .collect::<String>()- })+ .map(crate::tui::text::extract_4digit_year).unwrap_or_default();let title = if !item.name.trim().is_empty() {@@ -54,12 +49,7 @@ pub fn metas_to_moviebox_search_json(metas: Vec<MetaItem>) -> serde_json::Value.as_deref().or(item.year.as_deref()).or(item.released.as_deref())- .map(|s| {- s.chars()- .filter(|c| c.is_ascii_digit())- .take(4)- .collect::<String>()- })+ .map(crate::tui::text::extract_4digit_year).unwrap_or_default();let title = if !item.name.trim().is_empty() {@@ -138,11 +128,7 @@ pub fn meta_detail_to_moviebox_json(detail: &MetaDetail) -> serde_json::Value {.or(detail.year.as_deref()).or(detail.released.as_deref()).unwrap_or_default();- let year: String = year_raw- .chars()- .filter(|c| c.is_ascii_digit())- .take(4)- .collect();+ let year = crate::tui::text::extract_4digit_year(year_raw);let mut genres = detail.genres.clone();if genres.is_empty() {diff --git a/src/providers/tv/parser.rs b/src/providers/tv/parser.rsindex b42071a..6616651 100644--- a/src/providers/tv/parser.rs+++ b/src/providers/tv/parser.rs@@ -32,7 +32,7 @@ impl M3UParser {url: &str,) -> Result<Vec<Channel>, Box<dyn std::error::Error>> {let trimmed = url.trim();- let is_remote = trimmed.starts_with("http://") || trimmed.starts_with("https://");+ let is_remote = crate::tui::text::is_http_url(trimmed);let content = if is_remote {let file_path = self.cache_dir.join(cache_filename(trimmed));let mut needs_download = true;@@ -58,7 +58,7 @@ impl M3UParser {.error_for_status()?.text().await?;- let _ = write_cache_file(&file_path, res.as_bytes()).await;+ let _ = crate::cache::atomic_write_file_async(&file_path, res.as_bytes()).await;res} else {match tokio::fs::read_to_string(&file_path).await {@@ -98,7 +98,7 @@ impl M3UParser {if fresh_channels.is_empty() {return Ok(fresh_channels);}- let _ = write_cache_file(&file_path, fresh.as_bytes()).await;+ let _ = crate::cache::atomic_write_file_async(&file_path, fresh.as_bytes()).await;return Ok(fresh_channels);}Ok(channels)@@ -158,32 +158,6 @@ impl M3UParser {}}-async fn write_cache_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {- let stamp = SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));- tokio::fs::write(&temporary, bytes).await?;- if tokio::fs::rename(&temporary, path).await.is_err() {- let _ = tokio::fs::remove_file(path).await;- if let Err(error) = tokio::fs::rename(&temporary, path).await {- let _ = tokio::fs::remove_file(&temporary).await;- return Err(error);- }- }- Ok(())-}-fn cache_filename(raw: &str) -> String {- use md5::{Digest, Md5};- let mut hasher = Md5::new();- hasher.update(raw.as_bytes());- let result = hasher.finalize();- let mut name = String::with_capacity(32);- for byte in result {- use std::fmt::Write;- let _ = write!(&mut name, "{byte:02x}");- }- format!("{name}.m3u")+ format!("{}.m3u", crate::cache::md5_hex(raw))}diff --git a/src/tui/state.rs b/src/tui/state.rsindex 99f4cf0..262d8d2 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -456,8 +456,7 @@ pub enum TvManagerRow {}fn playlist_is_url(source: &str) -> bool {- let trimmed = source.trim_start();- trimmed.starts_with("http://") || trimmed.starts_with("https://")+ crate::tui::text::is_http_url(source)}#[derive(Debug, Clone, Copy, PartialEq, Eq)]diff --git a/src/tui/text.rs b/src/tui/text.rsindex 18cbd1b..9045d74 100644--- a/src/tui/text.rs+++ b/src/tui/text.rs@@ -213,3 +213,12 @@ pub fn wrap_text(text: &str, max_width: usize) -> Vec<String> {}lines}++pub fn is_http_url(source: &str) -> bool {+ let trimmed = source.trim();+ trimmed.starts_with("http://") || trimmed.starts_with("https://")+}++pub fn extract_4digit_year(raw: &str) -> String {+ raw.chars().filter(|c| c.is_ascii_digit()).take(4).collect()+}