Skip to main content

kget/ftp/
client.rs

1//! FTP client implementation.
2
3use crate::config::ProxyConfig;
4use crate::optimization::Optimizer;
5use crate::progress::create_progress_bar;
6use crate::utils::print;
7use std::error::Error;
8use std::io::Write;
9use suppaftp::FtpStream;
10use url::Url;
11
12/// FTP file downloader with progress tracking.
13///
14/// Supports:
15/// - Anonymous FTP (use "anonymous" as username)
16/// - Authenticated FTP with username/password in URL
17/// - Binary transfer mode (safe for all file types)
18/// - SOCKS5 proxy connections
19///
20/// # URL Format
21///
22/// ```text
23/// ftp://[user[:password]@]host[:port]/path/to/file
24/// ```
25///
26/// # Example
27///
28/// ```rust,no_run
29/// use kget::ftp::FtpDownloader;
30/// use kget::{ProxyConfig, Optimizer};
31///
32/// // Anonymous download
33/// let dl = FtpDownloader::new(
34///     "ftp://ftp.gnu.org/gnu/emacs/emacs-28.2.tar.gz".to_string(),
35///     "emacs-28.2.tar.gz".to_string(),
36///     false,
37///     ProxyConfig::default(),
38///     Optimizer::new(),
39/// );
40/// dl.download().expect("FTP download failed");
41///
42/// // Authenticated download
43/// let dl = FtpDownloader::new(
44///     "ftp://user:pass@private-server.com/file.zip".to_string(),
45///     "file.zip".to_string(),
46///     false,
47///     ProxyConfig::default(),
48///     Optimizer::new(),
49/// );
50/// dl.download().expect("FTP download failed");
51/// ```
52pub struct FtpDownloader {
53    url: String,
54    output_path: String,
55    quiet_mode: bool,
56    proxy: ProxyConfig,
57    #[allow(dead_code)]
58    optimizer: Optimizer,
59}
60
61impl FtpDownloader {
62    /// Create a new FTP downloader.
63    ///
64    /// # Arguments
65    ///
66    /// * `url` - FTP URL including path to file
67    /// * `output_path` - Local path to save the file
68    /// * `quiet_mode` - Suppress console output
69    /// * `proxy` - Proxy configuration (SOCKS5 only)
70    /// * `optimizer` - Optimizer instance
71    pub fn new(
72        url: String,
73        output_path: String,
74        quiet_mode: bool,
75        proxy: ProxyConfig,
76        optimizer: Optimizer,
77    ) -> Self {
78        Self {
79            url,
80            output_path,
81            quiet_mode,
82            proxy,
83            optimizer,
84        }
85    }
86
87    pub fn download(&self) -> Result<(), Box<dyn Error + Send + Sync>> {
88        let url = Url::parse(&self.url)?;
89        let host = url.host_str().ok_or("Invalid host")?;
90        let port = url.port().unwrap_or(21);
91        let path = url.path();
92
93        print(
94            &format!("Connecting to FTP server {}:{}...", host, port),
95            self.quiet_mode,
96        );
97
98        let mut ftp = if self.proxy.enabled {
99            self.connect_via_proxy(host, port)?
100        } else {
101            FtpStream::connect((host, port))?
102        };
103
104        let username = url.username();
105        let password = url.password().unwrap_or("anonymous");
106
107        print(&format!("Logging in as {}...", username), self.quiet_mode);
108        ftp.login(username, password)?;
109
110        ftp.transfer_type(suppaftp::types::FileType::Binary)?;
111
112        let size = ftp.size(path)? as u64;
113
114        let progress = create_progress_bar(
115            self.quiet_mode,
116            format!("Downloading {}", path),
117            Some(size),
118            false,
119        );
120
121        let mut file = std::fs::File::create(&self.output_path)?;
122
123        // Download file
124        let mut downloaded = 0;
125        ftp.retr(path, |reader| {
126            let mut buffer = vec![0; 8192];
127            loop {
128                match reader.read(&mut buffer) {
129                    Ok(0) => break,
130                    Ok(n) => {
131                        file.write_all(&buffer[..n])
132                            .map_err(|e| suppaftp::FtpError::ConnectionError(e))?;
133                        downloaded += n;
134                        progress.set_position(downloaded as u64);
135                    }
136                    Err(e) => return Err(suppaftp::FtpError::ConnectionError(e)),
137                }
138            }
139            Ok(())
140        })?;
141
142        progress.finish();
143        print("Download completed successfully!", self.quiet_mode);
144
145        Ok(())
146    }
147
148    fn connect_via_proxy(
149        &self,
150        host: &str,
151        port: u16,
152    ) -> Result<FtpStream, Box<dyn Error + Send + Sync>> {
153        match self.proxy.proxy_type {
154            crate::config::ProxyType::Http | crate::config::ProxyType::Https => {
155                Err("HTTP/HTTPS proxy not supported for FTP".into())
156            }
157            crate::config::ProxyType::Socks5 => {
158                if let Some(proxy_url) = &self.proxy.url {
159                    let proxy = Url::parse(proxy_url)?;
160                    let proxy_host = proxy.host_str().ok_or("Invalid proxy host")?;
161                    let proxy_port = proxy.port().unwrap_or(1080);
162
163                    let stream =
164                        socks::Socks5Stream::connect((proxy_host, proxy_port), (host, port))?;
165
166                    Ok(FtpStream::connect_with_stream(stream.into_inner())?)
167                } else {
168                    Err("Proxy URL not configured".into())
169                }
170            }
171        }
172    }
173}