xget 0.1.1

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

use std::time::Duration;

use anyhow::{Context, Result, bail};

use crate::engine::{EngineSummary, Input, Operation, Output};
use crate::inputs::HttpInput;

const API_PROBE: Duration = Duration::from_secs(2);

#[derive(Debug, Clone)]
pub struct IpfsParts {
    pub cid: String,
    pub subpath: String,
}

pub struct IpfsInput {
    pub url: String,
}

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

    pub fn parse(url: &str) -> Result<IpfsParts> {
        let u = url::Url::parse(url).with_context(|| format!("invalid IPFS URL: {url}"))?;
        if u.scheme() != "ipfs" {
            bail!("not an ipfs URL: {url}");
        }
        let mut segs: Vec<String> = Vec::new();
        if let Some(h) = u.host_str() {
            segs.push(h.to_string());
        }
        if let Some(seg) = u.path_segments() {
            segs.extend(seg.filter(|p| !p.is_empty()).map(|s| s.to_string()));
        }
        if segs.first().is_some_and(|s| s == "ipfs") {
            segs.remove(0);
        }
        let Some(cid) = segs.first().cloned() else {
            bail!("IPFS URL has no CID: {url} (need ipfs://<CID>[/path])");
        };
        if !valid_cid(&cid) {
            bail!("bad IPFS CID: {cid}");
        }
        let subpath = segs[1..].join("/");
        Ok(IpfsParts { cid, subpath })
    }

    async fn effective_base() -> String {
        if Self::daemon_up().await {
            return "http://127.0.0.1:8080".into();
        }
        public_gateway()
    }

    async fn daemon_up() -> bool {
        let Ok(client) = reqwest::Client::builder()
            .connect_timeout(API_PROBE)
            .build()
        else {
            return false;
        };
        let Ok(resp) = tokio::time::timeout(
            API_PROBE,
            client.post("http://127.0.0.1:5001/api/v0/version").send(),
        )
        .await
        else {
            return false;
        };
        resp.is_ok_and(|r| r.status().is_success())
    }

    fn object_url(base: &str, parts: &IpfsParts) -> String {
        let mut url = format!("{}/ipfs/{}", base.trim_end_matches('/'), parts.cid);
        if !parts.subpath.is_empty() {
            url.push('/');
            url.push_str(&parts.subpath);
        }
        url
    }

    async fn http_for(&self, base: &str) -> Result<HttpInput> {
        let parts = Self::parse(&self.url)?;
        Ok(HttpInput::new(Self::object_url(base, &parts)))
    }

    async fn download_via(
        &self,
        op: &Operation,
        out: &Output,
        base: &str,
    ) -> Result<EngineSummary> {
        self.http_for(base).await?.download(op, out).await
    }
}

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

    async fn open(&self) -> Result<()> {
        let base = Self::effective_base().await;
        self.http_for(&base).await?.open().await
    }

    async fn size(&self) -> Result<Option<u64>> {
        let base = Self::effective_base().await;
        self.http_for(&base).await?.size().await
    }

    async fn read_range(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
        let base = Self::effective_base().await;
        self.http_for(&base).await?.read_range(offset, len).await
    }

    async fn download(&self, op: &Operation, out: &Output) -> Result<EngineSummary> {
        let base = Self::effective_base().await;
        self.download_via(op, out, &base).await
    }
}

fn public_gateway() -> String {
    std::env::var("XGET_IPFS_GATEWAY")
        .map(|s| s.trim_end_matches('/').to_string())
        .unwrap_or_else(|_| "https://ipfs.io".into())
}

fn valid_cid(cid: &str) -> bool {
    if cid.len() < 40 || cid.len() > 128 {
        return false;
    }
    cid.chars().all(|c| c.is_ascii_alphanumeric())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::{DownloadParams, Operation, Output};

    #[test]
    fn parse_ipfs_url_shapes() {
        let p = IpfsInput::parse("ipfs://bafybeihdwdcefinitelyvalidcid0123456789abcdef").unwrap();
        assert!(p.cid.starts_with("bafy"));
        assert!(p.subpath.is_empty());
        let p = IpfsInput::parse("ipfs://QmYwAPJzv9CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme")
            .unwrap();
        assert_eq!(p.subpath, "readme");
        let p =
            IpfsInput::parse("ipfs:///ipfs/bafybeihdwdcefinitelyvalidcid0123456789abcdef/f.txt")
                .unwrap();
        assert_eq!(p.subpath, "f.txt");
        assert!(IpfsInput::parse("https://ipfs.io/ipfs/bafyabc").is_err());
        assert!(IpfsInput::parse("ipfs://too-short").is_err());
        assert!(IpfsInput::parse("ipfs://").is_err());
    }

    #[test]
    fn object_url_building() {
        let parts = IpfsParts {
            cid: "bafyabc".into(),
            subpath: "a/b.txt".into(),
        };
        assert_eq!(
            IpfsInput::object_url("https://ipfs.io/", &parts),
            "https://ipfs.io/ipfs/bafyabc/a/b.txt"
        );
    }

    #[tokio::test]
    async fn daemon_probe_returns_without_hanging() {
        let up = tokio::time::timeout(Duration::from_secs(10), IpfsInput::daemon_up()).await;
        assert!(up.is_ok(), "daemon probe must not hang");
    }

    async fn start_mock_gateway(data: Vec<u8>) -> String {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let shared = std::sync::Arc::new(data);
        tokio::spawn(async move {
            loop {
                let Ok((mut s, _)) = listener.accept().await else {
                    break;
                };
                let shared = shared.clone();
                tokio::spawn(async move {
                    let mut buf = vec![0u8; 65536];
                    while let Ok(n) = AsyncReadExt::read(&mut s, &mut buf).await {
                        if n == 0 {
                            break;
                        }
                        let req = String::from_utf8_lossy(&buf[..n]).to_string();
                        if !req.contains("/ipfs/") {
                            let r = "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: keep-alive\r\n\r\n";
                            let _ = AsyncWriteExt::write_all(&mut s, r.as_bytes()).await;
                            continue;
                        }
                        let range = req
                            .lines()
                            .find_map(|l| {
                                l.strip_prefix("Range:")
                                    .or_else(|| l.strip_prefix("range:"))
                            })
                            .map(|v| v.trim().to_string());
                        if let Some(r) = range {
                            let nums: Vec<u64> = r
                                .trim_start_matches("bytes=")
                                .split('-')
                                .map(|x| x.parse().unwrap_or(0))
                                .collect();
                            let (from, to) = (nums[0], nums[1].min(shared.len() as u64 - 1));
                            let body = &shared[from as usize..=to as usize];
                            let h = format!(
                                "HTTP/1.1 206 Partial Content\r\ncontent-range: bytes {from}-{to}/{}\r\ncontent-length: {}\r\naccept-ranges: bytes\r\nconnection: keep-alive\r\n\r\n",
                                shared.len(),
                                body.len()
                            );
                            let _ = AsyncWriteExt::write_all(&mut s, h.as_bytes()).await;
                            let _ = AsyncWriteExt::write_all(&mut s, body).await;
                        } else {
                            let h = format!(
                                "HTTP/1.1 200 OK\r\ncontent-length: {}\r\naccept-ranges: bytes\r\nconnection: keep-alive\r\n\r\n",
                                shared.len()
                            );
                            let _ = AsyncWriteExt::write_all(&mut s, h.as_bytes()).await;
                            let _ = AsyncWriteExt::write_all(&mut s, &shared).await;
                        }
                    }
                });
            }
        });
        base
    }

    fn sample(n: usize) -> Vec<u8> {
        (0..n).map(|i| (i * 29 % 251) as u8).collect()
    }

    #[tokio::test]
    async fn ipfs_download_via_mock_gateway() {
        let data = sample(600_000);
        let base = start_mock_gateway(data.clone()).await;
        let cid = "bafybeihdwdcefinitelyvalidcid0123456789abcdef";
        let input = IpfsInput::new(format!("ipfs://{cid}/file.bin"));
        let op = Operation::Download(DownloadParams {
            retries: 2,
            ..Default::default()
});
        let dir = std::env::temp_dir().join(format!("xget-ipfs-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let target = dir.join("file.bin");
        let http = input.http_for(&base).await.unwrap();
        assert_eq!(http.size().await.unwrap(), Some(data.len() as u64));
        assert_eq!(http.read_range(5000, 1000).await.unwrap(), data[5000..6000]);
        input
            .download_via(&op, &Output::File(target.clone()), &base)
            .await
            .unwrap();
        assert_eq!(std::fs::read(&target).unwrap(), data);
        let _ = std::fs::remove_dir_all(&dir);
    }
}