Check / stable / fmt (push) Failing after 26s
Check / beta / clippy (push) Failing after 1m10s
Check / stable / clippy (push) Failing after 1m10s
Check / nightly / doc (push) Successful in 1m0s
Check / 1.95.0 / check (push) Successful in 1m7s
Check / dockerfile / msrv (push) Successful in 5s
Test Suite / ubuntu / beta (push) Successful in 2m15s
Test Suite / ubuntu / stable (push) Successful in 2m14s
Test Suite / ubuntu / stable / coverage (push) Failing after 1m57s
Test Suite / macos-latest / stable (push) Canceled after 0s
Test Suite / windows-latest / stable (push) Canceled after 0s
477 lines
14 KiB
Rust
477 lines
14 KiB
Rust
use std::fs::{self, File};
|
|
use std::io::{BufRead, BufReader, Seek, SeekFrom};
|
|
use std::path::PathBuf;
|
|
use std::process;
|
|
use std::sync::{Arc, Once};
|
|
use std::time::Duration;
|
|
|
|
use anyhow::Result;
|
|
use anyhow::{Context, Error, anyhow};
|
|
use colored::Colorize;
|
|
use indicatif::{ProgressBar, ProgressStyle};
|
|
use log::{LevelFilter, error};
|
|
use log4rs::append::rolling_file::RollingFileAppender;
|
|
use log4rs::append::rolling_file::policy::compound::CompoundPolicy;
|
|
use log4rs::append::rolling_file::policy::compound::roll::fixed_window::FixedWindowRoller;
|
|
use log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger;
|
|
use log4rs::config::{Appender, Root};
|
|
use log4rs::encode::pattern::PatternEncoder;
|
|
use regex::Regex;
|
|
use reqwest::{Certificate, Client};
|
|
use serde::Serialize;
|
|
use serde_json::Value;
|
|
use tokio::sync::Mutex;
|
|
use tokio_util::sync::CancellationToken;
|
|
|
|
use crate::app::{App, AppConfig, log_and_print_error};
|
|
use crate::cli::{self, Command};
|
|
use crate::models::Route;
|
|
use crate::network::{Network, NetworkError};
|
|
use crate::ui::theme::ThemeDefinitionsWrapper;
|
|
|
|
#[cfg(test)]
|
|
#[path = "utils_tests.rs"]
|
|
mod utils_tests;
|
|
|
|
pub fn get_log_path() -> PathBuf {
|
|
let preferred = if cfg!(target_os = "linux") {
|
|
dirs_next::cache_dir().unwrap_or_else(|| PathBuf::from("~/.cache"))
|
|
} else if cfg!(target_os = "macos") {
|
|
dirs_next::home_dir()
|
|
.map(|h| h.join("Library/Logs"))
|
|
.unwrap_or_else(std::env::temp_dir)
|
|
} else {
|
|
dirs_next::data_local_dir().unwrap_or_else(|| PathBuf::from("C:\\Logs"))
|
|
}
|
|
.join("managarr");
|
|
|
|
resolve_log_dir(preferred).join("managarr.log")
|
|
}
|
|
|
|
fn resolve_log_dir(preferred: PathBuf) -> PathBuf {
|
|
static WARN_ONCE: Once = Once::new();
|
|
|
|
if let Err(e) = fs::create_dir_all(&preferred) {
|
|
WARN_ONCE.call_once(|| {
|
|
eprintln!(
|
|
"Failed to create log directory {}: {e}; file logging will be disabled",
|
|
preferred.display()
|
|
);
|
|
});
|
|
}
|
|
|
|
preferred
|
|
}
|
|
|
|
pub fn init_logging_config() -> log4rs::Config {
|
|
build_logging_config(get_log_path())
|
|
}
|
|
|
|
fn build_logging_config(log_path: PathBuf) -> log4rs::Config {
|
|
let archive_pattern = log_path
|
|
.with_file_name("managarr.{}.log")
|
|
.to_string_lossy()
|
|
.into_owned();
|
|
|
|
let trigger = SizeTrigger::new(10 * 1024 * 1024);
|
|
let roller = match FixedWindowRoller::builder().build(&archive_pattern, 3) {
|
|
Ok(roller) => roller,
|
|
Err(e) => {
|
|
eprintln!(
|
|
"Failed to build log roller for {archive_pattern}: {e}; file logging will be disabled"
|
|
);
|
|
return disabled_logging_config();
|
|
}
|
|
};
|
|
let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));
|
|
|
|
let logfile = match RollingFileAppender::builder()
|
|
.encoder(Box::new(PatternEncoder::new(
|
|
"{d(%Y-%m-%d %H:%M:%S%.3f)(utc)} <{i}> [{l}] {f}:{L} - {m}{n}",
|
|
)))
|
|
.build(&log_path, Box::new(policy))
|
|
{
|
|
Ok(logfile) => logfile,
|
|
Err(e) => {
|
|
eprintln!(
|
|
"Failed to build rolling file appender for {}: {e}; file logging will be disabled",
|
|
log_path.display()
|
|
);
|
|
return disabled_logging_config();
|
|
}
|
|
};
|
|
|
|
match log4rs::Config::builder()
|
|
.appender(Appender::builder().build("logfile", Box::new(logfile)))
|
|
.build(
|
|
Root::builder()
|
|
.appender("logfile")
|
|
.build(LevelFilter::Debug),
|
|
) {
|
|
Ok(config) => config,
|
|
Err(e) => {
|
|
eprintln!("Failed to build logging config: {e}; file logging will be disabled");
|
|
disabled_logging_config()
|
|
}
|
|
}
|
|
}
|
|
|
|
fn disabled_logging_config() -> log4rs::Config {
|
|
log4rs::Config::builder()
|
|
.build(Root::builder().build(LevelFilter::Debug))
|
|
.expect("appender-free logging config is infallibly valid")
|
|
}
|
|
|
|
pub fn format_size(bytes: i64, precision: usize) -> String {
|
|
if bytes >= 1024i64.pow(3) {
|
|
let gb = bytes as f64 / 1024f64.powi(3);
|
|
format!("{gb:.precision$} GB")
|
|
} else {
|
|
let mb = bytes as f64 / 1024f64.powi(2);
|
|
format!("{mb:.precision$} MB")
|
|
}
|
|
}
|
|
|
|
pub fn convert_runtime(runtime: i64) -> (i64, i64) {
|
|
let hours = runtime / 60;
|
|
let minutes = runtime % 60;
|
|
|
|
(hours, minutes)
|
|
}
|
|
|
|
pub async fn tail_logs(no_color: bool) -> Result<()> {
|
|
let re = Regex::new(r"^(?P<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})\s+<(?P<opid>[^\s>]+)>\s+\[(?P<level>[A-Z]+)]\s+(?P<logger>[^:]+):(?P<line>\d+)\s+-\s+(?P<message>.*)$").unwrap();
|
|
let file_path = get_log_path();
|
|
let file = File::open(&file_path).with_context(|| {
|
|
format!(
|
|
"Unable to open log file {}; file logging may be disabled",
|
|
file_path.display()
|
|
)
|
|
})?;
|
|
let mut reader = BufReader::new(file);
|
|
|
|
reader
|
|
.seek(SeekFrom::End(0))
|
|
.with_context(|| "Unable to tail log file")?;
|
|
|
|
tokio::task::spawn_blocking(move || {
|
|
let mut line_buf = String::new();
|
|
loop {
|
|
line_buf.clear();
|
|
match reader.read_line(&mut line_buf) {
|
|
Ok(0) => {
|
|
if was_log_rotated(&file_path, &mut reader) {
|
|
continue;
|
|
}
|
|
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
Ok(_) => {
|
|
let line = line_buf.trim_end();
|
|
if no_color {
|
|
println!("{line}");
|
|
} else {
|
|
let colored_line = colorize_log_line(line, &re);
|
|
println!("{colored_line}");
|
|
}
|
|
}
|
|
Err(_) => {
|
|
std::thread::sleep(Duration::from_millis(100));
|
|
}
|
|
}
|
|
}
|
|
})
|
|
.await?
|
|
}
|
|
|
|
pub(crate) fn was_log_rotated(file_path: &PathBuf, reader: &mut BufReader<File>) -> bool {
|
|
let current_pos = reader.stream_position().unwrap_or(0);
|
|
let file_len = fs::metadata(file_path).map(|m| m.len()).unwrap_or(0);
|
|
|
|
if file_len < current_pos
|
|
&& let Ok(new_file) = File::open(file_path)
|
|
{
|
|
*reader = BufReader::new(new_file);
|
|
return true;
|
|
}
|
|
|
|
false
|
|
}
|
|
|
|
fn colorize_log_line(line: &str, re: &Regex) -> String {
|
|
if let Some(caps) = re.captures(line) {
|
|
let level = &caps["level"];
|
|
let message = &caps["message"];
|
|
|
|
let colored_message = match level {
|
|
"ERROR" => message.red(),
|
|
"WARN" => message.yellow(),
|
|
"INFO" => message.green(),
|
|
"DEBUG" => message.blue(),
|
|
_ => message.normal(),
|
|
};
|
|
|
|
let timestamp = &caps["timestamp"];
|
|
let opid = &caps["opid"];
|
|
let logger = &caps["logger"];
|
|
let line_number = &caps["line"];
|
|
|
|
format!(
|
|
"{} <{}> [{}] {}:{} - {}",
|
|
timestamp.white(),
|
|
opid.cyan(),
|
|
level.bold(),
|
|
logger.magenta(),
|
|
line_number.bold(),
|
|
colored_message
|
|
)
|
|
} else {
|
|
line.to_string()
|
|
}
|
|
}
|
|
|
|
pub(super) fn load_config(path: &str) -> Result<AppConfig> {
|
|
match File::open(path).map_err(|e| anyhow!(e)) {
|
|
Ok(file) => {
|
|
let reader = BufReader::new(file);
|
|
let config = serde_yaml::from_reader(reader)?;
|
|
Ok(config)
|
|
}
|
|
Err(e) => {
|
|
log_and_print_error(format!("Unable to open config file '{path}': {e:?}"));
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn load_theme_config(path: &str) -> Result<ThemeDefinitionsWrapper> {
|
|
match File::open(path).map_err(|e| anyhow!(e)) {
|
|
Ok(file) => {
|
|
let reader = BufReader::new(file);
|
|
let theme_config = serde_yaml::from_reader(reader)?;
|
|
Ok(theme_config)
|
|
}
|
|
Err(e) => {
|
|
log_and_print_error(format!("Unable to open theme file: {e:?}"));
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn build_network_client(config: &AppConfig) -> Client {
|
|
let mut client_builder = Client::builder()
|
|
.pool_max_idle_per_host(10)
|
|
.http2_keep_alive_interval(Duration::from_secs(5))
|
|
.tcp_keepalive(Duration::from_secs(5));
|
|
|
|
if let Some(radarr_configs) = &config.radarr {
|
|
for radarr_config in radarr_configs {
|
|
if let Some(cert_path) = &radarr_config.ssl_cert_path {
|
|
let cert = create_cert(cert_path, "Radarr");
|
|
client_builder = client_builder.add_root_certificate(cert);
|
|
}
|
|
}
|
|
}
|
|
|
|
if let Some(sonarr_configs) = &config.sonarr {
|
|
for sonarr_config in sonarr_configs {
|
|
if let Some(cert_path) = &sonarr_config.ssl_cert_path {
|
|
let cert = create_cert(cert_path, "Sonarr");
|
|
client_builder = client_builder.add_root_certificate(cert);
|
|
}
|
|
}
|
|
}
|
|
|
|
match client_builder.build() {
|
|
Ok(client) => client,
|
|
Err(e) => {
|
|
error!("Unable to create reqwest client: {e}");
|
|
eprintln!("error: {}", e.to_string().red());
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn create_cert(cert_path: &String, servarr_name: &str) -> Certificate {
|
|
match fs::read(cert_path) {
|
|
Ok(cert) => match Certificate::from_pem(&cert) {
|
|
Ok(certificate) => certificate,
|
|
Err(_) => {
|
|
log_and_print_error(format!(
|
|
"Unable to read the specified {servarr_name} SSL certificate"
|
|
));
|
|
process::exit(1);
|
|
}
|
|
},
|
|
Err(_) => {
|
|
log_and_print_error(format!(
|
|
"Unable to open specified {servarr_name} SSL certificate"
|
|
));
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) fn render_spinner() -> ProgressBar {
|
|
let pb = ProgressBar::new_spinner();
|
|
pb.enable_steady_tick(Duration::from_millis(60));
|
|
pb.set_style(
|
|
ProgressStyle::with_template("{spinner:.blue}")
|
|
.unwrap()
|
|
.tick_strings(&[
|
|
"⢀⠀", "⡀⠀", "⠄⠀", "⢂⠀", "⡂⠀", "⠅⠀", "⢃⠀", "⡃⠀", "⠍⠀", "⢋⠀", "⡋⠀", "⠍⠁", "⢋⠁", "⡋⠁", "⠍⠉",
|
|
"⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⢈⠩", "⡀⢙", "⠄⡙", "⢂⠩", "⡂⢘", "⠅⡘", "⢃⠨", "⡃⢐",
|
|
"⠍⡐", "⢋⠠", "⡋⢀", "⠍⡁", "⢋⠁", "⡋⠁", "⠍⠉", "⠋⠉", "⠋⠉", "⠉⠙", "⠉⠙", "⠉⠩", "⠈⢙", "⠈⡙", "⠈⠩",
|
|
"⠀⢙", "⠀⡙", "⠀⠩", "⠀⢘", "⠀⡘", "⠀⠨", "⠀⢐", "⠀⡐", "⠀⠠", "⠀⢀", "⠀⡀",
|
|
]),
|
|
);
|
|
pb.set_message("Querying...");
|
|
pb
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct CliError<'a> {
|
|
error: CliErrorDetails<'a>,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct CliErrorDetails<'a> {
|
|
message: String,
|
|
status: Option<u16>,
|
|
body: Option<&'a Value>,
|
|
}
|
|
|
|
fn format_cli_error(error: &Error) -> String {
|
|
let details = match error.downcast_ref::<NetworkError>() {
|
|
Some(network_error) => CliErrorDetails {
|
|
message: network_error.message.clone(),
|
|
status: Some(network_error.status),
|
|
body: network_error.body.as_ref(),
|
|
},
|
|
None => CliErrorDetails {
|
|
message: error.to_string(),
|
|
status: None,
|
|
body: None,
|
|
},
|
|
};
|
|
|
|
serde_json::to_string_pretty(&CliError { error: details })
|
|
.expect("CLI error details are infallibly serializable")
|
|
}
|
|
|
|
pub(super) async fn start_cli_with_spinner(
|
|
config: AppConfig,
|
|
reqwest_client: Client,
|
|
cancellation_token: CancellationToken,
|
|
app: Arc<Mutex<App<'_>>>,
|
|
command: Command,
|
|
servarr_name: Option<&str>,
|
|
) {
|
|
config.verify_config_present_for_cli(&command);
|
|
{
|
|
let mut app = app.lock().await;
|
|
app.cli_mode = true;
|
|
select_cli_configuration(&mut app, &config, &command, servarr_name).unwrap_or_else(|error| {
|
|
error!("{error}");
|
|
eprintln!("{}", format_cli_error(&error));
|
|
process::exit(1);
|
|
});
|
|
}
|
|
let pb = render_spinner();
|
|
let app_nw = Arc::clone(&app);
|
|
let mut network = Network::new(&app_nw, cancellation_token, reqwest_client);
|
|
match cli::handle_command(&app, command, &mut network).await {
|
|
Ok(output) => {
|
|
pb.finish();
|
|
println!("{output}");
|
|
}
|
|
Err(e) => {
|
|
pb.finish();
|
|
eprintln!("{}", format_cli_error(&e));
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(super) async fn start_cli_no_spinner(
|
|
config: AppConfig,
|
|
reqwest_client: Client,
|
|
cancellation_token: CancellationToken,
|
|
app: Arc<Mutex<App<'_>>>,
|
|
command: Command,
|
|
servarr_name: Option<&str>,
|
|
) {
|
|
config.verify_config_present_for_cli(&command);
|
|
{
|
|
let mut app = app.lock().await;
|
|
app.cli_mode = true;
|
|
select_cli_configuration(&mut app, &config, &command, servarr_name).unwrap_or_else(|error| {
|
|
error!("{error}");
|
|
eprintln!("{}", format_cli_error(&error));
|
|
process::exit(1);
|
|
});
|
|
}
|
|
let app_nw = Arc::clone(&app);
|
|
let mut network = Network::new(&app_nw, cancellation_token, reqwest_client);
|
|
match cli::handle_command(&app, command, &mut network).await {
|
|
Ok(output) => {
|
|
println!("{output}");
|
|
}
|
|
Err(e) => {
|
|
eprintln!("{}", format_cli_error(&e));
|
|
process::exit(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn select_cli_configuration(
|
|
app: &mut App<'_>,
|
|
config: &AppConfig,
|
|
command: &Command,
|
|
servarr_name_arg: Option<&str>,
|
|
) -> Result<()> {
|
|
if let Some(servarr_name) = servarr_name_arg {
|
|
let trimmed_name = servarr_name.trim();
|
|
let selected_index = app.server_tabs.tabs.iter().position(|tab| {
|
|
tab.title == trimmed_name
|
|
&& matches!(
|
|
(&tab.route, command),
|
|
(Route::Radarr(..), Command::Radarr(_))
|
|
| (Route::Sonarr(..), Command::Sonarr(_))
|
|
| (Route::Lidarr(..), Command::Lidarr(_))
|
|
| (Route::Readarr(..), Command::Readarr(_))
|
|
)
|
|
});
|
|
app.server_tabs.index = selected_index.ok_or_else(|| {
|
|
anyhow!("A Servarr titled '{trimmed_name}' matching this command was not found in your configuration file")
|
|
})?;
|
|
} else {
|
|
match command {
|
|
Command::Radarr(_) => {
|
|
let default_radarr_config =
|
|
config.radarr.as_ref().expect("Radarr config must exist")[0].clone();
|
|
app.server_tabs.select_tab_by_config(&default_radarr_config);
|
|
}
|
|
Command::Sonarr(_) => {
|
|
let default_sonarr_config =
|
|
config.sonarr.as_ref().expect("Sonarr config must exist")[0].clone();
|
|
app.server_tabs.select_tab_by_config(&default_sonarr_config);
|
|
}
|
|
Command::Lidarr(_) => {
|
|
let default_lidarr_config =
|
|
config.lidarr.as_ref().expect("Lidarr config must exist")[0].clone();
|
|
app.server_tabs.select_tab_by_config(&default_lidarr_config);
|
|
}
|
|
Command::Readarr(_) => {
|
|
let default_readarr_config =
|
|
config.readarr.as_ref().expect("Readarr config must exist")[0].clone();
|
|
app
|
|
.server_tabs
|
|
.select_tab_by_config(&default_readarr_config);
|
|
}
|
|
_ => (),
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|