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
use crate::{
    error::{Error, Result},
    resource::{DriveId, ErrorResponse, ItemId, OAuth2ErrorResponse},
};
use reqwest::{header, RequestBuilder, Response, StatusCode};
use serde::{de, Deserialize};
use url::PathSegmentsMut;

/// Specify the location of a `Drive` resource.
///
/// # See also
/// [`resource::Drive`][drive]
///
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0)
///
/// [drive]: ./resource/struct.Drive.html
#[derive(Clone, Debug)]
pub struct DriveLocation {
    inner: DriveLocationEnum,
}

#[derive(Clone, Debug)]
enum DriveLocationEnum {
    Me,
    User(String),
    Group(String),
    Site(String),
    Id(DriveId),
}

impl DriveLocation {
    /// Current user's OneDrive.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0#get-current-users-onedrive)
    #[must_use]
    pub fn me() -> Self {
        Self {
            inner: DriveLocationEnum::Me,
        }
    }

    /// OneDrive of a user.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0#get-a-users-onedrive)
    pub fn from_user(id_or_principal_name: impl Into<String>) -> Self {
        Self {
            inner: DriveLocationEnum::User(id_or_principal_name.into()),
        }
    }

    /// The document library associated with a group.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0#get-the-document-library-associated-with-a-group)
    pub fn from_group(group_id: impl Into<String>) -> Self {
        Self {
            inner: DriveLocationEnum::Group(group_id.into()),
        }
    }

    /// The document library for a site.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0#get-the-document-library-for-a-site)
    pub fn from_site(site_id: impl Into<String>) -> Self {
        Self {
            inner: DriveLocationEnum::Site(site_id.into()),
        }
    }

    /// A drive with ID specified.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0#get-a-drive-by-id)
    #[must_use]
    pub fn from_id(drive_id: DriveId) -> Self {
        Self {
            inner: DriveLocationEnum::Id(drive_id),
        }
    }
}

impl From<DriveId> for DriveLocation {
    fn from(id: DriveId) -> Self {
        Self::from_id(id)
    }
}

/// Reference to a `DriveItem` in a drive.
/// It does not contains the drive information.
///
/// # See also
/// [`resource::DriveItem`][drive_item]
///
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-get?view=graph-rest-1.0)
///
/// [drive_item]: ./resource/struct.DriveItem.html
// TODO: Now `DriveLocation` has only owned version, while `ItemLocation` has only borrowed version.
#[derive(Clone, Copy, Debug)]
pub struct ItemLocation<'a> {
    inner: ItemLocationEnum<'a>,
}

#[derive(Clone, Copy, Debug)]
enum ItemLocationEnum<'a> {
    Path(&'a str),
    Id(&'a str),
    // See example `GET last user to modify file foo.txt` from
    // https://docs.microsoft.com/en-us/graph/overview?view=graph-rest-1.0#popular-api-requests
    ChildOfId {
        parent_id: &'a str,
        child_name: &'a str,
    },
}

impl<'a> ItemLocation<'a> {
    /// A UNIX-like `/`-started absolute path to a file or directory in the drive.
    ///
    /// # Error
    /// If `path` contains invalid characters for OneDrive API, it returns None.
    ///
    /// # Note
    /// The trailing `/` is optional.
    ///
    /// Special name on Windows like `CON` or `NUL` is tested to be permitted in API,
    /// but may still cause errors on Windows or OneDrive Online.
    /// These names will pass the check, but STRONGLY NOT recommended.
    ///
    /// # See also
    /// [Microsoft Docs](https://support.office.com/en-us/article/Invalid-file-names-and-file-types-in-OneDrive-OneDrive-for-Business-and-SharePoint-64883a5d-228e-48f5-b3d2-eb39e07630fa#invalidcharacters)
    #[must_use]
    pub fn from_path(path: &'a str) -> Option<Self> {
        if path == "/" {
            Some(Self::root())
        } else if path.starts_with('/')
            && path[1..]
                .split_terminator('/')
                .all(|comp| !comp.is_empty() && FileName::new(comp).is_some())
        {
            Some(Self {
                inner: ItemLocationEnum::Path(path),
            })
        } else {
            None
        }
    }

    /// Item id from other API.
    #[must_use]
    pub fn from_id(item_id: &'a ItemId) -> Self {
        Self {
            inner: ItemLocationEnum::Id(item_id.as_str()),
        }
    }

    /// The root directory item.
    #[must_use]
    pub fn root() -> Self {
        Self {
            inner: ItemLocationEnum::Path("/"),
        }
    }

    /// The child item in a directory.
    #[must_use]
    pub fn child_of_id(parent_id: &'a ItemId, child_name: &'a FileName) -> Self {
        Self {
            inner: ItemLocationEnum::ChildOfId {
                parent_id: parent_id.as_str(),
                child_name: child_name.as_str(),
            },
        }
    }
}

impl<'a> From<&'a ItemId> for ItemLocation<'a> {
    fn from(id: &'a ItemId) -> Self {
        Self::from_id(id)
    }
}

/// An valid file name str (unsized).
#[derive(Debug)]
pub struct FileName(str);

impl FileName {
    /// Check and wrap the name for a file or a directory in OneDrive.
    ///
    /// Returns None if contains invalid characters.
    ///
    /// # See also
    /// [`ItemLocation::from_path`][from_path]
    ///
    /// [from_path]: ./struct.ItemLocation.html#method.from_path
    pub fn new<S: AsRef<str> + ?Sized>(name: &S) -> Option<&Self> {
        const INVALID_CHARS: &str = r#""*:<>?/\|"#;

        let name = name.as_ref();
        if !name.is_empty() && !name.contains(|c| INVALID_CHARS.contains(c)) {
            Some(unsafe { &*(name as *const str as *const Self) })
        } else {
            None
        }
    }

    /// View the file name as `&str`. It is cost-free.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for FileName {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

pub(crate) trait ApiPathComponent {
    fn extend_into(&self, buf: &mut PathSegmentsMut);
}

impl ApiPathComponent for DriveLocation {
    fn extend_into(&self, buf: &mut PathSegmentsMut) {
        match &self.inner {
            DriveLocationEnum::Me => buf.extend(&["me", "drive"]),
            DriveLocationEnum::User(id) => buf.extend(&["users", id, "drive"]),
            DriveLocationEnum::Group(id) => buf.extend(&["groups", id, "drive"]),
            DriveLocationEnum::Site(id) => buf.extend(&["sites", id, "drive"]),
            DriveLocationEnum::Id(id) => buf.extend(&["drives", id.as_str()]),
        };
    }
}

impl ApiPathComponent for ItemLocation<'_> {
    fn extend_into(&self, buf: &mut PathSegmentsMut) {
        match &self.inner {
            ItemLocationEnum::Path("/") => buf.push("root"),
            ItemLocationEnum::Path(path) => buf.push(&["root:", path, ":"].join("")),
            ItemLocationEnum::Id(id) => buf.extend(&["items", id]),
            ItemLocationEnum::ChildOfId {
                parent_id,
                child_name,
            } => buf.extend(&["items", parent_id, "children", child_name]),
        };
    }
}

impl ApiPathComponent for str {
    fn extend_into(&self, buf: &mut PathSegmentsMut) {
        buf.push(self);
    }
}

pub(crate) trait RequestBuilderTransformer {
    fn trans(self, req: RequestBuilder) -> RequestBuilder;
}

pub(crate) trait RequestBuilderExt: Sized {
    fn apply(self, trans: impl RequestBuilderTransformer) -> Self;
}

impl RequestBuilderExt for RequestBuilder {
    fn apply(self, trans: impl RequestBuilderTransformer) -> Self {
        trans.trans(self)
    }
}

type BoxFuture<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'static>>;

// TODO: Avoid boxing?
pub(crate) trait ResponseExt: Sized {
    fn parse<T: de::DeserializeOwned>(self) -> BoxFuture<Result<T>>;
    fn parse_optional<T: de::DeserializeOwned>(self) -> BoxFuture<Result<Option<T>>>;
    fn parse_no_content(self) -> BoxFuture<Result<()>>;
}

impl ResponseExt for Response {
    fn parse<T: de::DeserializeOwned>(self) -> BoxFuture<Result<T>> {
        Box::pin(async move { Ok(handle_error_response(self).await?.json().await?) })
    }

    fn parse_optional<T: de::DeserializeOwned>(self) -> BoxFuture<Result<Option<T>>> {
        Box::pin(async move {
            match self.status() {
                StatusCode::NOT_MODIFIED | StatusCode::ACCEPTED => Ok(None),
                _ => Ok(Some(handle_error_response(self).await?.json().await?)),
            }
        })
    }

    fn parse_no_content(self) -> BoxFuture<Result<()>> {
        Box::pin(async move {
            handle_error_response(self).await?;
            Ok(())
        })
    }
}

pub(crate) async fn handle_error_response(resp: Response) -> Result<Response> {
    #[derive(Deserialize)]
    struct Resp {
        error: ErrorResponse,
    }

    let status = resp.status();
    // `get_item_download_url_with_option` expects 302.
    if status.is_success() || status.is_redirection() {
        Ok(resp)
    } else {
        let retry_after = parse_retry_after_sec(&resp);
        let resp: Resp = resp.json().await?;
        Err(Error::from_error_response(status, resp.error, retry_after))
    }
}

pub(crate) async fn handle_oauth2_error_response(resp: Response) -> Result<Response> {
    let status = resp.status();
    if status.is_success() {
        Ok(resp)
    } else {
        let retry_after = parse_retry_after_sec(&resp);
        let resp: OAuth2ErrorResponse = resp.json().await?;
        Err(Error::from_oauth2_error_response(status, resp, retry_after))
    }
}

/// The documentation said it is in seconds:
/// <https://learn.microsoft.com/en-us/graph/throttling#best-practices-to-handle-throttling>.
/// And HTTP requires it to be a non-negative integer:
/// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After>.
fn parse_retry_after_sec(resp: &Response) -> Option<u32> {
    resp.headers()
        .get(header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .parse()
        .ok()
}