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
151                read: true,
152
153                list: true,
154
155                write: true,
156
157                create_dir: true,
158                delete: true,
159                rename: true,
160                copy: true,
161
162                shared: true,
163
164                ..Default::default()
165            });
166
167        // allow deprecated api here for compatibility
168        #[allow(deprecated)]
169        if let Some(client) = self.http_client {
170            info.update_http_client(|_| client);
171        }
172
173        let accessor_info = Arc::new(info);
174        let mut signer = GdriveSigner::new(accessor_info.clone());
175        match (self.config.access_token, self.config.refresh_token) {
176            (Some(access_token), None) => {
177                signer.access_token = access_token;
178                // We will never expire user specified access token.
179                signer.expires_in = DateTime::<Utc>::MAX_UTC;
180            }
181            (None, Some(refresh_token)) => {
182                let client_id = self.config.client_id.ok_or_else(|| {
183                    Error::new(
184                        ErrorKind::ConfigInvalid,
185                        "client_id must be set when refresh_token is set",
186                    )
187                    .with_context("service", Scheme::Gdrive)
188                })?;
189                let client_secret = self.config.client_secret.ok_or_else(|| {
190                    Error::new(
191                        ErrorKind::ConfigInvalid,
192                        "client_secret must be set when refresh_token is set",
193                    )
194                    .with_context("service", Scheme::Gdrive)
195                })?;
196
197                signer.refresh_token = refresh_token;
198                signer.client_id = client_id;
199                signer.client_secret = client_secret;
200            }
201            (Some(_), Some(_)) => {
202                return Err(Error::new(
203                    ErrorKind::ConfigInvalid,
204                    "access_token and refresh_token cannot be set at the same time",
205                )
206                .with_context("service", Scheme::Gdrive))
207            }
208            (None, None) => {
209                return Err(Error::new(
210                    ErrorKind::ConfigInvalid,
211                    "access_token or refresh_token must be set",
212                )
213                .with_context("service", Scheme::Gdrive))
214            }
215        };
216
217        let signer = Arc::new(Mutex::new(signer));
218
219        Ok(GdriveBackend {
220            core: Arc::new(GdriveCore {
221                info: accessor_info.clone(),
222                root,
223                signer: signer.clone(),
224                path_cache: PathCacher::new(GdrivePathQuery::new(accessor_info, signer))
225                    .with_lock(),
226            }),
227        })
228    }
229}