rustdrivesync 1.1.1

Production-ready CLI tool for one-way file synchronization with Google Drive. Features: dependency injection, rate limiting, retry with backoff, parallel uploads, and comprehensive documentation.
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
use crate::error::{Result, RustDriveSyncError};
use crate::google_drive::client::DriveClient;
use crate::google_drive::models::{LocalFileMetadata, UploadOptions, UploadResult};
use google_drive3::api::File as DriveFile;
use std::fs;
use std::io::Cursor;
use std::path::Path;
use std::time::Instant;
use tokio::fs::File as AsyncFile;
use tokio::io::AsyncReadExt;
use tokio_util::io::ReaderStream;
use tracing::{debug, info, warn};

/// Gerenciador de uploads para Google Drive
pub struct DriveUploader<'a> {
    client: &'a DriveClient,
}

impl<'a> DriveUploader<'a> {
    /// Cria um novo uploader
    pub fn new(client: &'a DriveClient) -> Self {
        Self { client }
    }

    /// Faz upload de um arquivo para o Google Drive
    ///
    /// # Arguments
    /// * `file_path` - Caminho do arquivo local
    /// * `options` - Opções de upload
    pub async fn upload_file<P: AsRef<Path>>(
        &self,
        file_path: P,
        options: UploadOptions,
    ) -> Result<UploadResult> {
        let file_path = file_path.as_ref();

        // Preparar metadados do arquivo
        let metadata = self.prepare_file_metadata(file_path)?;

        info!(
            "Iniciando upload: {} ({} bytes)",
            metadata.name, metadata.size
        );

        // Decidir entre upload simples ou resumível
        let start_time = Instant::now();

        let result = if options.use_resumable && metadata.size > (5 * 1024 * 1024) {
            debug!("Usando upload resumível (arquivo grande)");
            self.upload_resumable(&metadata, options).await?
        } else {
            debug!("Usando upload simples");
            self.upload_simple(&metadata, options).await?
        };

        let duration = start_time.elapsed().as_secs_f64();

        info!(
            "Upload concluído: {} em {:.2}s ({:.2} MB/s)",
            result.name,
            duration,
            (result.size as f64 / 1_048_576.0) / duration
        );

        Ok(UploadResult {
            upload_duration_secs: duration,
            ..result
        })
    }

    /// Upload simples para arquivos pequenos
    async fn upload_simple(
        &self,
        metadata: &LocalFileMetadata,
        options: UploadOptions,
    ) -> Result<UploadResult> {
        // Ler arquivo completo em memória
        let file_content = fs::read(&metadata.path).map_err(|e| {
            RustDriveSyncError::FileReadError {
                path: metadata.path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        // Criar objeto File para o Drive
        let mut drive_file = DriveFile::default();
        drive_file.name = Some(metadata.name.clone());
        drive_file.mime_type = Some(metadata.mime_type.clone());

        if let Some(parent_id) = options.parent_folder_id.as_ref() {
            drive_file.parents = Some(vec![parent_id.clone()]);
        }

        // Criar um Cursor que implementa Read + Seek
        let cursor = Cursor::new(file_content);

        // Executar upload
        let result = self
            .client
            .hub()
            .files()
            .create(drive_file)
            .upload(
                cursor,
                metadata.mime_type.parse().map_err(|_| {
                    RustDriveSyncError::DriveApiError {
                        message: format!("MIME type inválido: {}", metadata.mime_type),
                    }
                })?,
            )
            .await
            .map_err(|e| RustDriveSyncError::UploadFailed {
                attempts: 1,
                message: format!("Erro no upload simples de {}: {}", metadata.name, e),
            })?;

        let uploaded_file = result.1;

        // Verificar checksum se solicitado
        if options.verify_checksum {
            self.verify_checksum(&uploaded_file, metadata)?;
        }

        Ok(UploadResult {
            file_id: uploaded_file.id.unwrap_or_default(),
            name: uploaded_file.name.unwrap_or_else(|| metadata.name.clone()),
            size: metadata.size,
            md5_checksum: uploaded_file.md5_checksum.clone(),
            web_view_link: uploaded_file.web_view_link.clone(),
            upload_duration_secs: 0.0, // Será preenchido pelo caller
        })
    }

    /// Upload resumível com chunks para arquivos grandes
    /// Agora usa streaming para memória constante
    async fn upload_resumable(
        &self,
        metadata: &LocalFileMetadata,
        options: UploadOptions,
    ) -> Result<UploadResult> {
        // Para arquivos grandes, usar upload com streaming
        // Isso mantém uso de memória constante (~5MB) independente do tamanho do arquivo
        self.upload_streaming(metadata, options).await
    }

    /// Prepara os metadados de um arquivo local
    fn prepare_file_metadata(&self, file_path: &Path) -> Result<LocalFileMetadata> {
        if !file_path.exists() {
            return Err(RustDriveSyncError::FileNotFound {
                path: file_path.display().to_string(),
            });
        }

        let metadata_fs = fs::metadata(file_path).map_err(|e| {
            RustDriveSyncError::FileReadError {
                path: file_path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        let name = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| RustDriveSyncError::DriveApiError {
                message: format!("Nome de arquivo inválido: {:?}", file_path),
            })?
            .to_string();

        let mime_type = self.detect_mime_type(file_path);

        // Para arquivos pequenos (< 5MB), calcular MD5 agora
        // Para arquivos grandes, MD5 será calculado durante streaming
        let md5_hash = if metadata_fs.len() < 5 * 1024 * 1024 {
            Some(self.calculate_md5(file_path)?)
        } else {
            None // Será calculado em upload_streaming
        };

        Ok(LocalFileMetadata {
            path: file_path.to_path_buf(),
            name,
            size: metadata_fs.len(),
            mime_type,
            md5_hash,
        })
    }

    /// Detecta o tipo MIME de um arquivo usando mime_guess
    fn detect_mime_type(&self, file_path: &Path) -> String {
        mime_guess::from_path(file_path)
            .first_or_octet_stream()
            .to_string()
    }

    /// Calcula o hash MD5 de um arquivo (síncrono, para arquivos pequenos)
    fn calculate_md5(&self, file_path: &Path) -> Result<String> {
        use md5::{Digest, Md5};

        let content = fs::read(file_path).map_err(|e| RustDriveSyncError::FileReadError {
            path: file_path.display().to_string(),
            message: e.to_string(),
        })?;

        let mut hasher = Md5::new();
        hasher.update(&content);
        let result = hasher.finalize();

        Ok(format!("{:x}", result))
    }

    /// Calcula o hash MD5 de um arquivo usando streaming (async, para arquivos grandes)
    async fn calculate_md5_streaming(&self, file_path: &Path) -> Result<String> {
        use md5::{Digest, Md5};

        let mut file = AsyncFile::open(file_path).await.map_err(|e| {
            RustDriveSyncError::FileReadError {
                path: file_path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        let mut hasher = Md5::new();
        let mut buffer = vec![0u8; 256 * 1024]; // 256KB chunks

        loop {
            let n = file.read(&mut buffer).await.map_err(|e| {
                RustDriveSyncError::FileReadError {
                    path: file_path.display().to_string(),
                    message: e.to_string(),
                }
            })?;

            if n == 0 {
                break;
            }

            hasher.update(&buffer[..n]);
        }

        let result = hasher.finalize();
        Ok(format!("{:x}", result))
    }

    /// Upload com streaming para arquivos grandes usando reqwest diretamente
    async fn upload_streaming(
        &self,
        metadata: &LocalFileMetadata,
        options: UploadOptions,
    ) -> Result<UploadResult> {

        info!("Usando upload streaming para: {}", metadata.name);

        // 1. Calcular MD5 antes do upload (necessário para verificação)
        debug!("Calculando MD5 do arquivo...");
        let md5_hash = self.calculate_md5_streaming(&metadata.path).await?;
        debug!("MD5 calculado: {}", md5_hash);

        // 2. Obter token de acesso
        let token = self.client.get_token().await?;

        // 3. Criar metadados do arquivo para o Google Drive
        let mut file_metadata = serde_json::json!({
            "name": metadata.name,
            "mimeType": metadata.mime_type,
        });

        if let Some(parent_id) = options.parent_folder_id.as_ref() {
            file_metadata["parents"] = serde_json::json!([parent_id]);
        }

        // 4. Iniciar sessão de upload resumível
        debug!("Iniciando sessão de upload resumível...");
        let http_client = reqwest::Client::new();

        let init_response = http_client
            .post("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable")
            .bearer_auth(&token)
            .header("Content-Type", "application/json; charset=UTF-8")
            .json(&file_metadata)
            .send()
            .await
            .map_err(|e| RustDriveSyncError::UploadFailed {
                attempts: 1,
                message: format!("Erro ao iniciar upload resumível: {}", e),
            })?;

        // 5. Obter URL da sessão de upload
        let upload_url = init_response
            .headers()
            .get("Location")
            .ok_or_else(|| RustDriveSyncError::DriveApiError {
                message: "URL de upload não retornada pelo Google Drive".to_string(),
            })?
            .to_str()
            .map_err(|e| RustDriveSyncError::DriveApiError {
                message: format!("URL de upload inválida: {}", e),
            })?
            .to_string();

        debug!("URL de upload obtida: {}", upload_url);

        // 6. Abrir arquivo e criar stream
        let file = AsyncFile::open(&metadata.path).await.map_err(|e| {
            RustDriveSyncError::FileReadError {
                path: metadata.path.display().to_string(),
                message: e.to_string(),
            }
        })?;

        // Criar stream de 256KB chunks
        const CHUNK_SIZE: usize = 256 * 1024;
        let stream = ReaderStream::with_capacity(file, CHUNK_SIZE);

        // Converter stream para Body
        let body = reqwest::Body::wrap_stream(stream);

        // 7. Enviar arquivo
        debug!("Enviando arquivo ({} bytes)...", metadata.size);
        let upload_response = http_client
            .put(&upload_url)
            .header("Content-Length", metadata.size)
            .header("Content-Type", &metadata.mime_type)
            .body(body)
            .send()
            .await
            .map_err(|e| RustDriveSyncError::UploadFailed {
                attempts: 1,
                message: format!("Erro ao enviar arquivo: {}", e),
            })?;

        // 8. Processar resposta
        if !upload_response.status().is_success() {
            let error_text = upload_response.text().await.unwrap_or_default();
            return Err(RustDriveSyncError::UploadFailed {
                attempts: 1,
                message: format!("Upload falhou: {}", error_text),
            });
        }

        let uploaded_file: DriveFile = upload_response.json().await.map_err(|e| {
            RustDriveSyncError::DriveApiError {
                message: format!("Erro ao parsear resposta do upload: {}", e),
            }
        })?;

        debug!("Upload streaming concluído com sucesso!");

        Ok(UploadResult {
            file_id: uploaded_file.id.unwrap_or_default(),
            name: uploaded_file.name.unwrap_or_else(|| metadata.name.clone()),
            size: metadata.size,
            md5_checksum: Some(md5_hash),
            web_view_link: uploaded_file.web_view_link.clone(),
            upload_duration_secs: 0.0, // Será preenchido pelo caller
        })
    }

    /// Verifica se o checksum MD5 corresponde
    fn verify_checksum(&self, uploaded_file: &DriveFile, metadata: &LocalFileMetadata) -> Result<()> {
        if let (Some(remote_md5), Some(local_md5)) =
            (&uploaded_file.md5_checksum, &metadata.md5_hash)
        {
            if remote_md5 != local_md5 {
                warn!(
                    "Checksum MD5 não corresponde! Local: {}, Remoto: {}",
                    local_md5, remote_md5
                );
                return Err(RustDriveSyncError::ChecksumMismatch {
                    file: metadata.name.clone(),
                    expected: local_md5.clone(),
                    actual: remote_md5.clone(),
                });
            }
            debug!("Checksum MD5 verificado com sucesso");
        } else {
            debug!("Checksum MD5 não disponível para verificação");
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::google_drive::models::UploadProgress;

    #[test]
    fn test_mime_type_detection() {
        // Teste de detecção de MIME type usando mime_guess
        let test_cases = vec![
            ("test.txt", "text/plain"),
            ("image.jpg", "image/jpeg"),
            ("image.jpeg", "image/jpeg"),
            ("picture.png", "image/png"),
            ("unknown.unknown123", "application/octet-stream"), // Extensão realmente desconhecida
            ("document.pdf", "application/pdf"),
            ("data.json", "application/json"),
            ("video.mp4", "video/mp4"),
            ("audio.mp3", "audio/mpeg"),
            ("archive.zip", "application/zip"),
            ("page.html", "text/html"),
            ("style.css", "text/css"),
            ("script.js", "text/javascript"), // mime_guess usa text/javascript
            ("image.webp", "image/webp"), // Extensão moderna suportada
            ("data.xyz", "chemical/x-xyz"), // mime_guess conhece formato XYZ molecular
        ];

        for (filename, expected_mime) in test_cases {
            let detected = mime_guess::from_path(filename)
                .first_or_octet_stream()
                .to_string();

            assert_eq!(detected, expected_mime, "MIME type incorreto para {}", filename);
        }
    }

    #[test]
    fn test_upload_progress() {
        let progress = UploadProgress::new(500, 1000);
        assert_eq!(progress.percentage, 50.0);
        assert!(!progress.is_complete());

        let complete = UploadProgress::new(1000, 1000);
        assert_eq!(complete.percentage, 100.0);
        assert!(complete.is_complete());
    }
}