opendal/services/gdrive/
builder.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19use std::fmt::Formatter;
20use std::sync::Arc;
21
22use chrono::DateTime;
23use chrono::Utc;
24use log::debug;
25use tokio::sync::Mutex;
26
27use super::backend::GdriveBackend;
28use super::core::GdriveCore;
29use super::core::GdrivePathQuery;
30use super::core::GdriveSigner;
31use crate::raw::normalize_root;
32use crate::raw::Access;
33use crate::raw::AccessorInfo;
34use crate::raw::HttpClient;
35use crate::raw::PathCacher;
36use crate::services::GdriveConfig;
37use crate::Scheme;
38use crate::*;
39
40impl Configurator for GdriveConfig {
41    type Builder = GdriveBuilder;
42
43    #[allow(deprecated)]
44    fn into_builder(self) -> Self::Builder {
45        GdriveBuilder {
46            config: self,
47            http_client: None,
48        }
49    }
50}
51
52/// [GoogleDrive](https://drive.google.com/) backend support.
53#[derive(Default)]
54#[doc = include_str!("docs.md")]
55pub struct GdriveBuilder {
56    config: GdriveConfig,
57
58    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
59    http_client: Option<HttpClient>,
60}
61
62impl Debug for GdriveBuilder {
63    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("Backend")
65            .field("config", &self.config)
66            .finish()
67    }
68}
69
70impl GdriveBuilder {
71    /// Set root path of GoogleDrive folder.
72    pub fn root(mut self, root: &str) -> Self {
73        self.config.root = if root.is_empty() {
74            None
75        } else {
76            Some(root.to_string())
77        };
78
79        self
80    }
81
82    /// Access token is used for temporary access to the GoogleDrive API.
83    ///
84    /// You can get the access token from [GoogleDrive App Console](https://console.cloud.google.com/apis/credentials)
85    /// or [GoogleDrive OAuth2 Playground](https://developers.google.com/oauthplayground/)
86    ///
87    /// # Note
88    ///
89    /// - An access token is valid for 1 hour.
90    /// - If you want to use the access token for a long time,
91    ///   you can use the refresh token to get a new access token.
92    pub fn access_token(mut self, access_token: &str) -> Self {
93        self.config.access_token = Some(access_token.to_string());
94        self
95    }
96
97    /// Refresh token is used for long term access to the GoogleDrive API.
98    ///
99    /// You can get the refresh token via OAuth 2.0 Flow of GoogleDrive API.
100    ///
101    /// OpenDAL will use this refresh token to get a new access token when the old one is expired.
102    pub fn refresh_token(mut self, refresh_token: &str) -> Self {
103        self.config.refresh_token = Some(refresh_token.to_string());
104        self
105    }
106
107    /// Set the client id for GoogleDrive.
108    ///
109    /// This is required for OAuth 2.0 Flow to refresh the access token.
110    pub fn client_id(mut self, client_id: &str) -> Self {
111        self.config.client_id = Some(client_id.to_string());
112        self
113    }
114
115    /// Set the client secret for GoogleDrive.
116    ///
117    /// This is required for OAuth 2.0 Flow with refresh the access token.
118    pub fn client_secret(mut self, client_secret: &str) -> Self {
119        self.config.client_secret = Some(client_secret.to_string());
120        self
121    }
122
123    /// Specify the http client that used by this service.
124    ///
125    /// # Notes
126    ///
127    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
128    /// during minor updates.
129    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
130    #[allow(deprecated)]
131    pub fn http_client(mut self, http_client: HttpClient) -> Self {
132        self.http_client = Some(http_client);
133        self
134    }
135}
136
137impl Builder for GdriveBuilder {
138    const SCHEME: Scheme = Scheme::Gdrive;
139    type Config = GdriveConfig;
140
141    fn build(self) -> Result<impl Access> {
142        let root = normalize_root(&self.config.root.unwrap_or_default());
143        debug!("backend use root {}", root);
144
145        let info = AccessorInfo::default();
146        info.set_scheme(Scheme::Gdrive)
147            .set_root(&root)
148            .set_native_capability(Capability {
149                stat: true,
150                stat_has_content_length: true,
151                stat_has_content_type: true,
152                stat_has_last_modified: true,
153
154                read: true,
155
156                list: true,
157                list_has_content_type: true,
158                list_has_content_length: true,
159                list_has_etag: true,
160
161                write: true,
162
163                create_dir: true,
164                delete: true,
165                rename: true,
166                copy: true,
167
168                shared: true,
169
170                ..Default::default()
171            });
172
173        // allow deprecated api here for compatibility
174        #[allow(deprecated)]
175        if let Some(client) = self.http_client {
176            info.update_http_client(|_| client);
177        }
178
179        let accessor_info = Arc::new(info);
180        let mut signer = GdriveSigner::new(accessor_info.clone());
181        match (self.config.access_token, self.config.refresh_token) {
182            (Some(access_token), None) => {
183                signer.access_token = access_token;
184                // We will never expire user specified access token.
185                signer.expires_in = DateTime::<Utc>::MAX_UTC;
186            }
187            (None, Some(refresh_token)) => {
188                let client_id = self.config.client_id.ok_or_else(|| {
189                    Error::new(
190                        ErrorKind::ConfigInvalid,
191                        "client_id must be set when refresh_token is set",
192                    )
193                    .with_context("service", Scheme::Gdrive)
194                })?;
195                let client_secret = self.config.client_secret.ok_or_else(|| {
196                    Error::new(
197                        ErrorKind::ConfigInvalid,
198                        "client_secret must be set when refresh_token is set",
199                    )
200                    .with_context("service", Scheme::Gdrive)
201                })?;
202
203                signer.refresh_token = refresh_token;
204                signer.client_id = client_id;
205                signer.client_secret = client_secret;
206            }
207            (Some(_), Some(_)) => {
208                return Err(Error::new(
209                    ErrorKind::ConfigInvalid,
210                    "access_token and refresh_token cannot be set at the same time",
211                )
212                .with_context("service", Scheme::Gdrive))
213            }
214            (None, None) => {
215                return Err(Error::new(
216                    ErrorKind::ConfigInvalid,
217                    "access_token or refresh_token must be set",
218                )
219                .with_context("service", Scheme::Gdrive))
220            }
221        };
222
223        let signer = Arc::new(Mutex::new(signer));
224
225        Ok(GdriveBackend {
226            core: Arc::new(GdriveCore {
227                info: accessor_info.clone(),
228                root,
229                signer: signer.clone(),
230                path_cache: PathCacher::new(GdrivePathQuery::new(accessor_info, signer))
231                    .with_lock(),
232            }),
233        })
234    }
235}