Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(logging): capture panic backtrace, flush buffers, and redact credentials
Samir Hossains719175f9bbac
diff --git a/src/config.rs b/src/config.rsindex 63c083f..24bf564 100644--- a/src/config.rs+++ b/src/config.rs@@ -137,6 +137,12 @@ pub fn cache_dir() -> PathBuf {}pub fn logs_dir() -> PathBuf {+ #[cfg(target_os = "windows")]+ {+ if let Some(dir) = dirs::data_local_dir() {+ return dir.join(APP_NAME).join("logs");+ }+ }data_dir().map(|dir| dir.join("logs")).unwrap_or_else(|| std::env::temp_dir().join(APP_NAME).join("logs"))diff --git a/src/logging.rs b/src/logging.rsindex 3bdb5d3..d69934a 100644--- a/src/logging.rs+++ b/src/logging.rs@@ -1,4 +1,7 @@-use flexi_logger::{Cleanup, Criterion, FileSpec, Logger, Naming, WriteMode};+use flexi_logger::{Cleanup, Criterion, FileSpec, Logger, LoggerHandle, Naming, WriteMode};+use std::sync::OnceLock;++static LOGGER_HANDLE: OnceLock<LoggerHandle> = OnceLock::new();pub fn init() {let default_level = if cfg!(debug_assertions) {@@ -13,31 +16,37 @@ pub fn init() {let log_dir = crate::config::logs_dir();- match Logger::try_with_str(&spec) {- Ok(logger) => {- if let Err(error) = logger- .log_to_file(- FileSpec::default()- .directory(&log_dir)- .basename(crate::config::APP_NAME),- )- .rotate(- Criterion::Size(5 * 1024 * 1024),- Naming::Numbers,- Cleanup::KeepLogFiles(3),- )- .write_mode(WriteMode::Direct)- .format(flexi_logger::opt_format)- .start()- {- eprintln!("[{}] logging unavailable: {error}", crate::config::APP_NAME);- }+ let logger_builder = Logger::try_with_str(&spec).unwrap_or_else(|error| {+ eprintln!(+ "[{}] invalid MOVIEBOX_LOG level '{}': {error}; falling back to '{}'",+ crate::config::APP_NAME,+ spec,+ default_level+ );+ Logger::try_with_str(default_level)+ .unwrap_or_else(|_| Logger::try_with_str("warn").unwrap())+ });++ match logger_builder+ .log_to_file(+ FileSpec::default()+ .directory(&log_dir)+ .basename(crate::config::APP_NAME),+ )+ .rotate(+ Criterion::Size(5 * 1024 * 1024),+ Naming::Numbers,+ Cleanup::KeepLogFiles(3),+ )+ .write_mode(WriteMode::Direct)+ .format(flexi_logger::opt_format)+ .start()+ {+ Ok(handle) => {+ let _ = LOGGER_HANDLE.set(handle);}Err(error) => {- eprintln!(- "[{}] invalid MOVIEBOX_LOG level: {error}",- crate::config::APP_NAME- );+ eprintln!("[{}] logging unavailable: {error}", crate::config::APP_NAME);}}@@ -50,6 +59,12 @@ pub fn init() {);}+pub fn flush() {+ if let Some(handle) = LOGGER_HANDLE.get() {+ handle.flush();+ }+}+pub fn log_file_path() -> std::path::PathBuf {crate::config::logs_dir().join(format!("{}_rCURRENT.log", crate::config::APP_NAME))}@@ -73,26 +88,65 @@ pub fn sanitize_url(raw: &str) -> String {let scheme = parsed.scheme();if host.is_empty() {"[redacted]".to_string()+ } else if let Some(port) = parsed.port() {+ format!("{scheme}://{host}:{port}")} else {format!("{scheme}://{host}")}}Err(_) => {let lower = raw.to_ascii_lowercase();- let host_start = lower.find("://").map(|index| index + 3);- match host_start {- Some(start) => {- let rest = &raw[start..];- let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());- let host = &rest[..host_end];- if host.is_empty() {- "[redacted]".to_string()- } else {- format!("https://{host}")- }+ if let Some(idx) = lower.find("://") {+ let scheme = &raw[..idx];+ let rest = &raw[idx + 3..];+ let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());+ let mut host = &rest[..host_end];+ if let Some(at_idx) = host.rfind('@') {+ host = &host[at_idx + 1..];+ }+ if host.is_empty() {+ "[redacted]".to_string()+ } else {+ format!("{scheme}://{host}")}- None => "[redacted]".to_string(),+ } else {+ "[redacted]".to_string()}}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_sanitize_url_valid() {+ assert_eq!(+ sanitize_url("https://example.com/path?token=secret#hash"),+ "https://example.com"+ );+ assert_eq!(+ sanitize_url("http://custom.tv:8080/live/user/pass/123.m3u8"),+ "http://custom.tv:8080"+ );+ }++ #[test]+ fn test_sanitize_url_with_credentials() {+ assert_eq!(+ sanitize_url("https://user:[email protected]/feed"),+ "https://example.com"+ );+ assert_eq!(+ sanitize_url("http://admin:[email protected]:8000/live.ts"),+ "http://stream.local:8000"+ );+ }++ #[test]+ fn test_sanitize_url_invalid() {+ assert_eq!(sanitize_url("not_a_url"), "[redacted]");+ assert_eq!(sanitize_url(""), "[redacted]");+ }+}diff --git a/src/main.rs b/src/main.rsindex c1db0af..692bc69 100644--- a/src/main.rs+++ b/src/main.rs@@ -114,9 +114,11 @@ async fn main() -> std::io::Result<()> {moviebox_tui::logging::init();std::panic::set_hook(Box::new(|info| {- log::error!("panic: {info}");+ let backtrace = std::backtrace::Backtrace::capture();+ log::error!("panic: {info}\nbacktrace:\n{backtrace}");+ moviebox_tui::logging::flush();restore_terminal();- eprintln!("{info}");+ eprintln!("{info}\n{backtrace}");}));let stdout = std::io::stdout();diff --git a/src/player/tracker.rs b/src/player/tracker.rsindex 30f456b..5f22cc1 100644--- a/src/player/tracker.rs+++ b/src/player/tracker.rs@@ -121,7 +121,10 @@ pub fn ensure_tracker_script() -> Option<PathBuf> {let dir = crate::config::scripts_dir()?;if !dir.exists() {if let Err(e) = fs::create_dir_all(&dir) {- log::warn!("failed to create scripts dir {}: {e}", dir.display());+ log::warn!(+ "failed to create scripts dir {}: {e}",+ crate::logging::sanitize_path(&dir)+ );return None;}}@@ -132,7 +135,10 @@ pub fn ensure_tracker_script() -> Option<PathBuf> {.unwrap_or(true){if let Err(e) = fs::write(&path, TRACKER_LUA_CONTENT.as_bytes()) {- log::warn!("failed to write tracker script {}: {e}", path.display());+ log::warn!(+ "failed to write tracker script {}: {e}",+ crate::logging::sanitize_path(&path)+ );return None;}}@@ -148,7 +154,10 @@ pub fn state_file_path(let dir = crate::config::playback_state_dir()?;if !dir.exists() {if let Err(e) = fs::create_dir_all(&dir) {- log::warn!("failed to create playback state dir {}: {e}", dir.display());+ log::warn!(+ "failed to create playback state dir {}: {e}",+ crate::logging::sanitize_path(&dir)+ );return None;}}diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex adbb234..cd5453f 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -451,6 +451,7 @@ impl App {})),}} else {+ log::info!("launching player: {kind:?}");spawn_configured_command(command, false)};@@ -494,6 +495,10 @@ impl App {match result {Ok(status) if status.success() => {+ log::info!(+ "player {kind:?} finished cleanly (duration: {}s)",+ start_time.elapsed().as_secs()+ );let has_tracker = tracker_opts.is_some()&& matches!(kind,@@ -663,8 +668,14 @@ fn is_user_quit(status: &std::process::ExitStatus) -> bool {}fn clean_player_error(code: Option<i32>, signal: Option<i32>, stderr: &str) -> String {- if !stderr.is_empty() {- return stderr.to_string();+ let trimmed = stderr.trim();+ if !trimmed.is_empty() {+ let bounded = if trimmed.len() > 512 {+ &trimmed[..512]+ } else {+ trimmed+ };+ return bounded.to_string();}if let Some(value) = code {