gdown-core 0.1.0

Core download logic for Google Drive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Core download logic for Google Drive files

use crate::error::{GdownError, Result};
use crate::url::{parse_url, build_download_url, FileId};
use futures_util::stream::StreamExt;
use reqwest::Client;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Default user agent string
const DEFAULT_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";

/// Options for download operations
pub struct DownloadOptions {
    /// Speed limit in bytes per second (None = unlimited)
    pub speed_limit: Option<u64>,
    /// Enable resume mode
    pub resume: bool,
    /// Export format for Google Docs/Sheets/Slides
    pub format: Option<String>,
    /// Progress callback (bytes_downloaded, total_bytes)
    #[allow(clippy::type_complexity)]
    pub progress_callback: Option<Box<dyn Fn(u64, Option<u64>) + Send + 'static>>,
}

impl Clone for DownloadOptions {
    fn clone(&self) -> Self {
        Self {
            speed_limit: self.speed_limit,
            resume: self.resume,
            format: self.format.clone(),
            progress_callback: None,  // Cannot clone fn pointers
        }
    }
}

impl std::fmt::Debug for DownloadOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DownloadOptions")
            .field("speed_limit", &self.speed_limit)
            .field("resume", &self.resume)
            .field("format", &self.format)
            .field("progress_callback", &"...")
            .finish()
    }
}

/// Downloader client for Google Drive
#[derive(Clone)]
pub struct Downloader {
    proxy: Option<String>,
    user_agent: String,
    verify_ssl: bool,
    cookies_path: PathBuf,
}

impl Downloader {
    /// Create a new Downloader with default settings
    pub fn new() -> Self {
        Self {
            proxy: None,
            user_agent: DEFAULT_USER_AGENT.to_string(),
            verify_ssl: true,
            cookies_path: PathBuf::from("~/.cache/gdown/cookies.txt"),
        }
    }

    /// Set proxy URL
    pub fn proxy(mut self, proxy: &str) -> Self {
        self.proxy = Some(proxy.to_string());
        self
    }

    /// Set user agent
    pub fn user_agent(mut self, ua: &str) -> Self {
        self.user_agent = ua.to_string();
        self
    }

    /// Set SSL verification
    pub fn verify_ssl(mut self, verify: bool) -> Self {
        self.verify_ssl = verify;
        self
    }

    /// Set cookies path
    pub fn cookies_path(mut self, path: &Path) -> Self {
        self.cookies_path = path.to_path_buf();
        self
    }

    /// Build the client with current settings
    pub fn build_client(&self) -> Client {
        let mut builder = Client::builder()
            .user_agent(&self.user_agent)
            .timeout(Duration::from_secs(60));

        if !self.verify_ssl {
            builder = builder.danger_accept_invalid_certs(true);
        }

        if let Some(proxy) = &self.proxy {
            if proxy.starts_with("socks5://") {
                builder = builder.proxy(reqwest::Proxy::all(proxy).unwrap());
            } else {
                builder = builder.proxy(reqwest::Proxy::http(proxy).unwrap());
            }
        }

        builder.build().unwrap_or_else(|_| {
            Client::builder()
                .user_agent(&self.user_agent)
                .build()
                .expect("Failed to create HTTP client")
        })
    }

    /// Download a file from URL
    pub async fn download(
        &self,
        url: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        let client = self.build_client();

        // Parse URL to get file ID
        let (file_id, is_download_link) = parse_url(url)?;
        let file_id = file_id.ok_or_else(|| GdownError::InvalidUrl("No file ID found".into()))?;

        // Build initial request URL
        let request_url = if is_download_link {
            build_download_url(&file_id)
        } else {
            // Check if it's a Google Doc type and needs export
            if let Some(format) = options.format.clone() {
                if url.contains("document") {
                    return self.download_doc_export(&file_id, &format, output, options).await;
                } else if url.contains("spreadsheet") {
                    return self.download_sheet_export(&file_id, &format, output, options).await;
                } else if url.contains("presentation") {
                    return self.download_slides_export(&file_id, &format, output, options).await;
                }
            }
            build_download_url(&file_id)
        };

        // Make initial request
        let response = client.get(&request_url).send().await.map_err(|e| GdownError::Download(e.to_string()))?;

        // Check content type
        let content_type = response
            .headers()
            .get("Content-Type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");

        if content_type.contains("text/html") {
            // Need to handle confirmation page
            let html = response.text().await.map_err(|e| GdownError::Download(e.to_string()))?;
            let actual_url = self.extract_confirmation_url(&html).await?;

            // Resume if requested and partial file exists
            if options.resume && output.exists() {
                return self.resume_download(&actual_url, output, options).await;
            }

            return self.download_file(&actual_url, output, options).await;
        }

        // Resume if requested and partial file exists
        if options.resume && output.exists() {
            return self.resume_download(&request_url, output, options).await;
        }

        // Download directly
        self.download_file(&request_url, output, options).await
    }

    /// Download Google Document (Docs) with export format
    async fn download_doc_export(
        &self,
        file_id: &FileId,
        format: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        let url = format!(
            "https://docs.google.com/document/d/{}/export?format={}",
            file_id, format
        );
        self.download_file(&url, output, options).await
    }

    /// Download Google Spreadsheet with export format
    async fn download_sheet_export(
        &self,
        file_id: &FileId,
        format: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        let url = format!(
            "https://docs.google.com/spreadsheets/d/{}/export?format={}",
            file_id, format
        );
        self.download_file(&url, output, options).await
    }

    /// Download Google Slides with export format
    async fn download_slides_export(
        &self,
        file_id: &FileId,
        format: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        let url = format!(
            "https://docs.google.com/presentation/d/{}/export?format={}",
            file_id, format
        );
        self.download_file(&url, output, options).await
    }

    /// Extract actual download URL from confirmation page HTML
    async fn extract_confirmation_url(&self, html: &str) -> Result<String> {
        use regex::Regex;

        // Try to find form action URL
        let form_regex = Regex::new(r#"action="([^"]+)""#).unwrap();
        if let Some(caps) = form_regex.captures(html) {
            let action = caps.get(1).unwrap().as_str();

            // Build POST request to confirmation URL
            if action.contains("confirm") {
                let client = self.build_client();

                // Try to find confirmation token
                let token_regex = Regex::new(r#"name="confirm".*?value="([^"]+)""#).unwrap();
                let token = token_regex.captures(html).and_then(|c| c.get(1)).map(|m| m.as_str());

                let mut request = client.post(action);
                if let Some(t) = token {
                    request = request.form(&[("confirm", t)]);
                }

                let response = request.send().await.map_err(|e| GdownError::Download(e.to_string()))?;

                if let Some(location) = response.headers().get("Location") {
                    return Ok(location.to_str().unwrap_or(action).to_string());
                }
            }

            return Ok(action.to_string());
        }

        // Fallback: try to find downloadUrl in JavaScript
        let download_url_regex = Regex::new(r#"downloadUrl\s*:\s*"([^"]+)""#).unwrap();
        if let Some(caps) = download_url_regex.captures(html) {
            return Ok(caps.get(1).unwrap().as_str().to_string());
        }

        Err(GdownError::FileUrlRetrieval("Could not find download URL in confirmation page".into()))
    }

    /// Download file content to output path
    async fn download_file(
        &self,
        url: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        use tokio::io::AsyncWriteExt;

        let client = self.build_client();
        let response = client.get(url).send().await.map_err(|e| GdownError::Download(e.to_string()))?;

        let total_size = response.content_length();
        let mut file = tokio::fs::File::create(output).await?;
        let mut downloaded: u64 = 0;

        let mut stream = response.bytes_stream();
        while let Some(chunk_result) = stream.next().await {
            let chunk = chunk_result.map_err(|e| GdownError::Download(e.to_string()))?;
            file.write_all(&chunk).await?;
            downloaded += chunk.len() as u64;

            // Call progress callback
            if let Some(ref cb) = options.progress_callback {
                cb(downloaded, total_size);
            }

            // Speed limiting
            if let Some(limit) = options.speed_limit {
                let expected_time = (downloaded as f64 / limit as f64 * 1000.0) as u64;
                tokio::time::sleep(std::time::Duration::from_millis(expected_time)).await;
            }
        }

        Ok(downloaded)
    }

    /// Resume a partially downloaded file
    async fn resume_download(
        &self,
        url: &str,
        output: &Path,
        options: DownloadOptions,
    ) -> Result<u64> {
        use tokio::io::AsyncWriteExt;

        let existing_size = tokio::fs::metadata(output).await?.len();
        let client = self.build_client();

        let response = client
            .get(url)
            .header("Range", format!("bytes={}-", existing_size))
            .send()
            .await.map_err(|e| GdownError::Download(e.to_string()))?;

        let mut file = tokio::fs::OpenOptions::new()
            .append(true)
            .open(output)
            .await?;

        let mut downloaded = existing_size;
        let mut stream = response.bytes_stream();

        while let Some(chunk_result) = stream.next().await {
            let chunk = chunk_result.map_err(|e| GdownError::Download(e.to_string()))?;
            file.write_all(&chunk).await?;
            downloaded += chunk.len() as u64;

            if let Some(ref cb) = options.progress_callback {
                cb(downloaded, None);
            }
        }

        Ok(downloaded)
    }

    /// Get filename from Content-Disposition header
    pub fn get_filename_from_disposition(disposition: &str) -> Option<String> {
        // Try filename* first (UTF-8 encoded)
        if let Some(start) = disposition.find("filename*=UTF-8''") {
            let remainder = &disposition[start + 17..];
            if let Some(end) = remainder.find(';') {
                return Some(remainder[..end].to_string());
            }
            return Some(remainder.to_string());
        }

        // Try simple filename
        if let Some(start) = disposition.find("filename=\"") {
            let remainder = &disposition[start + 10..];
            if let Some(end) = remainder.find('"') {
                return Some(remainder[..end].to_string());
            }
        }

        None
    }
}

impl Default for Downloader {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_downloader_creation() {
        let dl = Downloader::new();
        assert!(dl.verify_ssl);
    }

    #[test]
    fn test_filename_from_disposition() {
        let disp = r#"attachment; filename="test.txt"; filename*=UTF-8''test%20file.txt"#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, Some("test%20file.txt".to_string()));
    }

    #[test]
    fn test_filename_simple() {
        let disp = r#"attachment; filename="test.txt""#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, Some("test.txt".to_string()));
    }

    #[test]
    fn test_filename_from_disposition_empty() {
        let disp = r#"attachment"#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, None);
    }

    #[test]
    fn test_filename_from_disposition_only_filename_star() {
        // Only filename* (UTF-8), no regular filename
        let disp = r#"attachment; filename*=UTF-8''test%20file.txt"#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, Some("test%20file.txt".to_string()));
    }

    #[test]
    fn test_filename_from_disposition_with_spaces() {
        let disp = r#"attachment; filename="test file with spaces.txt""#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, Some("test file with spaces.txt".to_string()));
    }

    #[test]
    fn test_filename_from_disposition_no_quotes() {
        let disp = r#"attachment; filename=test.txt"#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, None); // Must have quotes
    }

    #[test]
    fn test_filename_from_disposition_rfc5987_chars() {
        // filename* with special UTF-8 characters
        let disp = r#"attachment; filename*=UTF-8''%E6%96%87%E4%BB%B6.txt"#;
        let filename = Downloader::get_filename_from_disposition(disp);
        assert_eq!(filename, Some("%E6%96%87%E4%BB%B6.txt".to_string()));
    }
}