dco3 0.3.0

Async API wrapper for DRACOON in Rust.
Documentation
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
#![allow(dead_code)]
#![allow(unused_variables)]

//! # dco3 - DRACOON API wrapper in Rust
//!
//! `dco3` is an async wrapper around API calls in DRACOON.
//! DRACOON is a cloud service provider - more information can be found on <https://dracoon.com>.
//! The name is based on several other projects pointing to oxide (Rust) and DRACOON.
//!
//! ## Usage
//! All API calls are implemented by the `Dracoon` struct. It can be created by using the `builder()` method.
//! 
//! In order to access specific API calls, the `Dracoon` struct needs to be in the `Connected` state. 
//! This can be achieved by calling the `connect` method.
//! To use specific endpoints, you need to import relevant traits.
//! Currently, the following traits are implemented:
//! 
//! * [User] - for user account management
//! * [UserAccountKeypairs] - for user keypair management
//! * [Nodes] - for node operations (folders, rooms, upload and download are excluded)
//! * [Download] - for downloading files
//! * [Upload] - for uploading files
//! * [Folders] - for folder operations
//! * [Rooms] - for room operations
//! * [DownloadShares] - for download share operations
//! * [UploadShares] - for upload share operations
//! * [Groups] - for group operations
//! * [Users] - for user management operations
//! 
//! 
//! ### Example
//! ```no_run
//! use dco3::{Dracoon, OAuth2Flow, User};
//! 
//! #[tokio::main]
//! async fn main() {
//!    let dracoon = Dracoon::builder()
//!       .with_base_url("https://dracoon.team")
//!       .with_client_id("client_id")
//!       .with_client_secret("client_secret")
//!       .build()
//!       .unwrap()
//!       .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//!       .await
//!       .unwrap();
//! 
//!   let user_info = dracoon.get_user_account().await.unwrap();
//!   println!("User info: {:?}", user_info);
//! }
//!```
//! 
//! ## Authentication
//! 
//! All supported OAuth2 flows are implemented. 
//! 
//! ### Password Flow
//! ```no_run
//! use dco3::{Dracoon, OAuth2Flow};
//! 
//! #[tokio::main]
//! async fn main() {
//! 
//!    // you can instantiate the required flow by using the `OAuth2Flow` enum
//!    let password_flow = OAuth2Flow::PasswordFlow("username".into(), "password".into());
//! 
//!    let dracoon = Dracoon::builder()
//!       .with_base_url("https://dracoon.team")
//!       .with_client_id("client_id")
//!       .with_client_secret("client_secret")
//!       .build()
//!       .unwrap()
//!       .connect(password_flow)
//!       .await
//!       .unwrap();
//! }
//!```
//! ### Authorization Code Flow
//! ```no_run
//! use dco3::{Dracoon, OAuth2Flow};
//! 
//! #[tokio::main]
//! async fn main() {
//! 
//!    let mut dracoon = Dracoon::builder()
//!       .with_base_url("https://dracoon.team")
//!       .with_client_id("client_id")
//!       .with_client_secret("client_secret")
//!       .with_redirect_uri("https://redirect.uri")
//!       .build()
//!       .unwrap();
//! 
//!    // initiate the authorization code flow
//!    let authorize_url = dracoon.get_authorize_url();
//! 
//!    // get auth code
//!    let auth_code = "some_auth_code";
//! 
//!    // you can instantiate the required flow by using the `OAuth2Flow` enum
//!    let auth_code_flow = OAuth2Flow::AuthCodeFlow("auth_code".into());
//! 
//!    let dracoon = dracoon.connect(auth_code_flow).await.unwrap();
//! }
//!```
//! 
//! ### Refresh Token
//! 
//! ```no_run
//! use dco3::{Dracoon, OAuth2Flow};
//! 
//! #[tokio::main]
//! async fn main() {
//! 
//!   let refresh_token = "some_refresh_token";
//! 
//!   let dracoon = Dracoon::builder()
//!     .with_base_url("https://dracoon.team")
//!     .with_client_id("client_id")
//!     .with_client_secret("client_secret")
//!     .build()
//!     .unwrap()
//!     .connect(OAuth2Flow::RefreshToken(refresh_token.into()))
//!     .await
//!     .unwrap();
//! 
//! }
//! ```
//! 
//! ## Error handling
//! 
//! All errors are wrapped in the [DracoonClientError] enum.
//! 
//! Most errrors are related to general usage (like missing parameters). 
//! 
//! All API errors are wrapped in the `DracoonClientError::Http` variant.
//! The variant contains response with relevant status code and message.
//! 
//! You can check if the underlying error message if a specific API error by using the `is_*` methods.
//! 
//! ```no_run
//! use dco3::{Dracoon, OAuth2Flow, Nodes};
//! 
//! #[tokio::main]
//! 
//! async fn main() {
//! 
//!  let dracoon = Dracoon::builder()
//!    .with_base_url("https://dracoon.team")
//!    .with_client_id("client_id")
//!    .with_client_secret("client_secret")
//!    .build()
//!    .unwrap()
//!    .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//!    .await
//!    .unwrap();
//! 
//! let node = dracoon.get_node(123).await;
//! 
//! match node {
//!  Ok(node) => println!("Node info: {:?}", node),
//! Err(err) => {
//!  if err.is_not_found() {
//!     println!("Node not found");
//!     } else {
//!          println!("Error: {:?}", err);
//!            }
//!         }
//!       }
//!  }
//! 
//! ```
//! 
//! ### Retries 
//! The client will automatically retry failed requests.
//! You can configure the retry behavior by passing your config during client creation.
//! 
//! Default values are: 5 retries, min delay 600ms, max delay 20s.
//! Keep in mind that you cannot set arbitrary values - for all values, minimum and maximum values are defined.
//! 
//! ```
//! 
//! use dco3::{Dracoon, OAuth2Flow};
//! 
//! #[tokio::main]
//! async fn main() {
//! 
//!  let dracoon = Dracoon::builder()
//!   .with_base_url("https://dracoon.team")
//!   .with_client_id("client_id")
//!   .with_client_secret("client_secret")
//!   .with_max_retries(3)
//!   .with_min_retry_delay(400)
//!   .with_max_retry_delay(1000)
//!   .build();
//! 
//! }
//! 
//! ```
//! 
//! ## Building requests
//! 
//! All API calls are implemented as traits.
//! Each API call that requires a sepcific payload has a corresponding builder.
//! To access the builder, you can call the builder() method.
//! 
//! ```no_run
//! # use dco3::{Dracoon, OAuth2Flow, Rooms, nodes::CreateRoomRequest};
//! # #[tokio::main]
//! # async fn main() {
//! # let dracoon = Dracoon::builder()
//! #  .with_base_url("https://dracoon.team")
//! #  .with_client_id("client_id")
//! #  .with_client_secret("client_secret")
//! #  .build()
//! #  .unwrap()
//! #  .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//! #  .await
//! #  .unwrap();
//! let room = CreateRoomRequest::builder("My Room")
//!            .with_parent_id(123)
//!            .with_admin_ids(vec![1, 2, 3])
//!            .build();
//! 
//! let room = dracoon.create_room(room).await.unwrap();
//! 
//! # }
//! ```
//! Some requests do not have any complicated fields - in these cases, use the `new()` method.
//! ```no_run
//! # use dco3::{Dracoon, OAuth2Flow, Groups, groups::CreateGroupRequest};
//! # #[tokio::main]
//! # async fn main() {
//! # let dracoon = Dracoon::builder()
//! #  .with_base_url("https://dracoon.team")
//! #  .with_client_id("client_id")
//! #  .with_client_secret("client_secret")
//! #  .build()
//! #  .unwrap()
//! #  .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//! #  .await
//! #  .unwrap();
//! 
//! // this takes a mandatory name and optional expiration
//! let group = CreateGroupRequest::new("My Group", None);
//! let group = dracoon.create_group(group).await.unwrap();
//! 
//! # }
//! ```
//! 
//! ## Pagination
//! 
//! GET endpoints are limited to 500 returned items - therefore you must paginate the content to fetch 
//! remaining items.
//! 
//! ```no_run
//! # use dco3::{Dracoon, auth::OAuth2Flow, Nodes, ListAllParams};
//! # #[tokio::main]
//! # async fn main() {
//! # let dracoon = Dracoon::builder()
//! #  .with_base_url("https://dracoon.team")
//! #  .with_client_id("client_id")
//! #  .with_client_secret("client_secret")
//! #  .build()
//! #  .unwrap()
//! #  .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//! #  .await
//! #  .unwrap(); 
//! 

//! // This fetches the first 500 nodes without any param
//!  let mut nodes = dracoon.get_nodes(None, None, None).await.unwrap();
//! 
//! // Iterate over the remaining nodes
//!  for offset in (0..nodes.range.total).step_by(500) {
//!  let params = ListAllParams::builder()
//!   .with_offset(offset)
//!   .build();
//!  let next_nodes = dracoon.get_nodes(None, None, Some(params)).await.unwrap();
//!  
//!   nodes.items.extend(next_nodes.items);
//! 
//! };
//! # }
//! ```
//! ## Cryptography support
//! All API calls (specifically up- and downloads) support encryption and decryption.
//! In order to use encryption, you need to get your keypair once the client is in `Connected` state.
//! 
//! ```no_run
//! # use dco3::{Dracoon, auth::OAuth2Flow, Nodes};
//! # #[tokio::main]
//! # async fn main() {
//! # let mut dracoon = Dracoon::builder()
//! #  .with_base_url("https://dracoon.team")
//! #  .with_client_id("client_id")
//! #  .with_client_secret("client_secret")
//! #  .build()
//! #  .unwrap()
//! #  .connect(OAuth2Flow::PasswordFlow("username".into(), "password".into()))
//! #  .await
//! #  .unwrap();
//! // get the keypair (also after providing the secret once)
//! dracoon.get_keypair(Some("my secret")).await.unwrap();
//! # }
//! ```
//! ## Examples
//! For an example client implementation, see the [dccmd-rs](https://github.com/unbekanntes-pferd/dccmd-rs) repository.

use std::marker::PhantomData;

use dco3_crypto::PlainUserKeyPairContainer;
use reqwest::Url;

use self::{
    auth::{Connected, Disconnected},
    auth::{DracoonClient, DracoonClientBuilder},
    user::{models::UserAccount},
};

// re-export traits and base models
pub use self::{
    nodes::{Download, Folders, Nodes, Rooms, Upload},
    user::{User, UserAccountKeypairs},
    auth::errors::DracoonClientError,
    auth::OAuth2Flow,
    groups::Groups,
    shares::{DownloadShares, UploadShares},
    users::Users,
    models::*,
};


pub mod auth;
pub mod constants;
pub mod models;
pub mod nodes;
pub mod user;
pub mod utils;
pub mod groups;
pub mod shares;
pub mod users;


/// DRACOON struct - implements all API calls via traits
#[derive(Clone)]
pub struct Dracoon<State = Disconnected> {
    client: DracoonClient<State>,
    state: PhantomData<State>,
    user_info: Option<UserAccount>,
    keypair: Option<PlainUserKeyPairContainer>,
}

/// Builder for the `Dracoon` struct.
/// Requires a base url, client id and client secret.
/// Optionally, a redirect uri can be provided.
/// For convenience, use the [Dracoon] builder method.
#[derive(Default)]
pub struct DracoonBuilder {
    client_builder: DracoonClientBuilder,
}

impl DracoonBuilder {
    /// Creates a new `DracoonBuilder`
    pub fn new() -> Self {
        let client_builder = DracoonClientBuilder::new();
        Self {
            client_builder,
        }
    }

    /// Sets the base url for the DRACOON instance
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.client_builder = self.client_builder.with_base_url(base_url);
        self
    }

    /// Sets the client id for the DRACOON instance
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
        self.client_builder = self.client_builder.with_client_id(client_id);
        self
    }

    /// Sets the client secret for the DRACOON instance
    pub fn with_client_secret(mut self, client_secret: impl Into<String>) -> Self {
        self.client_builder = self.client_builder.with_client_secret(client_secret);
        self
    }

    /// Sets the redirect uri for the DRACOON instance
    pub fn with_redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
        self.client_builder = self.client_builder.with_redirect_uri(redirect_uri);
        self
    }

    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.client_builder = self.client_builder.with_user_agent(user_agent);
        self
    }

    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.client_builder = self.client_builder.with_max_retries(max_retries);
        self
    }

    pub fn with_min_retry_delay(mut self, min_retry_delay: u64) -> Self {
        self.client_builder = self.client_builder.with_min_retry_delay(min_retry_delay);
        self
    }

    pub fn with_max_retry_delay(mut self, max_retry_delay: u64) -> Self {
        self.client_builder = self.client_builder.with_max_retry_delay(max_retry_delay);
        self
    }

    /// Builds the `Dracoon` struct - fails, if any of the required fields are missing
    pub fn build(self) -> Result<Dracoon<Disconnected>, DracoonClientError> {
        let dracoon = self.client_builder.build()?;

        Ok(Dracoon {
            client: dracoon,
            state: PhantomData,
            user_info: None,
            keypair: None,
        })
    }
}

impl Dracoon<Disconnected> {

    pub fn builder() -> DracoonBuilder {
        DracoonBuilder::new()
    }

    pub async fn connect(
        self,
        oauth_flow: OAuth2Flow,
    ) -> Result<Dracoon<Connected>, DracoonClientError> {
        let client = self.client.connect(oauth_flow).await?;

        Ok(Dracoon {
            client,
            state: PhantomData,
            user_info: None,
            keypair: None,
        })
    }

    pub fn get_authorize_url(&mut self) -> String {
        self.client.get_authorize_url()
    }
}

impl Dracoon<Connected> {
    pub fn build_api_url(&self, url_part: &str) -> Url {
        self.client
            .get_base_url()
            .join(url_part)
            .expect("Correct base url")
    }

    pub async fn get_auth_header(&self) -> Result<String, DracoonClientError> {
        self.client.get_auth_header().await
    }

    pub fn get_base_url(&self) -> &Url {
        self.client.get_base_url()
    }

    pub fn get_refresh_token(&self) -> &str {
        self.client.get_refresh_token()
    }

    pub async fn get_user_info(&mut self) -> Result<&UserAccount, DracoonClientError> {
        if let Some(ref user_info) = self.user_info {
            return Ok(user_info);
        }

        let user_info = self.get_user_account().await?;
        self.user_info = Some(user_info);
        Ok(self.user_info.as_ref().expect("Just set user info"))
    }

    pub async fn get_keypair(
        &mut self,
        secret: Option<&str>,
    ) -> Result<&PlainUserKeyPairContainer, DracoonClientError> {
        if let Some(ref keypair) = self.keypair {
            return Ok(keypair);
        }

        let secret = secret.ok_or(DracoonClientError::MissingEncryptionSecret)?;
        let keypair = self.get_user_keypair(secret).await?;
        self.keypair = Some(keypair);
        Ok(self.keypair.as_ref().expect("Just set keypair"))
    }
}