xget 0.1.0

xget: fast multi-connection download manager for the terminal: segmented Range downloads, queue, torrents, and curl-like requests.
use std::path::PathBuf;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

pub const DEFAULT_CONNECTIONS: usize = 16;
pub const MAX_CONNECTIONS: usize = 32;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    pub connections: usize,
    pub download_dir: PathBuf,
    pub speed_limit_bps: Option<u64>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            connections: DEFAULT_CONNECTIONS,
            download_dir: default_download_dir(),
            speed_limit_bps: None,
        }
    }
}

pub fn default_download_dir() -> PathBuf {
    if let Some(home) = dirs::home_dir() {
        let dl = home.join("Downloads");
        if dl.exists() {
            return dl;
        }
        return home;
    }
    PathBuf::from(".")
}

pub fn config_path() -> PathBuf {
    if let Ok(v) = std::env::var("XGET_CONFIG")
        && !v.trim().is_empty()
    {
        return PathBuf::from(v);
    }
    if let Some(dir) = dirs::config_dir() {
        return dir.join("xget").join("config.json");
    }
    PathBuf::from(".xget-config.json")
}

impl Config {
    pub fn load() -> Result<Self> {
        let path = config_path();
        if !path.exists() {
            return Ok(Self::default());
        }
        let raw = std::fs::read_to_string(&path)
            .with_context(|| format!("cannot read {}", path.display()))?;
        if raw.trim().is_empty() {
            return Ok(Self::default());
        }
        let mut cfg: Config = serde_json::from_str(&raw).context("invalid config file format")?;
        cfg.connections = cfg.connections.clamp(1, MAX_CONNECTIONS);
        Ok(cfg)
    }

    pub fn save(&self) -> Result<()> {
        let path = config_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("cannot create directory {}", parent.display()))?;
        }
        let raw = serde_json::to_string_pretty(self)?;
        std::fs::write(&path, raw)?;
        Ok(())
    }

    pub fn effective_connections(&self, override_v: Option<usize>) -> usize {
        override_v
            .unwrap_or(self.connections)
            .clamp(1, MAX_CONNECTIONS)
    }
}

pub fn parse_speed_limit(s: &str) -> Result<Option<u64>> {
    let t = s.trim().to_lowercase().replace([' ', '_'], "");
    if t.is_empty() || t == "0" || t == "unlimited" || t == "none" || t == "off" {
        return Ok(None);
    }
    let (num_part, mult): (&str, f64) = if let Some(stripped) = t.strip_suffix("kb") {
        (stripped, 1024.0)
    } else if let Some(stripped) = t.strip_suffix("mb") {
        (stripped, 1024.0 * 1024.0)
    } else if let Some(stripped) = t.strip_suffix("gb") {
        (stripped, 1024.0 * 1024.0 * 1024.0)
    } else if let Some(stripped) = t.strip_suffix('k') {
        (stripped, 1024.0)
    } else if let Some(stripped) = t.strip_suffix('m') {
        (stripped, 1024.0 * 1024.0)
    } else if let Some(stripped) = t.strip_suffix('g') {
        (stripped, 1024.0 * 1024.0 * 1024.0)
    } else if let Some(stripped) = t.strip_suffix("bps") {
        (stripped, 1.0)
    } else if let Some(stripped) = t.strip_suffix('b') {
        (stripped, 1.0)
    } else {
        (t.as_str(), 1.0)
    };
    let n: f64 = num_part
        .parse()
        .with_context(|| format!("invalid speed limit: '{s}' (examples: 500K, 2M, 0)"))?;
    if n <= 0.0 {
        return Ok(None);
    }
    Ok(Some((n * mult) as u64))
}

pub fn format_speed(bps: f64) -> String {
    const UNITS: [&str; 5] = ["B/s", "KiB/s", "MiB/s", "GiB/s", "TiB/s"];
    let mut v = bps;
    let mut u = 0;
    while v >= 1024.0 && u + 1 < UNITS.len() {
        v /= 1024.0;
        u += 1;
    }
    if u == 0 {
        format!("{v:.0} {}", UNITS[u])
    } else {
        format!("{v:.2} {}", UNITS[u])
    }
}

pub fn format_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut v = bytes as f64;
    let mut u = 0;
    while v >= 1024.0 && u + 1 < UNITS.len() {
        v /= 1024.0;
        u += 1;
    }
    if u == 0 {
        format!("{bytes} {}", UNITS[u])
    } else {
        format!("{v:.2} {}", UNITS[u])
    }
}

#[allow(dead_code)]
pub fn format_duration(secs: u64) -> String {
    let h = secs / 3600;
    let m = (secs % 3600) / 60;
    let s = secs % 60;
    if h > 0 {
        format!("{h}h {m}m {s}s")
    } else if m > 0 {
        format!("{m}m {s}s")
    } else {
        format!("{s}s")
    }
}

pub fn format_duration_precise(secs: f64) -> String {
    if secs >= 60.0 {
        let h = (secs / 3600.0) as u64;
        let m = ((secs % 3600.0) / 60.0) as u64;
        let s = secs % 60.0;
        if h > 0 {
            format!("{h}h {m}m {s:.1}s")
        } else {
            format!("{m}m {s:.1}s")
        }
    } else {
        format!("{secs:.2}s")
    }
}