opendal/services/dropbox/
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 jiff::Timestamp;
19use std::fmt::Debug;
20use std::fmt::Formatter;
21use std::sync::Arc;
22use tokio::sync::Mutex;
23
24use super::DEFAULT_SCHEME;
25use super::backend::DropboxBackend;
26use super::core::DropboxCore;
27use super::core::DropboxSigner;
28use crate::raw::*;
29use crate::services::DropboxConfig;
30use crate::*;
31impl Configurator for DropboxConfig {
32    type Builder = DropboxBuilder;
33
34    #[allow(deprecated)]
35    fn into_builder(self) -> Self::Builder {
36        DropboxBuilder {
37            config: self,
38            http_client: None,
39        }
40    }
41}
42
43/// [Dropbox](https://www.dropbox.com/) backend support.
44#[doc = include_str!("docs.md")]
45#[derive(Default)]
46pub struct DropboxBuilder {
47    config: DropboxConfig,
48
49    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
50    http_client: Option<HttpClient>,
51}
52
53impl Debug for DropboxBuilder {
54    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
55        f.debug_struct("Builder")
56            .field("root", &self.config.root)
57            .finish()
58    }
59}
60
61impl DropboxBuilder {
62    /// Set the root directory for dropbox.
63    ///
64    /// Default to `/` if not set.
65    pub fn root(mut self, root: &str) -> Self {
66        self.config.root = if root.is_empty() {
67            None
68        } else {
69            Some(root.to_string())
70        };
71
72        self
73    }
74
75    /// Access token is used for temporary access to the Dropbox API.
76    ///
77    /// You can get the access token from [Dropbox App Console](https://www.dropbox.com/developers/apps)
78    ///
79    /// NOTE: this token will be expired in 4 hours.
80    /// If you are trying to use the Dropbox service in a long time, please set a refresh_token instead.
81    pub fn access_token(mut self, access_token: &str) -> Self {
82        self.config.access_token = Some(access_token.to_string());
83        self
84    }
85
86    /// Refresh token is used for long term access to the Dropbox API.
87    ///
88    /// You can get the refresh token via OAuth 2.0 Flow of Dropbox.
89    ///
90    /// OpenDAL will use this refresh token to get a new access token when the old one is expired.
91    pub fn refresh_token(mut self, refresh_token: &str) -> Self {
92        self.config.refresh_token = Some(refresh_token.to_string());
93        self
94    }
95
96    /// Set the client id for Dropbox.
97    ///
98    /// This is required for OAuth 2.0 Flow to refresh the access token.
99    pub fn client_id(mut self, client_id: &str) -> Self {
100        self.config.client_id = Some(client_id.to_string());
101        self
102    }
103
104    /// Set the client secret for Dropbox.
105    ///
106    /// This is required for OAuth 2.0 Flow with refresh the access token.
107    pub fn client_secret(mut self, client_secret: &str) -> Self {
108        self.config.client_secret = Some(client_secret.to_string());
109        self
110    }
111
112    /// Specify the http client that used by this service.
113    ///
114    /// # Notes
115    ///
116    /// This API is part of OpenDAL's Raw API. `HttpClient` could be changed
117    /// during minor updates.
118    #[deprecated(since = "0.53.0", note = "Use `Operator::update_http_client` instead")]
119    #[allow(deprecated)]
120    pub fn http_client(mut self, http_client: HttpClient) -> Self {
121        self.http_client = Some(http_client);
122        self
123    }
124}
125
126impl Builder for DropboxBuilder {
127    type Config = DropboxConfig;
128
129    fn build(self) -> Result<impl Access> {
130        let root = normalize_root(&self.config.root.unwrap_or_default());
131
132        let signer = match (self.config.access_token, self.config.refresh_token) {
133            (Some(access_token), None) => DropboxSigner {
134                access_token,
135                // We will never expire user specified token.
136                expires_in: Timestamp::MAX,
137                ..Default::default()
138            },
139            (None, Some(refresh_token)) => {
140                let client_id = self.config.client_id.ok_or_else(|| {
141                    Error::new(
142                        ErrorKind::ConfigInvalid,
143                        "client_id must be set when refresh_token is set",
144                    )
145                    .with_context("service", Scheme::Dropbox)
146                })?;
147                let client_secret = self.config.client_secret.ok_or_else(|| {
148                    Error::new(
149                        ErrorKind::ConfigInvalid,
150                        "client_secret must be set when refresh_token is set",
151                    )
152                    .with_context("service", Scheme::Dropbox)
153                })?;
154
155                DropboxSigner {
156                    refresh_token,
157                    client_id,
158                    client_secret,
159                    ..Default::default()
160                }
161            }
162            (Some(_), Some(_)) => {
163                return Err(Error::new(
164                    ErrorKind::ConfigInvalid,
165                    "access_token and refresh_token can not be set at the same time",
166                )
167                .with_context("service", Scheme::Dropbox));
168            }
169            (None, None) => {
170                return Err(Error::new(
171                    ErrorKind::ConfigInvalid,
172                    "access_token or refresh_token must be set",
173                )
174                .with_context("service", Scheme::Dropbox));
175            }
176        };
177
178        Ok(DropboxBackend {
179            core: Arc::new(DropboxCore {
180                info: {
181                    let am = AccessorInfo::default();
182                    am.set_scheme(DEFAULT_SCHEME)
183                        .set_root(&root)
184                        .set_native_capability(Capability {
185                            stat: true,
186
187                            read: true,
188
189                            write: true,
190
191                            create_dir: true,
192
193                            delete: true,
194
195                            list: true,
196                            list_with_recursive: true,
197
198                            copy: true,
199
200                            rename: true,
201
202                            shared: true,
203
204                            ..Default::default()
205                        });
206
207                    // allow deprecated api here for compatibility
208                    #[allow(deprecated)]
209                    if let Some(client) = self.http_client {
210                        am.update_http_client(|_| client);
211                    }
212
213                    am.into()
214                },
215                root,
216                signer: Arc::new(Mutex::new(signer)),
217            }),
218        })
219    }
220}