cloud_sync_lib 0.1.0

Cloud storage provider synchronization library
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
//! Google Drive storage backend provider implementation.
//!
//! Handles interaction with the Google Drive API v3. Supports full OAuth2-based
//! upload, download, delete, and list operations, with recursive directory resolution.

use crate::traits::{StorageBackend, StorageError, StorageItem};
use crate::providers::OAuthCredentials;
use crate::providers::utils::translate_http_error;
use async_trait::async_trait;
use std::path::{Path, PathBuf};
use tracing::info;

/// Storage provider client for Google Drive REST API.
pub struct GoogleDriveProvider {
    /// The HTTP client for making API requests.
    client: reqwest::Client,
    /// Credentials configuration (client id/secret, refresh token).
    credentials: OAuthCredentials,
    /// The base API URL.
    api_url: String,
    /// The base upload API URL.
    upload_url: String,
    /// Shared OAuth token manager.
    token_manager: std::sync::Arc<super::utils::OAuthTokenManager>,
    /// Optional upload rate limiter.
    upload_limiter: Option<crate::rate_limit::TokenBucket>,
    /// Optional download rate limiter.
    download_limiter: Option<crate::rate_limit::TokenBucket>,
}

crate::impl_provider_builder!(GoogleDriveProvider, GoogleDriveProviderBuilder, OAuthCredentials);
crate::impl_oauth_token_helper!(GoogleDriveProvider);

impl GoogleDriveProvider {
    /// Creates a new `GoogleDriveProvider` with custom HTTP client options.
    pub fn with_client_options(
        credentials: OAuthCredentials,
        timeout: Option<std::time::Duration>,
        custom_headers: Option<reqwest::header::HeaderMap>,
    ) -> Self {
        let client = super::utils::build_http_client(timeout, custom_headers);
        let auth_url = "https://oauth2.googleapis.com/token".to_string();
        let token_manager = std::sync::Arc::new(super::utils::OAuthTokenManager::new(
            client.clone(),
            &auth_url,
            &credentials.client_id,
            &credentials.client_secret,
            &credentials.refresh_token,
            "Google Drive",
        ));
        Self {
            client,
            credentials,
            api_url: "https://www.googleapis.com/drive/v3/files".to_string(),
            upload_url: "https://www.googleapis.com/upload/drive/v3/files".to_string(),
            token_manager,
            upload_limiter: None,
            download_limiter: None,
        }
    }

    /// Sets the upload and download rate limiters.
    pub fn with_limiters(
        mut self,
        upload_limiter: Option<crate::rate_limit::TokenBucket>,
        download_limiter: Option<crate::rate_limit::TokenBucket>,
    ) -> Self {
        if self.upload_limiter.is_none() {
            self.upload_limiter = upload_limiter;
        }
        if self.download_limiter.is_none() {
            self.download_limiter = download_limiter;
        }
        self
    }

    /// Configures custom endpoints, useful for mocking during tests.
    ///
    /// # Arguments
    /// * `auth_url` - Custom authorization URL.
    /// * `api_url` - Custom API URL.
    /// * `upload_url` - Custom upload API URL.
    ///
    /// # Returns
    /// The modified `GoogleDriveProvider` instance.
    #[cfg(test)]
    pub fn with_endpoints(mut self, auth_url: String, api_url: String, upload_url: String) -> Self {
        self.api_url = api_url;
        self.upload_url = upload_url;
        self.token_manager = std::sync::Arc::new(super::utils::OAuthTokenManager::new(
            self.client.clone(),
            &auth_url,
            &self.credentials.client_id,
            &self.credentials.client_secret,
            &self.credentials.refresh_token,
            "Google Drive",
        ));
        self
    }


    /// Retrieves or creates a Google Drive folder ID for a folder of the given name under `parent_id`.
    ///
    /// # Arguments
    /// * `token` - The active OAuth2 access token.
    /// * `parent_id` - The ID of the parent folder in Google Drive.
    /// * `name` - The name of the folder to resolve/create.
    ///
    /// # Returns
    /// The folder's ID, or a `StorageError`.
    async fn get_or_create_folder_id(&self, token: &str, parent_id: &str, name: &str) -> Result<String, StorageError> {
        let query = format!(
            "name = '{}' and '{}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false",
            name.replace('\'', "\\'"),
            parent_id
        );

        let res = super::utils::apply_bearer_auth(self.client.get(&self.api_url), token)
            .query(&[("q", &query), ("fields", &"files(id)".to_string())])
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        if let Some(files) = res["files"].as_array() {
            if !files.is_empty() {
                return Ok(files[0]["id"].as_str().unwrap().to_string());
            }
        }

        let body = serde_json::json!({
            "name": name,
            "parents": [parent_id],
            "mimeType": "application/vnd.google-apps.folder"
        });

        let create_res = super::utils::apply_bearer_auth(self.client.post(&self.api_url), token)
            .json(&body)
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        let id = create_res["id"].as_str()
            .ok_or_else(|| StorageError::Provider { message: format!("Failed to create folder '{}' in Google Drive: {:?}", name, create_res), status: None })?
            .to_string();

        Ok(id)
    }

    /// Resolves a path (e.g. "a/b/c.txt") to a Google Drive file ID.
    ///
    /// If directories in the path do not exist, they will be automatically created.
    ///
    /// # Arguments
    /// * `token` - The active OAuth2 access token.
    /// * `path` - The relative destination/source file path.
    /// * `is_folder` - True if we are resolving a folder path, false for a file.
    ///
    /// # Returns
    /// The ID of the target file/folder in Google Drive, or a `StorageError`.
    async fn get_or_create_file_id(&self, token: &str, path: &str, is_folder: bool) -> Result<String, StorageError> {
        let normalized = super::utils::normalize_remote_path(path);
        let parts: Vec<&str> = normalized.split('/').filter(|s| !s.is_empty()).collect();
        let mut parent_id = "root".to_string();

        if let Some(ref dest_folder) = self.credentials.common.destination_folder {
            let normalized_dest = super::utils::normalize_remote_path(dest_folder);
            if !normalized_dest.is_empty() {
                // If destination folder has multiple segments, resolve them segment by segment
                for seg in normalized_dest.split('/').filter(|s| !s.is_empty()) {
                    parent_id = self.get_or_create_folder_id(token, &parent_id, seg).await?;
                }
            }
        }

        for (i, part) in parts.iter().enumerate() {
            let is_last = i == parts.len() - 1;
            let current_is_folder = !is_last || is_folder;

            if current_is_folder {
                parent_id = self.get_or_create_folder_id(token, &parent_id, part).await?;
            } else {
                let query = format!(
                    "name = '{}' and '{}' in parents and mimeType != 'application/vnd.google-apps.folder' and trashed = false",
                    part.replace('\'', "\\'"),
                    parent_id
                );

                let res = super::utils::apply_bearer_auth(self.client.get(&self.api_url), token)
                    .query(&[("q", &query), ("fields", &"files(id)".to_string())])
                    .send()
                    .await?
                    .json::<serde_json::Value>()
                    .await?;

                if let Some(files) = res["files"].as_array() {
                    if !files.is_empty() {
                        parent_id = files[0]["id"].as_str().unwrap().to_string();
                        continue;
                    }
                }

                let body = serde_json::json!({
                    "name": part,
                    "parents": [parent_id],
                    "mimeType": "application/octet-stream"
                });

                let create_res = super::utils::apply_bearer_auth(self.client.post(&self.api_url), token)
                    .json(&body)
                    .send()
                    .await?
                    .json::<serde_json::Value>()
                    .await?;

                parent_id = create_res["id"].as_str()
                    .ok_or_else(|| StorageError::Provider { message: format!("Failed to create file '{}' in Google Drive: {:?}", part, create_res), status: None })?
                    .to_string();
            }
        }

        Ok(parent_id)
    }
}

#[async_trait]
impl StorageBackend for GoogleDriveProvider {
    fn name(&self) -> &str {
        "Google Drive"
    }


    async fn upload(&self, local_path: &Path, remote_path: &str) -> Result<(), StorageError> {
        super::utils::execute_with_retry(self.name(), "upload", || async {
            let token = self.get_access_token().await?;
            let file_id = self.get_or_create_file_id(&token, remote_path, false).await?;

            info!("[{}] Real upload starting for '{}' (ID: {})", self.name(), remote_path, file_id);
            let (body, size) = super::utils::get_upload_body(local_path, self.upload_limiter.clone()).await?;
            
            let upload_url = format!("{}/{}?uploadType=media", self.upload_url, file_id);
            let res = super::utils::apply_bearer_auth(self.client.patch(&upload_url), &token)
                .header("Content-Type", "application/octet-stream")
                .header("Content-Length", size.to_string())
                .body(body)
                .send()
                .await?;

            if !res.status().is_success() {
                return Err(translate_http_error(res, self.name(), "upload").await);
            }

            Ok(())
        }).await
    }

    async fn download(&self, remote_path: &str, local_path: &Path) -> Result<(), StorageError> {
        super::utils::execute_with_retry(self.name(), "download", || async {
            let token = self.get_access_token().await?;
            let file_id = self.get_or_create_file_id(&token, remote_path, false).await?;

            let download_url = format!("{}/{}?alt=media", self.api_url, file_id);
            let res = super::utils::apply_bearer_auth(self.client.get(&download_url), &token)
                .send()
                .await?;

            if !res.status().is_success() {
                return Err(translate_http_error(res, self.name(), "download").await);
            }

            super::utils::download_rate_limited(res, local_path, self.download_limiter.clone()).await?;
            Ok(())
        }).await
    }

    async fn delete(&self, remote_path: &str) -> Result<(), StorageError> {
        super::utils::execute_with_retry(self.name(), "delete", || async {
            let token = self.get_access_token().await?;
            let file_id = self.get_or_create_file_id(&token, remote_path, false).await?;

            let delete_url = format!("{}/{}", self.api_url, file_id);
            let res = super::utils::apply_bearer_auth(self.client.delete(&delete_url), &token)
                .send()
                .await?;

            if !res.status().is_success() {
                return Err(translate_http_error(res, self.name(), "delete").await);
            }

            Ok(())
        }).await
    }

    /// Creates a directory folder recursively on Google Drive.
    ///
    /// # Arguments
    /// * `remote_path` - The folder path relative to the sync root.
    async fn create_folder(&self, remote_path: &str) -> Result<(), StorageError> {
        super::utils::execute_with_retry(self.name(), "create_folder", || async {
            let token = self.get_access_token().await?;
            let _ = self.get_or_create_file_id(&token, remote_path, true).await?;
            Ok(())
        }).await
    }

    async fn list(&self, remote_path: &str) -> Result<Vec<StorageItem>, StorageError> {
        super::utils::execute_with_retry(self.name(), "list", || async {
            let token = self.get_access_token().await?;
            let folder_id = self.get_or_create_file_id(&token, remote_path, true).await?;

            let query = format!("'{}' in parents and trashed = false", folder_id);
            let mut items = Vec::new();
            let mut next_page_token: Option<String> = None;

            loop {
                let req = super::utils::apply_bearer_auth(self.client.get(&self.api_url), &token);
                
                let fields = "nextPageToken, files(id, name, size, mimeType, modifiedTime, md5Checksum)".to_string();
                let mut query_params = vec![
                    ("q", query.clone()),
                    ("fields", fields),
                ];
                let page_token_str;
                if let Some(ref page_token) = next_page_token {
                    page_token_str = page_token.clone();
                    query_params.push(("pageToken", page_token_str));
                }

                let res = req.query(&query_params)
                    .send()
                    .await?
                    .json::<serde_json::Value>()
                    .await?;

                if let Some(files) = res["files"].as_array() {
                    for file in files {
                        let name = file["name"].as_str().unwrap_or("").to_string();
                        let size = file["size"].as_str().unwrap_or("0").parse::<u64>().unwrap_or(0);
                        let mime_type = file["mimeType"].as_str().unwrap_or("");
                        let is_dir = mime_type == "application/vnd.google-apps.folder";
                        
                        if mime_type.starts_with("application/vnd.google-apps.") && !is_dir {
                            continue;
                        }

                        let checksum = file["md5Checksum"].as_str().map(|s| s.to_string());

                        let modified = file["modifiedTime"].as_str()
                            .and_then(|t| time::OffsetDateTime::parse(t, &time::format_description::well_known::Rfc3339).ok())
                            .map(std::time::SystemTime::from)
                            .unwrap_or_else(std::time::SystemTime::now);

                        let rel_path = if remote_path.is_empty() {
                            name
                        } else {
                            format!("{}/{}", remote_path, name)
                        };

                        items.push(StorageItem {
                            path: PathBuf::from(rel_path),
                            size,
                            modified,
                            is_dir,
                            checksum,
                            permissions: None,
                });
                    }
                }

                next_page_token = res["nextPageToken"].as_str().map(|s| s.to_string());
                if next_page_token.is_none() {
                    break;
                }
            }

            Ok(items)
        }).await
    }

    async fn compute_local_checksum(&self, local_path: &Path) -> Result<Option<String>, StorageError> {
        Ok(crate::checksum::compute_md5(local_path).await.ok())
    }
}



/// Builder for [`GoogleDriveProvider`].
pub struct GoogleDriveProviderBuilder {
    pub credentials: OAuthCredentials,
    pub timeout: Option<std::time::Duration>,
    pub custom_headers: Option<reqwest::header::HeaderMap>,
}

impl GoogleDriveProviderBuilder {
    /// Creates a new builder with the required credentials.
    pub fn new(credentials: OAuthCredentials) -> Self {
        Self {
            credentials,
            timeout: None,
            custom_headers: None,
        }
    }

    /// Builds the provider.
    pub fn build(self) -> GoogleDriveProvider {
        GoogleDriveProvider::with_client_options(self.credentials, self.timeout, self.custom_headers)
    }
}