dbox 0.1.3

An unofficial Dropbox SDK
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use super::{Result, Response, DropboxClient, ApiError};
use std::default::Default;
use std::io;
use std::fmt;
use std::collections::BTreeMap;
use rustc_serialize::json;

use structs::{FolderList, Metadata, FileMetadata, NewFolder};

/// Instructs dropbox what to do when a conflict happens during upload
#[derive(Debug, PartialEq, Clone)]
pub enum WriteMode {
    Add,
    Overwrite,
    Update,
}

impl fmt::Display for WriteMode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            WriteMode::Add => write!(f, "add"),
            WriteMode::Overwrite => write!(f, "overwrite"),
            WriteMode::Update => write!(f, "update"),
        }
    }
}

/// Optional arguments to the `upload` API call
#[derive(Debug, PartialEq, Clone)]
pub struct UploadOptions {
    pub mode: WriteMode,
    pub autorename: bool,
    pub client_modified: Option<String>,
    pub mute: bool,
}

impl Default for UploadOptions {
    fn default() -> UploadOptions {
        UploadOptions {
            mode: WriteMode::Add,
            autorename: false,
            client_modified: None,
            mute: false,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum ThumbnailFormat {
    Jpeg,
    Png,
    Gif,
}

#[derive(Debug, PartialEq, Clone)]
pub enum ThumbnailSize {
    W16H16,
    W32H32,
    W64H64,
    Other(usize, usize),
}

#[derive(Debug, PartialEq, Clone)]
pub struct ThumbnailOptions {
    format: ThumbnailFormat,
    size: ThumbnailSize,
}

impl Default for ThumbnailOptions {
    fn default() -> ThumbnailOptions {
        ThumbnailOptions {
            format: ThumbnailFormat::Jpeg,
            size: ThumbnailSize::W64H64,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct GetCursorOptions {
    recursive: bool,
    include_media_info: bool,
    include_deleted: bool,
}

impl Default for GetCursorOptions {
    fn default() -> GetCursorOptions {
        GetCursorOptions {
            recursive: false,
            include_media_info: false,
            include_deleted: false,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct FolderListLongpoll {
    changes: bool,
    backoff: Option<bool>,
}

#[derive(Debug, PartialEq, Clone)]
pub struct ListRevisions {
    is_deleted: bool,
    entries: Vec<Metadata>,
}

#[derive(Debug, PartialEq, Clone)]
pub enum SearchMode {
    Filename,
    FilenameAndContent,
    DeletedFilename,
}

#[derive(Debug, PartialEq, Clone)]
pub struct SearchOptions {
    start: usize,
    max_results: usize,
    mode: SearchMode,
}

impl Default for SearchOptions {
    fn default() -> SearchOptions {
        SearchOptions {
            start: 0,
            max_results: 100,
            mode: SearchMode::Filename,
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum SearchMatchType {
    Filename(String),
    Content(String),
    Both(String),
}

#[derive(Debug, PartialEq, Clone)]
pub struct SearchMatch {
    match_type: SearchMatchType,
    metadata: Metadata,
}

#[derive(Debug, PartialEq, Clone)]
pub struct Search {
    matches: Vec<SearchMatch>,
    more: bool,
    start: usize,
}

#[derive(Debug, PartialEq, Clone)]
pub struct CommitInfo {
    path: String,
    mode: WriteMode,
    autorename: bool,
    client_modified: String,
    mute: bool,
}

#[derive(Debug, PartialEq, Clone)]
pub struct UploadSessionCursor {
    session_id: String,
    offset: usize,
}

// Functions

/// Copy a file
///
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let metadata = try!(files::copy_(&client, "/Path/to/existing/file", "/Path/to/new/file"));
/// ```
pub fn copy_<T>(client: &T, from: &str, to: &str) -> Result<Metadata>
                where T: DropboxClient
{
    let mut map = BTreeMap::new();
    map.insert("from_path".to_string(), json::Json::String(from.to_string()));
    map.insert("to_path".to_string(), json::Json::String(to.to_string()));
    let mut headers = BTreeMap::new();
    headers.insert("Content-Type".to_string(), "application/json".to_string());
    let resp = try!(client.api("files/copy", &mut headers, Some(&map)));
    json::decode(&resp.body).map_err(|e| ApiError::from(e))
}

/// Create a folder
///
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let metadata = try!(files::create_folder(&client, "/Path/to/new/folder"));
/// ```
pub fn create_folder<T>(client: &T, path: &str) -> Result<NewFolder>
                where T: DropboxClient
{
    let mut map = BTreeMap::new();
    map.insert("path".to_string(), json::Json::String(path.to_string()));
    let mut headers = BTreeMap::new();
    headers.insert("Content-Type".to_string(), "application/json".to_string());
    let resp = try!(client.api("files/create_folder", &mut headers, Some(map)));
    json::decode(&resp.body).map_err(|e| ApiError::from(e))
}

/// Delete a file or folder from the user's dropbox acconut
///
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let deleted = files::delete(&client, "/path/to/file/or/folder");
/// ```
/// TODO error handling
pub fn delete<T: DropboxClient>(client: &T, path: &str) -> Result<Metadata> {
    let mut map = BTreeMap::new();
    map.insert("path".to_string(), json::Json::String(path.to_string()));
    let mut headers = BTreeMap::new();
    headers.insert("Content-Type".to_string(), "application/json".to_string());
    let resp = try!(client.api("files/delete", &mut headers, Some(map)));
    json::decode(&resp.body).map_err(|e| ApiError::from(e))
}

/// Download a file
///
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let token = env::var("DROPBOX_TOKEN");
/// let client = Client::new(token);
/// let (metadata, response) = try!(files::download(&client, "/Path/to/file"));
/// ```
pub fn download<T: DropboxClient>(client: &T, path: &str) -> Result<(FileMetadata, Response)> {
    let mut map = BTreeMap::new();
    map.insert("path".to_string(), json::Json::String(path.to_string()));
    let mut headers = BTreeMap::new();
    headers.insert("Dropbox-API-Arg".to_string(), json::encode(&map).unwrap());
    let resp = try!(client.content("files/download", &mut headers, None::<&str>));
    let metadata: FileMetadata = match resp.api_result {
        Some(ref data) => {
            try!(json::decode(data))
        },
        None => return Err(ApiError::ClientError)
    };
    Ok((
        metadata,
        resp,
    ))
}

/// TODO implement
pub fn download_to_file<T>(client: &T, dest_path: &str, path: &str) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    Ok((
        Default::default(),
        Response {
            status: 200,
            api_result: None,
            body: "".to_string(),
        },
    ))
}

/// TODO implement
pub fn get_metadata<T>(client: &T, path: &str, include_media_info: bool) -> Result<Metadata>
                where T: DropboxClient
{
    Ok(Default::default())
}

/// TODO implement
pub fn get_preview<T>(client: &T, path: &str) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    Ok((
        Default::default(),
        Response {
            status: 200,
            api_result: None,
            body: "".to_string(),
        },
    ))
}

/// TODO implement
pub fn get_preview_to_file<T>(client: &T, dest_path: &str, path: &str) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    Ok((
        Default::default(),
        Response {
            status: 200,
            api_result: None,
            body: "".to_string(),
        },
    ))
}

pub fn get_thumbnail<T>(client: &T, path: &str) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    get_thumbnail_with_options(client, path, Default::default())
}

/// TODO implement
pub fn get_thumbnail_with_options<T>(client: &T, path: &str, options: ThumbnailOptions) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    Ok((
        Default::default(),
        Response {
            status: 200,
            api_result: None,
            body: "".to_string(),
        },
    ))
}

pub fn get_thumbnail_to_file<T>(client: &T, dest_path: &str, path: &str) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    get_thumbnail_to_file_with_options(client, dest_path, path, Default::default())
}

/// TODO implement
pub fn get_thumbnail_to_file_with_options<T>(client: &T, dest_path: &str, path: &str, options: ThumbnailOptions) -> Result<(Metadata, Response)>
                where T: DropboxClient
{
    Ok((
        Default::default(),
        Response {
            status: 200,
            api_result: None,
            body: "".to_string(),
        },
    ))
}

/// List the entries in a user's dropbox folder
///
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let folderlist = files::list_folder(&client, "/path/to/folder");
/// ```
/// TODO error handling
pub fn list_folder<T: DropboxClient>(client: &T, path: &str) -> Result<FolderList> {
    let mut map = BTreeMap::new();
    map.insert("path".to_string(), json::Json::String(path.to_string()));
    map.insert("recursive".to_string(), json::Json::Boolean(false));
    map.insert("include_media_info".to_string(), json::Json::Boolean(false));
    map.insert("include_deleted".to_string(), json::Json::Boolean(false));
    let mut headers = BTreeMap::new();
    headers.insert("Content-Type".to_string(), "application/json".to_string());
    let resp = try!(client.api("files/list_folder", &mut headers, Some(&map)));
    json::decode(&resp.body).map_err(ApiError::from)
}

/// TODO implement
pub fn list_folder_continue<T>(client: &T, cursor: &str) -> Result<FolderList>
                where T: DropboxClient
{
    Ok(Default::default())
}


pub fn list_folder_get_latest_cursor<T>(client: &T, path: &str) -> Result<String>
                where T: DropboxClient
{
    list_folder_get_latest_cursor_with_options(client, path, Default::default())
}

/// TODO implement
pub fn list_folder_get_latest_cursor_with_options<T>(client: &T, path: &str, options: GetCursorOptions) -> Result<String>
                where T: DropboxClient
{
    Ok("".to_string())
}

/// TODO implement
pub fn list_folder_longpoll<T>(client: &T, cursor: &str, timeout: usize) -> Result<FolderListLongpoll>
                where T: DropboxClient
{
    Ok(FolderListLongpoll {
        changes: false,
        backoff: None,
    })
}

/// TODO implement
pub fn list_revisions<T>(client: &T, path: &str, limit: usize) -> Result<ListRevisions>
                where T: DropboxClient
{
    Ok(ListRevisions {
        is_deleted: false,
        entries: vec![],
    })
}

/// TODO implement
pub fn move_<T>(client: &T, from: &str, to: &str) -> Result<Metadata>
                where T: DropboxClient
{
    Ok(Default::default())
}

/// TODO implement
pub fn permanently_delete<T>(client: &T, path: &str) -> Result<()>
                where T: DropboxClient
{
    Ok(())
}

/// TODO implement
pub fn restore<T>(client: &T, path: &str, rev: &str) -> Result<Metadata>
                where T: DropboxClient
{
    Ok(Default::default())
}

pub fn search<T>(client: &T, path: &str, query: &str) -> Result<Search>
                where T: DropboxClient
{
    search_with_options(client, path, query, Default::default())
}

/// TODO implement
pub fn search_with_options<T>(client: &T, path: &str, query: &str, options: SearchOptions) -> Result<Search>
                where T: DropboxClient
{
    Ok(Search {
        matches: vec![],
        more: false,
        start: 0,
    })
}

/// Upload a file to the user's dropbox acconut
/// 
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let metadata = try!(files::upload(&client, "file contents", "/path/to/file"));
/// ```
///
/// TODO error handling
pub fn upload<T>(client: &T, contents: &str, path: &str) -> Result<FileMetadata>
                where T: DropboxClient
{
    upload_with_options(client, contents, path, Default::default())
}

/// Upload a file to the user's dropbox acconut
/// 
/// # Example
///
/// ```ignore
/// use std::env;
/// use dbox::client::Client;
/// use dbox::files;
///
/// let client = Client::new(env::var("DROPBOX_TOKEN"));
/// let upload_options = UploadOptions { mode: WriteMode::Overwrite, autorename: true, mute: false };
/// let metadata = try!(files::upload_with_options(&client, "file contents", "/path/to/file", upload_options));
/// ```
///
/// TODO error handling
pub fn upload_with_options<T>(client: &T, contents: &str, path: &str, options: UploadOptions) -> Result<FileMetadata>
                where T: DropboxClient
{
    let mut map = BTreeMap::new();
    map.insert("path", json::Json::String(path.to_string()));
    map.insert("mode", json::Json::String(format!("{}", options.mode)));
    map.insert("autorename", json::Json::Boolean(options.autorename));
    map.insert("mute", json::Json::Boolean(options.mute));
    let mut headers = BTreeMap::new();
    headers.insert("Dropbox-API-Arg".to_string(), json::encode(&map).unwrap());
    headers.insert("Content-Type".to_string(), "application/octet-stream".to_string());
    let resp = try!(client.content("files/upload", &mut headers, Some(contents.to_owned())));
    json::decode(&resp.body).map_err(ApiError::from)
}

/// TODO implement
pub fn upload_session_append<T, U>(client: &T, f: U, session_id: &str, offset: usize) -> Result<()>
                where T: DropboxClient, U: io::Read
{
    Ok(())
}

/// TODO implement
pub fn upload_session_finish<T, U>(client: &T, f: U, cursor: &UploadSessionCursor, commit: &CommitInfo) -> Result<Metadata>
                where T: DropboxClient,
                      U: io::Read
{
    Ok(Default::default())
}

/// TODO implement
pub fn upload_session_start<T, U>(client: &T, f: U) -> Result<String>
                where T: DropboxClient,
                      U: io::Read
{
    Ok("".to_string())
}