xget 0.1.1

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

use anyhow::Result;

use crate::engine::{EngineSummary, Input, Operation, Output};
use crate::request::{self, ReqOptions};

pub struct ReqInput {
    pub url: String,
    pub opts: ReqOptions,
}

impl ReqInput {
    pub fn new(url: impl Into<String>, opts: ReqOptions) -> Self {
        Self {
            url: url.into(),
            opts,
        }
    }
}

impl Input for ReqInput {
    fn label(&self) -> &'static str {
        "req"
    }

    async fn open(&self) -> Result<()> {
        request::parsed_http_url(&self.url).map(|_| ())
    }

    async fn size(&self) -> Result<Option<u64>> {
        Ok(None)
    }

    async fn read_range(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
        let mut o = self.opts.clone();
        o.headers
            .push(format!("Range: bytes={}-{}", offset, offset + len - 1));
        let res = request::fetch(&self.url, &o).await?;
        Ok(res.body)
    }

    async fn download(&self, _op: &Operation, out: &Output) -> Result<EngineSummary> {
        let started = std::time::Instant::now();
        let mut opts = self.opts.clone();
        opts.output = match out {
            Output::File(p) => Some(p.clone()),
            Output::Null => Some(std::path::PathBuf::from("/dev/null")),
            Output::Stdout => None,
            Output::Dir(d) => Some(d.clone()),
        };
        request::run_req(&self.url, &opts).await?;
        let total = match out {
            Output::File(p) => std::fs::metadata(p).map(|m| m.len()).unwrap_or(0),
            _ => 0,
        };
        let secs = started.elapsed().as_secs_f64().max(0.001);
        Ok(EngineSummary {
            total_bytes: total,
            elapsed_secs: secs,
            avg_bps: total as f64 / secs,
            mirrors: vec![],
        })
    }
}