grr-cli 0.4.0

Google tools from the terminal, at maximum performance: zero-config Gmail, Calendar, Drive, Contacts, Chat and Forms over HTTP/3
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! High-performance Google Drive client: typed endpoints over [`HttpCore`].
//!
//! Transport, retry, rate-valving, and OAuth live in core; this module
//! adds Drive's URL space, models, pagination, streaming media transfer, and
//! streaming multipart upload.

use std::path::Path;

use bytes::Bytes;
use futures::{StreamExt, future, stream};
use rand::random;
use reqwest::Response;
use reqwest::header::{CONTENT_LENGTH, CONTENT_TYPE};
use tokio::io::{AsyncWriteExt, BufWriter};
use tokio_util::io::ReaderStream;
use tracing::info;
use url::Url;

use crate::core::auth::{DeviceAuthChallenge, GoogleAuth, TokenStorage};
use crate::core::error::{GrrError, Result};
use crate::core::http::{HttpCore, QueryParams, TransportInfo, join_url, parse_url};
use crate::core::runtime::detect_runtime_features;
use crate::core::{Page, paginate};

use crate::drive::models::*;

const DEFAULT_BASE_URL: &str = "https://www.googleapis.com/drive/v3/";
const DEFAULT_UPLOAD_BASE_URL: &str = "https://www.googleapis.com/upload/drive/v3/";
const FOLDER_MIME_TYPE: &str = "application/vnd.google-apps.folder";
const PROBE_PATH: &str = "files";
const MAX_PAGE_SIZE: usize = 1000;
const MAX_SUBRESOURCE_PAGE_SIZE: usize = 100;
const PERMISSION_FIELDS: &str = "id,type,role,emailAddress,domain,displayName,deleted,pendingOwner";
const COMMENT_FIELDS: &str =
    "id,author(displayName,photoLink),content,createdTime,modifiedTime,resolved,replies";
const COMMENT_LIST_FIELDS: &str = "nextPageToken,comments(id,author(displayName,photoLink),content,createdTime,modifiedTime,resolved,replies)";
const REVISION_FIELDS: &str =
    "id,modifiedTime,lastModifyingUser(displayName,photoLink),size,mimeType,keepForever";
const REVISION_LIST_FIELDS: &str = "nextPageToken,revisions(id,modifiedTime,lastModifyingUser(displayName,photoLink),size,mimeType,keepForever)";

/// Google Drive API client builder.
pub struct DriveClientBuilder {
    auth: Option<GoogleAuth>,
    base_url: Option<Url>,
    upload_base_url: Option<Url>,
}

impl DriveClientBuilder {
    pub fn new() -> Self {
        Self {
            auth: None,
            base_url: None,
            upload_base_url: None,
        }
    }

    pub fn auth(mut self, auth: GoogleAuth) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Override the Drive API base URL (primarily for test injection).
    pub fn base_url(mut self, url: Url) -> Self {
        self.base_url = Some(url);
        self
    }

    /// Override the Drive media-upload base URL (primarily for test
    /// injection).
    pub fn upload_base_url(mut self, url: Url) -> Self {
        self.upload_base_url = Some(url);
        self
    }

    pub async fn build(self) -> Result<DriveClient> {
        let auth = self
            .auth
            .ok_or_else(|| GrrError::Config("Auth is required".into()))?;
        let has_base_override = self.base_url.is_some();
        let base_url = match self.base_url {
            Some(url) => url,
            None => parse_url(DEFAULT_BASE_URL, "base")?,
        };
        let upload_base_url = match self.upload_base_url {
            Some(url) => url,
            None => parse_url(DEFAULT_UPLOAD_BASE_URL, "upload base")?,
        };

        let core = if has_base_override {
            HttpCore::unprobed(auth, crate::core::http::build_http_client()?)
        } else {
            HttpCore::connect(auth, &base_url, PROBE_PATH).await?
        };
        DriveClient::new(core, base_url, upload_base_url).await
    }
}

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

/// High-performance Google Drive client.
#[derive(Clone)]
pub struct DriveClient {
    core: HttpCore,
    base_url: Url,
    upload_base_url: Url,
}

fn generate_boundary() -> String {
    format!("grr-drive-{:032x}", random::<u128>())
}

fn page_size(max_results: usize, maximum: usize) -> usize {
    if max_results == 0 {
        maximum
    } else {
        max_results.min(maximum)
    }
}

impl DriveClient {
    /// Create new client from a connected core (test injection point).
    pub async fn new(core: HttpCore, base_url: Url, upload_base_url: Url) -> Result<Self> {
        let features = detect_runtime_features().await;
        info!(
            "DriveClient initialized: http3=always, io_uring={}",
            features.io_uring
        );
        Ok(Self {
            core,
            base_url,
            upload_base_url,
        })
    }

    /// The shared HTTP engine (advanced use; typed methods preferred).
    pub fn core(&self) -> &HttpCore {
        &self.core
    }

    /// Transport negotiation details observed during client construction.
    pub fn transport_info(&self) -> &TransportInfo {
        self.core.transport_info()
    }

    /// Which token backend is live ("os-keyring" or "file").
    pub fn token_backend(&self) -> &'static str {
        self.core.auth().token_backend()
    }

    /// Fresh interactive login (PKCE browser flow), dropping any stored
    /// token first so a dead credential can never block consent.
    pub async fn login(&self) -> Result<TokenStorage> {
        self.core.auth().login().await
    }

    /// Start an OAuth device flow; display the challenge to the user.
    pub async fn request_device_code(&self) -> Result<DeviceAuthChallenge> {
        self.core.auth().request_device_code().await
    }

    /// Poll a device-flow challenge. `Ok(None)` means keep waiting.
    pub async fn poll_device_code(
        &self,
        challenge: &mut DeviceAuthChallenge,
    ) -> Result<Option<TokenStorage>> {
        self.core.auth().poll_device_code(challenge).await
    }

    /// Get access token
    pub async fn access_token(&self) -> Result<String> {
        self.core.auth().get_access_token().await
    }

    fn api_url(&self, path: &str) -> Result<Url> {
        join_url(&self.base_url, path, "API")
    }

    fn upload_url(&self, path: &str) -> Result<Url> {
        join_url(&self.upload_base_url, path, "upload")
    }

    fn file_url(&self, file_id: &str) -> Result<Url> {
        self.api_url(&format!("files/{}", urlencoding::encode(file_id)))
    }

    fn file_collection_url(&self, file_id: &str, collection: &str) -> Result<Url> {
        self.api_url(&format!(
            "files/{}/{collection}",
            urlencoding::encode(file_id)
        ))
    }

    fn file_item_url(&self, file_id: &str, collection: &str, item_id: &str) -> Result<Url> {
        self.api_url(&format!(
            "files/{}/{collection}/{}",
            urlencoding::encode(file_id),
            urlencoding::encode(item_id)
        ))
    }

    fn media_url(&self, file_id: &str) -> Result<Url> {
        let mut url = self.file_url(file_id)?;
        url.query_pairs_mut().append_pair("alt", "media");
        Ok(url)
    }

    fn export_url(&self, file_id: &str, mime_type: &str) -> Result<Url> {
        let mut url = self.file_collection_url(file_id, "export")?;
        url.query_pairs_mut().append_pair("mimeType", mime_type);
        Ok(url)
    }

    async fn write_response_to_path(response: Response, dest: &Path) -> Result<u64> {
        let mut file = BufWriter::new(tokio::fs::File::create(dest).await?);
        let mut written = 0_u64;
        let mut chunks = response.bytes_stream();
        while let Some(chunk) = chunks.next().await {
            let chunk = chunk?;
            file.write_all(&chunk).await?;
            written += chunk.len() as u64;
        }
        file.flush().await?;
        Ok(written)
    }

    pub async fn list_files(&self, opts: FileListOptions) -> Result<Vec<File>> {
        let max = if opts.max_results == 0 {
            None
        } else {
            Some(opts.max_results)
        };
        let q = opts.q.as_deref();
        let batch_size = page_size(opts.max_results, MAX_PAGE_SIZE);

        paginate(max, move |page_token| async move {
            let params = QueryParams::new()
                .add("pageSize", batch_size.to_string())
                .add_optional("q", q)
                .add_page_token(page_token.as_deref());
            let page: FileList = self
                .core
                .execute_json(params.apply(self.core.get(self.api_url("files")?)))
                .await?;
            Ok(Page::new(page.files, page.next_page_token))
        })
        .await
    }

    pub async fn get_file(&self, file_id: &str) -> Result<File> {
        let response = self
            .core
            .execute(self.core.get(self.file_url(file_id)?))
            .await?;
        Ok(response.json().await?)
    }

    pub async fn create_folder(&self, name: &str, parent_id: Option<&str>) -> Result<File> {
        let mut body = serde_json::Map::new();
        body.insert("name".into(), name.into());
        body.insert("mimeType".into(), FOLDER_MIME_TYPE.into());
        if let Some(parent_id) = parent_id {
            body.insert(
                "parents".into(),
                serde_json::Value::Array(vec![parent_id.into()]),
            );
        }

        let response = self
            .core
            .execute(self.core.post(self.api_url("files")?).json(&body))
            .await?;
        Ok(response.json().await?)
    }

    pub async fn download_file(&self, file_id: &str, dest: &Path) -> Result<u64> {
        let response = self
            .core
            .execute(self.core.get(self.media_url(file_id)?))
            .await?;
        Self::write_response_to_path(response, dest).await
    }

    pub async fn download_file_bytes(&self, file_id: &str) -> Result<Vec<u8>> {
        let response = self
            .core
            .execute(self.core.get(self.media_url(file_id)?))
            .await?;
        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }

    pub async fn export_file(&self, file_id: &str, mime_type: &str, dest: &Path) -> Result<u64> {
        let response = self
            .core
            .execute(self.core.get(self.export_url(file_id, mime_type)?))
            .await
            .map_err(|error| match error {
                GrrError::PermissionDenied(message) => GrrError::Api {
                    status: 403,
                    message: format!("Drive export failed: {message}"),
                },
                other => other,
            })?;
        Self::write_response_to_path(response, dest).await
    }

    pub async fn upload_file(
        &self,
        path: &Path,
        name: Option<&str>,
        parent_id: Option<&str>,
    ) -> Result<File> {
        let filename = name.map_or_else(
            || {
                path.file_name().map_or_else(
                    || path.display().to_string(),
                    |name| name.to_string_lossy().into_owned(),
                )
            },
            str::to_owned,
        );
        let mime = mime_guess::from_path(path)
            .first_or_octet_stream()
            .to_string();

        let mut metadata = serde_json::Map::new();
        metadata.insert("name".into(), filename.into());
        if let Some(parent_id) = parent_id {
            metadata.insert(
                "parents".into(),
                serde_json::Value::Array(vec![parent_id.into()]),
            );
        }
        let metadata_json = serde_json::Value::Object(metadata).to_string();

        let boundary = generate_boundary();
        let prefix = format!(
            "--{boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{metadata_json}\r\n--{boundary}\r\nContent-Type: {mime}\r\n\r\n"
        );
        let suffix = format!("\r\n--{boundary}--\r\n");
        let media = tokio::fs::File::open(path).await?;
        let media_length = media.metadata().await?.len();
        let content_length = (prefix.len() + suffix.len()) as u64 + media_length;
        let media_stream = ReaderStream::with_capacity(media, 64 * 1024);
        let prefix_stream = stream::once(future::ready(Ok::<Bytes, std::io::Error>(Bytes::from(
            prefix,
        ))));
        let suffix_stream = stream::once(future::ready(Ok::<Bytes, std::io::Error>(Bytes::from(
            suffix,
        ))));
        let body_stream = prefix_stream.chain(media_stream).chain(suffix_stream);

        let mut url = self.upload_url("files")?;
        url.query_pairs_mut().append_pair("uploadType", "multipart");

        let response = self
            .core
            .execute(
                self.core
                    .post(url)
                    .header(
                        CONTENT_TYPE,
                        format!("multipart/related; boundary={boundary}"),
                    )
                    .header(CONTENT_LENGTH, content_length.to_string())
                    .body(reqwest::Body::wrap_stream(body_stream)),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<File> {
        let response = self
            .core
            .execute(
                self.core
                    .patch(self.file_url(file_id)?)
                    .json(&serde_json::json!({ "name": new_name })),
            )
            .await?;
        Ok(response.json().await?)
    }

    async fn set_trashed(&self, file_id: &str, trashed: bool) -> Result<File> {
        let response = self
            .core
            .execute(
                self.core
                    .patch(self.file_url(file_id)?)
                    .json(&serde_json::json!({ "trashed": trashed })),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn trash_file(&self, file_id: &str) -> Result<File> {
        self.set_trashed(file_id, true).await
    }

    pub async fn restore_file(&self, file_id: &str) -> Result<File> {
        self.set_trashed(file_id, false).await
    }

    pub async fn copy_file(
        &self,
        file_id: &str,
        name: Option<&str>,
        parent_id: Option<&str>,
    ) -> Result<File> {
        let mut body = serde_json::Map::new();
        if let Some(name) = name {
            body.insert("name".into(), name.into());
        }
        if let Some(parent_id) = parent_id {
            body.insert(
                "parents".into(),
                serde_json::Value::Array(vec![parent_id.into()]),
            );
        }

        let response = self
            .core
            .execute(
                self.core
                    .post(self.file_collection_url(file_id, "copy")?)
                    .json(&body),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn delete_file(&self, file_id: &str) -> Result<()> {
        self.core
            .execute(self.core.delete(self.file_url(file_id)?))
            .await?;
        Ok(())
    }

    pub async fn empty_trash(&self) -> Result<()> {
        self.core
            .execute(self.core.post(self.api_url("files/emptyTrash")?))
            .await?;
        Ok(())
    }

    pub async fn list_permissions(
        &self,
        file_id: &str,
        max_results: usize,
    ) -> Result<Vec<Permission>> {
        let max = if max_results == 0 {
            None
        } else {
            Some(max_results)
        };
        let batch_size = page_size(max_results, MAX_SUBRESOURCE_PAGE_SIZE);

        paginate(max, move |page_token| async move {
            let params = QueryParams::new()
                .add("pageSize", batch_size.to_string())
                .add("fields", PERMISSION_FIELDS)
                .add_page_token(page_token.as_deref());
            let page: PermissionList = self
                .core
                .execute_json(
                    params.apply(
                        self.core
                            .get(self.file_collection_url(file_id, "permissions")?),
                    ),
                )
                .await?;
            Ok(Page::new(page.permissions, page.next_page_token))
        })
        .await
    }

    pub async fn create_permission(
        &self,
        file_id: &str,
        role: &str,
        grant: &PermissionGrant,
        send_notification_email: bool,
    ) -> Result<Permission> {
        let mut body = serde_json::Map::new();
        body.insert("role".into(), role.into());
        match grant {
            PermissionGrant::User { email_address } => {
                body.insert("type".into(), "user".into());
                body.insert("emailAddress".into(), email_address.as_str().into());
            }
            PermissionGrant::Domain { domain } => {
                body.insert("type".into(), "domain".into());
                body.insert("domain".into(), domain.as_str().into());
            }
            PermissionGrant::Anyone => {
                body.insert("type".into(), "anyone".into());
            }
        }

        let mut request = self
            .core
            .post(self.file_collection_url(file_id, "permissions")?)
            .query(&[("fields", PERMISSION_FIELDS)])
            .json(&body);
        if matches!(grant, PermissionGrant::User { .. }) {
            let notification = send_notification_email.to_string();
            request = request.query(&[("sendNotificationEmail", notification.as_str())]);
        }

        let response = self.core.execute(request).await?;
        Ok(response.json().await?)
    }

    pub async fn delete_permission(&self, file_id: &str, permission_id: &str) -> Result<()> {
        self.core
            .execute(
                self.core
                    .delete(self.file_item_url(file_id, "permissions", permission_id)?),
            )
            .await?;
        Ok(())
    }

    pub async fn list_comments(&self, file_id: &str, max_results: usize) -> Result<Vec<Comment>> {
        let max = if max_results == 0 {
            None
        } else {
            Some(max_results)
        };
        let batch_size = page_size(max_results, MAX_SUBRESOURCE_PAGE_SIZE);

        paginate(max, move |page_token| async move {
            let params = QueryParams::new()
                .add("pageSize", batch_size.to_string())
                .add("fields", COMMENT_LIST_FIELDS)
                .add_page_token(page_token.as_deref());
            let page: CommentList = self
                .core
                .execute_json(
                    params.apply(
                        self.core
                            .get(self.file_collection_url(file_id, "comments")?),
                    ),
                )
                .await?;
            Ok(Page::new(page.comments, page.next_page_token))
        })
        .await
    }

    pub async fn get_comment(&self, file_id: &str, comment_id: &str) -> Result<Comment> {
        let response = self
            .core
            .execute(
                self.core
                    .get(self.file_item_url(file_id, "comments", comment_id)?)
                    .query(&[("fields", COMMENT_FIELDS)]),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn create_comment(&self, file_id: &str, content: &str) -> Result<Comment> {
        let response = self
            .core
            .execute(
                self.core
                    .post(self.file_collection_url(file_id, "comments")?)
                    .query(&[("fields", COMMENT_FIELDS)])
                    .json(&serde_json::json!({ "content": content })),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn delete_comment(&self, file_id: &str, comment_id: &str) -> Result<()> {
        self.core
            .execute(
                self.core
                    .delete(self.file_item_url(file_id, "comments", comment_id)?),
            )
            .await?;
        Ok(())
    }

    pub async fn list_revisions(&self, file_id: &str, max_results: usize) -> Result<Vec<Revision>> {
        let max = if max_results == 0 {
            None
        } else {
            Some(max_results)
        };
        let batch_size = page_size(max_results, MAX_SUBRESOURCE_PAGE_SIZE);

        paginate(max, move |page_token| async move {
            let params = QueryParams::new()
                .add("pageSize", batch_size.to_string())
                .add("fields", REVISION_LIST_FIELDS)
                .add_page_token(page_token.as_deref());
            let page: RevisionList = self
                .core
                .execute_json(
                    params.apply(
                        self.core
                            .get(self.file_collection_url(file_id, "revisions")?),
                    ),
                )
                .await?;
            Ok(Page::new(page.revisions, page.next_page_token))
        })
        .await
    }

    pub async fn get_revision(&self, file_id: &str, revision_id: &str) -> Result<Revision> {
        let response = self
            .core
            .execute(
                self.core
                    .get(self.file_item_url(file_id, "revisions", revision_id)?)
                    .query(&[("fields", REVISION_FIELDS)]),
            )
            .await?;
        Ok(response.json().await?)
    }

    pub async fn about(&self) -> Result<About> {
        let response = self
            .core
            .execute(
                self.core
                    .get(self.api_url("about")?)
                    .query(&[("fields", "user,storageQuota")]),
            )
            .await?;
        Ok(response.json().await?)
    }
}