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
#![allow(clippy::field_reassign_with_default)]
use anyhow::{anyhow, Result};

#[async_trait::async_trait]
pub trait FileOps {
    /// Get a file by it's name.
    async fn get_by_name(
        &self,
        drive_id: &str,
        parent_id: &str,
        name: &str,
    ) -> Result<Vec<crate::types::File>>;

    /// Create or update a file in a drive.
    /// If the file already exists, it will update it.
    /// If the file does not exist, it will create it.
    async fn create_or_update(
        &self,
        drive_id: &str,
        parent_id: &str,
        name: &str,
        mime_type: &str,
        contents: &[u8],
    ) -> Result<crate::types::File>;

    /// Download a file by it's ID.
    async fn download_by_id(&self, id: &str) -> Result<bytes::Bytes>;

    /// Create a folder, if it doesn't exist, returns the ID of the folder.
    async fn create_folder(&self, drive_id: &str, parent_id: &str, name: &str) -> Result<String>;

    /// Get a file's contents by it's ID. Only works for Google Docs.
    async fn get_contents_by_id(&self, id: &str) -> Result<String>;

    /// Delete a file by its name.
    async fn delete_by_name(&self, drive_id: &str, parent_id: &str, name: &str) -> Result<()>;
}

#[async_trait::async_trait]
impl FileOps for crate::files::Files {
    /// Get a file by it's name.
    async fn get_by_name(
        &self,
        drive_id: &str,
        parent_id: &str,
        name: &str,
    ) -> Result<Vec<crate::types::File>> {
        let mut query = format!("name = '{}'", name);
        if !parent_id.is_empty() {
            query = format!("{} and '{}' in parents", query, parent_id);
        }

        self.list_all(
            "drive",  // corpora
            drive_id, // drive id
            true,     // include_items_from_all_drives
            "",       // include_permissions_for_view
            false,    // include_team_drive_items
            "",       // order_by
            &query,   // query
            "",       // spaces
            true,     // supports_all_drives
            false,    // supports_team_drives
            "",       // team_drive_id
        )
        .await
    }

    /// Create or update a file in a drive.
    /// If the file already exists, it will update it.
    /// If the file does not exist, it will create it.
    async fn create_or_update(
        &self,
        drive_id: &str,
        parent_id: &str,
        name: &str,
        mime_type: &str,
        contents: &[u8],
    ) -> Result<crate::types::File> {
        // Create the file.
        let mut f: crate::types::File = Default::default();
        let mut method = reqwest::Method::POST;
        let mut uri = "https://www.googleapis.com/upload/drive/v3/files".to_string();

        // Check if the file exists.
        let files = self
            .get_by_name(drive_id, parent_id, name)
            .await
            .unwrap_or_default();
        if files.is_empty() {
            // Set the name,
            f.name = name.to_string();
            f.mime_type = mime_type.to_string();
            if !parent_id.is_empty() {
                f.parents = vec![parent_id.to_string()];
            } else {
                f.parents = vec![drive_id.to_string()];
            }

            uri += "?uploadType=resumable&supportsAllDrives=true&includeItemsFromAllDrives=true";

            // Create the file.
        } else {
            method = reqwest::Method::PATCH;

            f = files.get(0).unwrap().clone();
            uri += &format!(
                "/{}?uploadType=resumable&supportsAllDrives=true&includeItemsFromAllDrives=true",
                f.id
            );

            f.id = "".to_string();
            f.drive_id = "".to_string();
            f.kind = "".to_string();
            f.original_filename = f.name.to_string();
        }

        // Build the request to get the URL upload location if we need to create the file.
        let resp = self
            .client
            .request_raw(
                method,
                &uri,
                Some(reqwest::Body::from(serde_json::to_vec(&f).unwrap())),
            )
            .await
            .unwrap();

        // Get the "Location" header.
        let location = resp.headers().get("Location").unwrap().to_str().unwrap();

        // Now upload the file to that location.
        Ok(self
            .client
            .request_with_mime(reqwest::Method::PUT, location, contents, mime_type)
            .await
            .unwrap())
    }

    /// Download a file by it's ID.
    async fn download_by_id(&self, id: &str) -> Result<bytes::Bytes> {
        let resp = self
            .client
            .request_raw(
                reqwest::Method::GET,
                &format!("/files/{}?supportsAllDrives=true&alt=media", id),
                None,
            )
            .await
            .unwrap();

        Ok(resp.bytes().await.unwrap())
    }

    /// Create a folder, if it doesn't exist, returns the ID of the folder.
    async fn create_folder(&self, drive_id: &str, parent_id: &str, name: &str) -> Result<String> {
        let folder_mime_type = "application/vnd.google-apps.folder";
        let mut file: crate::types::File = Default::default();
        // Set the name,
        file.name = name.to_string();
        file.mime_type = folder_mime_type.to_string();
        if !parent_id.is_empty() {
            file.parents = vec![parent_id.to_string()];
        } else {
            file.parents = vec![drive_id.to_string()];
        }

        let mut query = format!(
            "name = '{}' and mimeType = 'application/vnd.google-apps.folder'",
            name
        );
        if !parent_id.is_empty() {
            query = format!("{} and '{}' in parents", query, parent_id);
        }

        // Check if the folder exists.
        let folders = self
            .list_all(
                "drive",  // corpora
                drive_id, // drive id
                true,     // include_items_from_all_drives
                "",       // include_permissions_for_view
                false,    // include_team_drive_items
                "",       // order_by
                &query,   // query
                "",       // spaces
                true,     // supports_all_drives
                false,    // supports_team_drives
                "",       // team_drive_id
            )
            .await
            .unwrap_or_default();
        if !folders.is_empty() {
            let f = folders.get(0).unwrap().clone();
            return Ok(f.id);
        }

        // Make the request and return the ID.
        let folder: crate::types::File = self
            .client
            .post(
                "/files?supportsAllDrives=true&includeItemsFromAllDrives=true",
                Some(reqwest::Body::from(serde_json::to_vec(&file).unwrap())),
            )
            .await
            .unwrap();

        Ok(folder.id)
    }

    /// Get a file's contents by it's ID. Only works for Google Docs.
    // TODO: make binary content work in the actual library.
    async fn get_contents_by_id(&self, id: &str) -> Result<String> {
        let mut query_ = String::new();
        let query_args = vec!["mime_type=text/plain".to_string()];
        for (i, n) in query_args.iter().enumerate() {
            if i > 0 {
                query_.push('&');
            }
            query_.push_str(n);
        }
        let url = format!(
            "/files/{}/export?{}",
            crate::progenitor_support::encode_path(&id.to_string()),
            query_
        );
        let resp = self
            .client
            .request_raw(reqwest::Method::GET, &url, None)
            .await
            .unwrap();

        Ok(resp.text().await.unwrap())
    }

    /// Delete a file by its name.
    async fn delete_by_name(&self, drive_id: &str, parent_id: &str, name: &str) -> Result<()> {
        // Check if the file exists.
        let files = self
            .get_by_name(drive_id, parent_id, name)
            .await
            .unwrap_or_default();
        if files.is_empty() {
            // The file does not exist.
            return Ok(());
        }

        // Delete the file.
        self.delete(
            &files.get(0).unwrap().id,
            true, // supports all drives
            true, // supports team drives
        )
        .await
    }
}

#[async_trait::async_trait]
pub trait DriveOps {
    /// Get a drive by it's name.
    async fn get_by_name(&self, name: &str) -> Result<crate::types::Drive>;
}

#[async_trait::async_trait]
impl DriveOps for crate::drives::Drives {
    /// Get a drive by it's name.
    async fn get_by_name(&self, name: &str) -> Result<crate::types::Drive> {
        let drives = self
            .list_all(
                //&format!("name = '{}'", name), // query
                "", true, // use domain admin access
            )
            .await
            .unwrap();

        for drive in drives {
            if drive.name == name {
                return Ok(drive);
            }
        }

        Err(anyhow!("could not find drive with name: {:?}", name))
    }
}