xget 0.1.1

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

use std::path::Path;
use std::time::Duration;

use anyhow::{Context, Result};

use crate::downloader::{self, DownloadOptions};
use crate::engine::{EngineSummary, Input, Operation, Output};

pub struct HttpInput {
    pub url: String,
}

impl HttpInput {
    pub fn new(url: impl Into<String>) -> Self {
        Self { url: url.into() }
    }

    fn opts(op: &Operation) -> Result<DownloadOptions> {
        match op {
            Operation::Download(p) => Ok(DownloadOptions {
                connections: p.connections,
                speed_limit_bps: p.speed_limit_bps,
                retries: p.retries,
                mirrors: p.mirrors.clone(),
                allow_h3: p.allow_h3,
                auto_mirror: p.auto_mirror,
                proxy: p.proxy.clone(),
            }),
            _ => anyhow::bail!("http input needs Operation::Download"),
        }
    }

    fn out_path<'a>(out: &'a Output, fallback: &'a Path) -> &'a Path {
        match out {
            Output::File(p) => p,
            Output::Dir(d) => d,
            Output::Stdout | Output::Null => fallback,
        }
    }
}

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

    async fn open(&self) -> Result<()> {
        let client = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(10))
            .build()
            .context("cannot create HTTP client")?;
        client
            .head(&self.url)
            .send()
            .await
            .map(|_| ())
            .context("http open failed")
    }

    async fn size(&self) -> Result<Option<u64>> {
        let client = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(10))
            .build()
            .context("cannot create HTTP client")?;
        let resp = client
            .get(&self.url)
            .header(reqwest::header::RANGE, "bytes=0-0")
            .header(reqwest::header::ACCEPT_ENCODING, "identity")
            .send()
            .await
            .context("http size probe failed")?;
        if resp.status() == reqwest::StatusCode::PARTIAL_CONTENT
            && let Some(v) = resp.headers().get(reqwest::header::CONTENT_RANGE)
            && let Ok(s) = v.to_str()
            && let Some(total) = s
                .rsplit('/')
                .next()
                .and_then(|t| t.trim().parse::<u64>().ok())
        {
            return Ok(Some(total));
        }
        Ok(resp
            .headers()
            .get(reqwest::header::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.trim().parse::<u64>().ok()))
    }

    async fn read_range(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
        let client = reqwest::Client::builder()
            .connect_timeout(Duration::from_secs(10))
            .build()
            .context("cannot create HTTP client")?;
        let resp = client
            .get(&self.url)
            .header(
                reqwest::header::RANGE,
                format!("bytes={}-{}", offset, offset + len - 1),
            )
            .header(reqwest::header::ACCEPT_ENCODING, "identity")
            .send()
            .await
            .context("http range read failed")?;
        if resp.status() != reqwest::StatusCode::PARTIAL_CONTENT {
            anyhow::bail!("server rejected Range (HTTP {})", resp.status());
        }
        resp.bytes()
            .await
            .map(|b| b.to_vec())
            .context("cannot read range body")
    }

    async fn download(&self, op: &Operation, out: &Output) -> Result<EngineSummary> {
        let opts = Self::opts(op)?;
        let target: &Path = Self::out_path(out, Path::new(&self.url));
        let sum = downloader::run_download(&self.url, target, &opts).await?;
        Ok(EngineSummary {
            total_bytes: sum.total_bytes,
            elapsed_secs: sum.elapsed_secs,
            avg_bps: sum.avg_bps,
            mirrors: sum.mirrors,
        })
    }
}