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
//! Resource Objects defined in the OneDrive API.
//!
//! # Field descriper
//!
//! Some structures have field descriper mods with singleton types representing
//! all controlable fields of it, which may be used
//! in [`onedrive_api::query_option`][query_option] to select or expand it using
//! `with_option` version API of [`DriveClient`][drive_client].
//!
//! ## Example
//! Here is an example to use [`resource::DriveItemField`][drive_item_field].
//! ```
//! use onedrive_api::{DriveClient, ItemLocation, query_option::ObjectOption};
//! use onedrive_api::resource::DriveItemField;
//!
//! // let client: DriveClient;
//! # fn run(client: &DriveClient) -> onedrive_api::Result<()> {
//! let item = client
//!     .get_item_with_option(
//!         ItemLocation::root(),
//!         None,
//!         // Only response `id` and `e_tag` to reduce data transmission.
//!         ObjectOption::new()
//!             .select(&[&DriveItemField::id, &DriveItemField::e_tag]),
//!     )?;
//!
//! Ok(())
//! # }
//! ```
//!
//!
//! # See also
//! [Microsoft Docs](https://docs.microsoft.com/en-us/onedrive/developer/rest-api/resources/?view=odsp-graph-online)
//!
//! [query_option]: ../query_option/index.html
//! [drive_client]: ../struct.DriveClient.html
//! [drive_item_field]: ./DriveItemField/index.html
use serde::{Deserialize, Serialize};

/// A semantic alias for URL string in resource objects.
pub type Url = String;

/// A semantic alias for file size in resource objects.
pub type FileSize = u64;

macro_rules! define_string_wrapper {
    ($($(#[$meta:meta])* $vis:vis $name:ident;)*) => { $(
        $(#[$meta])*
        #[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
        $vis struct $name(String);

        impl $name {
            /// Wrap a string.
            ///
            /// Simply wrap without checking.
            pub fn new(id: String) -> Self {
                $name(id)
            }

            /// View as str.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                self.as_str()
            }
        }
    )* };
}

define_string_wrapper! {
    /// The unique identifier to a `Drive`.
    pub DriveId;

    /// The unique identifier for a `DriveItem`.
    pub ItemId;

    /// An tag representing the state of an item.
    ///
    /// Used for avoid data transmission when a resource is not modified.
    ///
    /// The tag from `DriveItem::c_tag` (TODO) is for the content of the item,
    /// while the one from [`DriveItem::e_tag`][e_tag] is for the entire item (metadata + content).
    ///
    /// [e_tag]: ./struct.DriveItem.html#structfield.e_tag
    pub Tag;
}

#[doc(hidden)]
pub trait ResourceFieldOf<T> {
    fn api_field_name(&self) -> String;
}

// Separate `type` to enable making `ResoucrFieldOf` into trait object.
#[doc(hidden)]
pub trait ResourceFieldTypeOf<T>: ResourceFieldOf<T> {
    type Type;
}

macro_rules! define_resource_object {
    ($(
        $(#[$meta:meta])*
        $vis:vis struct $struct_name:ident $(#$field_mod_name:ident)? {
            $(
                $(#[$field_meta:meta])*
                $([unselectable $($unselectable_mark:ident)?])?
                pub $field_name:ident $(@$field_rename:literal)?: Option<$field_ty:ty>,
            )*
        }
    )*) => {
        $(
            $(#[$meta])*
            #[derive(Deserialize)]
            #[serde(rename_all = "camelCase")]
            $vis struct $struct_name {
                $(
                    #[allow(missing_docs)]
                    $(#[$field_meta])*
                    $(#[serde(rename = $field_rename)])?
                    pub $field_name: Option<$field_ty>,
                )*
                #[serde(default)]
                _private: (),
            }

            define_resource_object! { __impl_struct($struct_name $($field_mod_name)?) [
                $({
                    [$(unselectable $($unselectable_mark)?)?]
                    [$($field_meta)*]
                    $field_name
                    ($($field_rename)?)
                    ($field_ty)
                })*
            ] }
        )*
    };
    (__impl_struct($struct_name:ident) $tt:tt) => {}; // No field mod.
    (__impl_struct($struct_name:ident $field_mod_name:ident) [$({
        [$($unselectable:ident)?]
        [$($meta:meta)*]
        $field:ident
        ($($rename:literal)?)
        ($ty:ty)
    })*]) => {
        /// Fields descriptors.
        ///
        /// More details in [mod documentation][mod].
        ///
        /// [mod]: ../index.html
        #[allow(non_snake_case)]
        pub mod $field_mod_name {
            $(
                define_resource_object! { __impl_if_empty($($unselectable)?) {
                    /// Field descriptor.
                    ///
                    /// More details in [mod documentation][mod].
                    ///
                    /// [mod]: ../index.html
                    #[allow(non_camel_case_types)]
                    pub struct $field;

                    impl ::std::fmt::Debug for $field {
                        fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                            f.debug_struct(
                                concat!(stringify!($field_mod_name), "::", stringify!($field)),
                            ).finish()
                        }
                    }
                } }
            )*
        }

        $(
            define_resource_object! { __impl_if_empty($($unselectable)?) {
                impl ResourceFieldOf<$struct_name> for $field_mod_name::$field {
                    #[inline]
                    fn api_field_name(&self) -> String {
                        snake_to_camel_case(stringify!($field))
                        $(; $rename)? // Replace
                    }
                }

                impl ResourceFieldTypeOf<$struct_name> for $field_mod_name::$field {
                    type Type = $ty;
                }
            } }
        )*
    };
    (__impl_if_empty() { $($tt:tt)* }) => { $($tt)* };
    (__impl_if_empty($sth:tt) $tt:tt) => {};
}

define_resource_object! {
    /// Drive resource type
    ///
    /// The drive resource is the top level object representing a user's OneDrive
    /// or a document library in SharePoint.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/resources/drive?view=graph-rest-1.0)
    #[derive(Debug)]
    pub struct Drive #DriveField {
        // TODO: Incomplete
        pub id: Option<DriveId>,
        // created_by: IdentitySet,
        // created_date_time: Timestamp,
        pub description: Option<String>,
        // drive_type: DriveType,
        pub items: Option<Vec<DriveItem>>,
        // last_modified_by: IdeneitySet,
        // last_modified_date_time: Timestamp,
        pub name: Option<String>,
        // owner: IdentitySet,
        // quota: Quota,
        // root: DriveItem,
        // sharepoint_ids: SharepointIds,
        pub special: Option<DriveItem>,
        // system: SystemFacet,
        pub web_url: Option<Url>,
    }

    /// DriveItem resource type
    ///
    /// The `DriveItem` resource represents a file, folder, or other item stored in a drive.
    /// All file system objects in OneDrive and SharePoint are returned as `DriveItem` resources.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/resources/driveitem?view=graph-rest-1.0)
    #[derive(Debug)]
    pub struct DriveItem #DriveItemField {
        // TODO: Incomplete
        // Type specified fields

        // audio: Audio,
        // content: Stream,
        // file: File,
        // folder: Folder,
        // image: Image,
        // location: Option<GeoCoordinations>,
        // malware: Option<Malware>,
        // package: Package,
        // photo: Photo,
        // root: Root,
        // special_folder: SpecialFolder,
        // video: Video,

        // Drive item
        // c_tag: Option<Tag>,
        pub deleted: Option<Deleted>,
        pub description: Option<String>,
        // pub file_system_info: FileSystemInfo,
        // publication: Option<PublicationFacet>,
        // remote_item: Option<RemoteItem>,
        // search_result: Option<SearchResult>,
        // shared: Shared,
        // sharepoint_ids: SharepointIds,
        pub size: Option<FileSize>,
        // web_dav_url: Url,

        // Relationships

        // activities: Vec<ItemActivity>,
        pub children: Option<Vec<DriveItem>>,
        // permissions: Vec<Permission>,
        // thumbnails: Vec<ThumbnailSet>,
        // versions: Vec<DriveItemVersion>,

        // Base item
        pub id: Option<ItemId>,
        // created_by: IdentitySet,
        // created_date_time: Timestamp,
        pub e_tag: Option<Tag>,
        // last_modified_by: IdentitySet,
        // last_modified_date_time: Timestamp,
        pub name: Option<String>,
        pub parent_reference: Option<ItemReference>,
        pub web_url: Option<Url>,

        // Instance annotations
        [unselectable]
        pub download_url @"@microsoft.graph.downloadUrl": Option<Url>,
    }

    /// Deleted facet
    ///
    /// The `Deleted` resource indicates that the item has been deleted.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/resources/deleted?view=graph-rest-1.0)
    #[derive(Debug, Serialize)]
    pub struct Deleted {
        pub state: Option<String>,
    }

    /// ItemReference resource type
    ///
    /// The `ItemReference` resource provides information necessary to address a `DriveItem` via the API.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/resources/itemreference?view=graph-rest-1.0)
    #[derive(Debug, Serialize)]
    pub struct ItemReference {
        pub drive_id: Option<DriveId>,
        // drive_type: DriveType,
        pub id: Option<ItemId>,
        // list_id: String,
        pub name: Option<String>,
        pub path: Option<String>,
        // shared_id: String,
        // sharepoint_ids: SharepointIds,
        // site_id: String,
    }
}

#[inline]
fn snake_to_camel_case(s: &str) -> String {
    let mut buf = String::new();
    let mut is_u = false;
    for c in s.chars() {
        if c == '_' {
            is_u = true;
        } else if is_u {
            is_u = false;
            buf.push(c.to_ascii_uppercase());
        } else {
            buf.push(c);
        }
    }
    buf
}

/// The error object with description and details of the error responsed from server.
///
/// It may be contained in [`onedrive_api::Error`][error] which may
/// be returned when processing requests.
///
/// # See also
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/errors#error-resource-type)
///
/// [error]: ../struct.Error.html
#[allow(missing_docs)]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorObject {
    pub code: Option<String>,
    pub message: Option<String>,
    pub inner_error: Option<Box<ErrorObject>>,
    #[serde(flatten)]
    pub extra_data: serde_json::Map<String, serde_json::Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_snake_to_camel_case() {
        let data = [
            ("abc", "abc"),
            ("hello_world", "helloWorld"),
            ("wh_tst_ef_ck", "whTstEfCk"),
        ];
        for (i, o) in &data {
            assert_eq!(snake_to_camel_case(i), *o);
        }
    }
}