xget 0.1.2

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::torrent;

pub struct TorrentInput {
    pub source: torrent::TorrentSource,
    pub output: Option<std::path::PathBuf>,
    pub download_dir: std::path::PathBuf,
    pub seed_minutes: u64,
    pub only_files: Option<Vec<usize>>,
}

impl TorrentInput {
    pub fn new(
        source: torrent::TorrentSource,
        output: Option<std::path::PathBuf>,
        download_dir: std::path::PathBuf,
        seed_minutes: u64,
        only_files: Option<Vec<usize>>,
    ) -> Self {
        Self {
            source,
            output,
            download_dir,
            seed_minutes,
            only_files,
        }
    }
}

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

    async fn open(&self) -> Result<()> {
        Ok(())
    }

    async fn size(&self) -> Result<Option<u64>> {
        if let torrent::TorrentSource::File(p) = &self.source {
            let b = std::fs::read(p).ok().unwrap_or_default();
            if let Ok(m) = torrent::parse_torrent_bytes(&b) {
                return Ok(Some(m.total_length));
            }
        }
        Ok(None)
    }

    async fn read_range(&self, _offset: u64, _len: u64) -> Result<Vec<u8>> {
        anyhow::bail!("torrent input streams pieces, not byte ranges (use download)")
    }

    async fn download(&self, op: &Operation, out: &Output) -> Result<EngineSummary> {
        let done = self.run_full(op, out).await?;
        Ok(EngineSummary {
            total_bytes: done.total_bytes,
            elapsed_secs: done.summary.elapsed_secs,
            avg_bps: done.summary.avg_bps,
            mirrors: Vec::new(),
        })
    }
}

impl TorrentInput {
    pub async fn run_full(&self, op: &Operation, _out: &Output) -> Result<torrent::TorrentDone> {
        if !matches!(op, Operation::Download(_)) {
            anyhow::bail!("torrent input needs Operation::Download");
        }
        let opts = if let Operation::Download(p) = op {
            torrent::TorrentOptions {
                seed_minutes: self.seed_minutes,
                only_files: self.only_files.clone(),
                proxy: p.proxy.clone(),
            }
        } else {
            torrent::TorrentOptions {
                seed_minutes: self.seed_minutes,
                only_files: self.only_files.clone(),
                proxy: None,
            }
        };
        torrent::run(&self.source, self.output.clone(), &self.download_dir, &opts).await
    }
}