onedrive-api 0.10.2

OneDrive HTTP REST API
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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
#![allow(clippy::default_trait_access)] // Forwarding default options is allowed.
use crate::{
    error::{Error, Result},
    option::{CollectionOption, DriveItemPutOption, ObjectOption},
    resource::{Drive, DriveField, DriveItem, DriveItemField, TimestampString},
    util::{
        handle_error_response, ApiPathComponent, DriveLocation, FileName, ItemLocation,
        RequestBuilderExt as _, ResponseExt as _,
    },
    {ConflictBehavior, ExpectRange},
};
use bytes::Bytes;
use reqwest::{header, Client};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
use url::Url;

macro_rules! api_url {
    ($($seg:expr),* $(,)?) => {{
        let mut url = Url::parse("https://graph.microsoft.com/v1.0").unwrap();
        {
            let mut buf = url.path_segments_mut().unwrap();
            $(ApiPathComponent::extend_into($seg, &mut buf);)*
        } // End borrowing of `url`
        url
    }};
}

/// TODO: More efficient impl.
macro_rules! api_path {
    ($item:expr) => {{
        let mut url = Url::parse("path:///drive").unwrap();
        let item: &ItemLocation = $item;
        ApiPathComponent::extend_into(item, &mut url.path_segments_mut().unwrap());
        url
    }
    .path()};
}

/// The authorized client to access OneDrive resources in a specified Drive.
#[derive(Clone)]
pub struct OneDrive {
    client: Client,
    token: String,
    drive: DriveLocation,
}

impl fmt::Debug for OneDrive {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OneDrive")
            .field("client", &self.client)
            // Skip `token`.
            .field("drive", &self.drive)
            .finish_non_exhaustive()
    }
}

impl OneDrive {
    /// Create a new OneDrive instance with access token given to perform operations in a Drive.
    ///
    /// # Panics
    /// It panics if the underlying `reqwest::Client` cannot be created.
    pub fn new(access_token: impl Into<String>, drive: impl Into<DriveLocation>) -> Self {
        let client = Client::builder()
            .redirect(reqwest::redirect::Policy::none())
            .gzip(true)
            .build()
            .unwrap();
        Self::new_with_client(client, access_token, drive.into())
    }

    /// Same as [`OneDrive::new`] but with custom `reqwest::Client`.
    ///
    /// # Note
    /// The given `client` should have redirection disabled to
    /// make [`get_item_download_url[_with_option]`][get_url] work properly.
    /// See also the docs of [`get_item_download_url[_with_option]`][get_url].
    ///
    /// [`OneDrive::new`]: #method.new
    /// [get_url]: #method.get_item_download_url_with_option
    pub fn new_with_client(
        client: Client,
        access_token: impl Into<String>,
        drive: impl Into<DriveLocation>,
    ) -> Self {
        OneDrive {
            client,
            token: access_token.into(),
            drive: drive.into(),
        }
    }

    /// Get the `reqwest::Client` used to create the OneDrive instance.
    #[must_use]
    pub fn client(&self) -> &Client {
        &self.client
    }

    /// Get the access token used to create the OneDrive instance.
    #[must_use]
    pub fn access_token(&self) -> &str {
        &self.token
    }

    /// Get current `Drive`.
    ///
    /// Retrieve the properties and relationships of a [`resource::Drive`][drive] resource.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0)
    ///
    /// [drive]: ./resource/struct.Drive.html
    pub async fn get_drive_with_option(&self, option: ObjectOption<DriveField>) -> Result<Drive> {
        self.client
            .get(api_url![&self.drive])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse()
            .await
    }

    /// Shortcut to `get_drive_with_option` with default parameters.
    ///
    /// # See also
    /// [`get_drive_with_option`][with_opt]
    ///
    /// [with_opt]: #method.get_drive_with_option
    pub async fn get_drive(&self) -> Result<Drive> {
        self.get_drive_with_option(Default::default()).await
    }

    /// List children of a `DriveItem`.
    ///
    /// Retrieve a collection of [`resource::DriveItem`][drive_item]s in the children relationship
    /// of the given one.
    ///
    /// # Response
    /// If successful, respond a fetcher for fetching changes from initial state (empty) to the snapshot of
    /// current states. See [`ListChildrenFetcher`][fetcher] for more details.
    ///
    /// If [`if_none_match`][if_none_match] is set and it matches the item tag, return an `None`.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-list-children?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [if_none_match]: ./option/struct.CollectionOption.html#method.if_none_match
    /// [fetcher]: ./struct.ListChildrenFetcher.html
    pub async fn list_children_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        option: CollectionOption<DriveItemField>,
    ) -> Result<Option<ListChildrenFetcher>> {
        let opt_resp = self
            .client
            .get(api_url![&self.drive, &item.into(), "children"])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse_optional()
            .await?;

        Ok(opt_resp.map(ListChildrenFetcher::new))
    }

    /// Shortcut to `list_children_with_option` with default params,
    /// and fetch and collect all children.
    ///
    /// # See also
    /// [`list_children_with_option`][with_opt]
    ///
    /// [with_opt]: #method.list_children_with_option
    pub async fn list_children<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
    ) -> Result<Vec<DriveItem>> {
        self.list_children_with_option(item, Default::default())
            .await?
            .ok_or_else(|| Error::unexpected_response("Unexpected empty response"))?
            .fetch_all(self)
            .await
    }

    /// Get a `DriveItem` resource.
    ///
    /// Retrieve the metadata for a [`resource::DriveItem`][drive_item] by file system path or ID.
    ///
    /// # Errors
    /// Will return `Ok(None)` if [`if_none_match`][if_none_match] is set and it matches the item tag.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-get?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [if_none_match]: ./option/struct.CollectionOption.html#method.if_none_match
    pub async fn get_item_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        option: ObjectOption<DriveItemField>,
    ) -> Result<Option<DriveItem>> {
        self.client
            .get(api_url![&self.drive, &item.into()])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse_optional()
            .await
    }

    /// Shortcut to `get_item_with_option` with default parameters.
    ///
    /// # See also
    /// [`get_item_with_option`][with_opt]
    ///
    /// [with_opt]: #method.get_item_with_option
    pub async fn get_item<'a>(&self, item: impl Into<ItemLocation<'a>>) -> Result<DriveItem> {
        self.get_item_with_option(item, Default::default())
            .await?
            .ok_or_else(|| Error::unexpected_response("Unexpected empty response"))
    }

    /// Get a pre-authorized download URL for a file.
    ///
    /// The URL returned is only valid for a short period of time (a few minutes).
    ///
    /// # Note
    /// This API only works with reqwest redirection disabled, which is the default option set by
    /// [`OneDrive::new()`][new].
    /// If the `OneDrive` instance is created by [`new_with_client()`][new_with_client],
    /// be sure the `reqwest::Client` has redirection disabled.
    ///
    /// Only `If-None-Match` is supported in `option`.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-get-content?view=graph-rest-1.0&tabs=http)
    ///
    /// [new]: #method.new
    /// [new_with_client]: #method.new_with_client
    pub async fn get_item_download_url_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        option: ObjectOption<DriveItemField>,
    ) -> Result<String> {
        let raw_resp = self
            .client
            .get(api_url![&self.drive, &item.into(), "content"])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?;
        let url = handle_error_response(raw_resp)
            .await?
            .headers()
            .get(header::LOCATION)
            .ok_or_else(|| {
                Error::unexpected_response(
                    "Header `Location` not exists in response of `get_item_download_url`",
                )
            })?
            .to_str()
            .map_err(|_| Error::unexpected_response("Invalid string header `Location`"))?
            .to_owned();
        Ok(url)
    }

    /// Shortcut to [`get_item_download_url_with_option`] with default options.
    ///
    /// # See also
    /// [`get_item_download_url_with_option`]
    ///
    /// [`get_item_download_url_with_option`]: #method.get_item_downloda_url_with_option
    pub async fn get_item_download_url<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
    ) -> Result<String> {
        self.get_item_download_url_with_option(item.into(), Default::default())
            .await
    }

    /// Create a new [`DriveItem`][drive_item] allowing to set supported attributes.
    /// [`DriveItem`][drive_item] resources have facets modeled as properties that provide data
    /// about the [`DriveItem`][drive_item]'s identities and capabilities. You must provide one
    /// of the following facets to create an item: `bundle`, `file`, `folder`, `remote_item`.
    ///
    /// # Errors
    /// * Will result in `Err` with HTTP `409 CONFLICT` if [`conflict_behavior`][conflict_behavior]
    ///   is set to [`Fail`][conflict_fail] and the target already exists.
    /// * Will result in `Err` with HTTP `400 BAD REQUEST` if facets are not properly set.
    ///
    /// # See also
    ///
    /// [Microsoft Docs](https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_post_children?view=graph-rest-1.0)
    ///
    /// [with_opt]: #method.create_folder_with_option
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [conflict_behavior]: ./option/struct.DriveItemPutOption.html#method.conflict_behavior
    /// [conflict_fail]: ./enum.ConflictBehavior.html#variant.Fail
    pub async fn create_drive_item<'a>(
        &self,
        parent_item: impl Into<ItemLocation<'a>>,
        drive_item: DriveItem,
        option: DriveItemPutOption,
    ) -> Result<DriveItem> {
        #[derive(Serialize)]
        struct Req {
            #[serde(rename = "@microsoft.graph.conflictBehavior")]
            conflict_behavior: ConflictBehavior,
            #[serde(flatten)]
            drive_item: DriveItem,
        }

        let conflict_behavior = option
            .get_conflict_behavior()
            .unwrap_or(ConflictBehavior::Fail);

        self.client
            .post(api_url![&self.drive, &parent_item.into(), "children"])
            .bearer_auth(&self.token)
            .apply(option)
            .json(&Req {
                conflict_behavior,
                drive_item,
            })
            .send()
            .await?
            .parse()
            .await
    }

    /// Create a new folder under an `DriveItem`
    ///
    /// Create a new folder [`DriveItem`][drive_item] with a specified parent item or path.
    ///
    /// # Errors
    /// Will result in `Err` with HTTP `409 CONFLICT` if [`conflict_behavior`][conflict_behavior]
    /// is set to [`Fail`][conflict_fail] and the target already exists.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-post-children?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [conflict_behavior]: ./option/struct.DriveItemPutOption.html#method.conflict_behavior
    /// [conflict_fail]: ./enum.ConflictBehavior.html#variant.Fail
    pub async fn create_folder_with_option<'a>(
        &self,
        parent_item: impl Into<ItemLocation<'a>>,
        name: &FileName,
        option: DriveItemPutOption,
    ) -> Result<DriveItem> {
        let drive_item = DriveItem {
            name: Some(name.as_str().to_string()),
            folder: Some(json!({}).into()),
            ..Default::default()
        };

        self.create_drive_item(parent_item, drive_item, option)
            .await
    }

    /// Shortcut to `create_folder_with_option` with default options.
    ///
    /// # See also
    /// [`create_folder_with_option`][with_opt]
    ///
    /// [with_opt]: #method.create_folder_with_option
    pub async fn create_folder<'a>(
        &self,
        parent_item: impl Into<ItemLocation<'a>>,
        name: &FileName,
    ) -> Result<DriveItem> {
        self.create_folder_with_option(parent_item, name, Default::default())
            .await
    }

    /// Update `DriveItem` properties
    ///
    /// Update the metadata for a [`DriveItem`][drive_item].
    ///
    /// If you want to rename or move an [`DriveItem`][drive_item] to another place,
    /// you should use [`move_`][move_] (or [`move_with_option`][move_with_opt]) instead of this, which is a wrapper
    /// to this API endpoint to make things easier.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-update?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [move_]: #method.move_
    /// [move_with_opt]: #method.move_with_option
    pub async fn update_item_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        patch: &DriveItem,
        option: ObjectOption<DriveItemField>,
    ) -> Result<DriveItem> {
        self.client
            .patch(api_url![&self.drive, &item.into()])
            .bearer_auth(&self.token)
            .apply(option)
            .json(patch)
            .send()
            .await?
            .parse()
            .await
    }

    /// Shortcut to `update_item_with_option` with default options.
    ///
    /// # See also
    /// [`update_item_with_option`][with_opt]
    ///
    /// [with_opt]: #method.update_item_with_option
    pub async fn update_item<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        patch: &DriveItem,
    ) -> Result<DriveItem> {
        self.update_item_with_option(item, patch, Default::default())
            .await
    }

    /// The upload size limit of [`upload_small`].
    ///
    /// The value is from
    /// [OneDrive Developer documentation](https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online)
    /// (4MB) which is smaller than
    /// [Microsoft Graph documentation](https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0)
    /// (250MB).
    /// The exact limit is unknown. Here we chose the smaller one as a reference.
    ///
    /// [`upload_small`]: #method.upload_small
    pub const UPLOAD_SMALL_MAX_SIZE: usize = 4_000_000; // 4 MB

    /// Upload or replace the contents of a `DriveItem` file.
    ///
    /// The simple upload API allows you to provide the contents of a new file or
    /// update the contents of an existing file in a single API call. This method
    /// only supports files up to [`Self::UPLOAD_SMALL_MAX_SIZE`]. The length is not checked
    /// locally and request will still be sent for large data.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    pub async fn upload_small<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        data: impl Into<Bytes>,
    ) -> Result<DriveItem> {
        let data = data.into();
        self.client
            .put(api_url![&self.drive, &item.into(), "content"])
            .bearer_auth(&self.token)
            .header(header::CONTENT_TYPE, "application/octet-stream")
            .header(header::CONTENT_LENGTH, data.len().to_string())
            .body(data)
            .send()
            .await?
            .parse()
            .await
    }

    /// Create an upload session.
    ///
    /// Create an upload session to allow your app to upload files up to
    /// the maximum file size. An upload session allows your app to
    /// upload ranges of the file in sequential API requests, which allows
    /// the transfer to be resumed if a connection is dropped
    /// while the upload is in progress.
    ///
    /// # Errors
    /// Will return `Err` with HTTP `412 PRECONDITION_FAILED` if [`if_match`][if_match] is set
    /// but does not match the item.
    ///
    /// # Note
    /// [`conflict_behavior`][conflict_behavior] is supported.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#create-an-upload-session)
    ///
    /// [if_match]: ./option/struct.CollectionOption.html#method.if_match
    /// [conflict_behavior]: ./option/struct.DriveItemPutOption.html#method.conflict_behavior
    /// [upload_sess]: ./struct.UploadSession.html
    /// [upload_part]: ./struct.UploadSession.html#method.upload_part
    pub async fn new_upload_session_with_initial_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        initial: &DriveItem,
        option: DriveItemPutOption,
    ) -> Result<(UploadSession, UploadSessionMeta)> {
        #[derive(Serialize)]
        struct Item<'a> {
            #[serde(rename = "@microsoft.graph.conflictBehavior")]
            conflict_behavior: ConflictBehavior,
            #[serde(flatten)]
            initial: &'a DriveItem,
        }

        #[derive(Serialize)]
        struct Req<'a> {
            item: Item<'a>,
        }

        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Resp {
            upload_url: String,
            #[serde(flatten)]
            meta: UploadSessionMeta,
        }

        let conflict_behavior = option
            .get_conflict_behavior()
            .unwrap_or(ConflictBehavior::Fail);
        let resp: Resp = self
            .client
            .post(api_url![&self.drive, &item.into(), "createUploadSession"])
            .apply(option)
            .bearer_auth(&self.token)
            .json(&Req {
                item: Item {
                    conflict_behavior,
                    initial,
                },
            })
            .send()
            .await?
            .parse()
            .await?;

        Ok((
            UploadSession {
                upload_url: resp.upload_url,
            },
            resp.meta,
        ))
    }

    /// Shortcut to [`new_upload_session_with_initial_option`] without initial attributes.
    ///
    /// [`new_upload_session_with_initial_option`]: #method.new_upload_session_with_initial_option
    pub async fn new_upload_session_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        option: DriveItemPutOption,
    ) -> Result<(UploadSession, UploadSessionMeta)> {
        let initial = DriveItem::default();
        self.new_upload_session_with_initial_option(item, &initial, option)
            .await
    }

    /// Shortcut to [`new_upload_session_with_option`] with `ConflictBehavior::Fail`.
    ///
    /// [`new_upload_session_with_option`]: #method.new_upload_session_with_option
    pub async fn new_upload_session<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
    ) -> Result<(UploadSession, UploadSessionMeta)> {
        self.new_upload_session_with_option(item, Default::default())
            .await
    }

    /// Copy a `DriveItem`.
    ///
    /// Asynchronously creates a copy of an driveItem (including any children),
    /// under a new parent item or with a new name.
    ///
    /// # Note
    /// The conflict behavior is not mentioned in Microsoft Docs, and cannot be specified.
    ///
    /// But it seems to behave as [`Rename`][conflict_rename] if the destination folder is just the current
    /// parent folder, and [`Fail`][conflict_fail] otherwise.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-copy?view=graph-rest-1.0)
    ///
    /// [conflict_rename]: ./enum.ConflictBehavior.html#variant.Rename
    /// [conflict_fail]: ./enum.ConflictBehavior.html#variant.Fail
    pub async fn copy<'a, 'b>(
        &self,
        source_item: impl Into<ItemLocation<'a>>,
        dest_folder: impl Into<ItemLocation<'b>>,
        dest_name: &FileName,
    ) -> Result<CopyProgressMonitor> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Req<'a> {
            parent_reference: ItemReference<'a>,
            name: &'a str,
        }

        let raw_resp = self
            .client
            .post(api_url![&self.drive, &source_item.into(), "copy"])
            .bearer_auth(&self.token)
            .json(&Req {
                parent_reference: ItemReference {
                    path: api_path!(&dest_folder.into()),
                },
                name: dest_name.as_str(),
            })
            .send()
            .await?;

        let url = handle_error_response(raw_resp)
            .await?
            .headers()
            .get(header::LOCATION)
            .ok_or_else(|| {
                Error::unexpected_response("Header `Location` not exists in response of `copy`")
            })?
            .to_str()
            .map_err(|_| Error::unexpected_response("Invalid string header `Location`"))?
            .to_owned();

        Ok(CopyProgressMonitor::from_monitor_url(url))
    }

    /// Move a `DriveItem` to a new folder.
    ///
    /// This is a special case of the Update method. Your app can combine
    /// moving an item to a new container and updating other properties of
    /// the item into a single request.
    ///
    /// Note: Items cannot be moved between Drives using this request.
    ///
    /// # Note
    /// [`conflict_behavior`][conflict_behavior] is supported.
    ///
    /// # Errors
    /// Will return `Err` with HTTP `412 PRECONDITION_FAILED` if [`if_match`][if_match] is set
    /// but it does not match the item.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0)
    ///
    /// [conflict_behavior]: ./option/struct.DriveItemPutOption.html#method.conflict_behavior
    /// [if_match]: ./option/struct.CollectionOption.html#method.if_match
    pub async fn move_with_option<'a, 'b>(
        &self,
        source_item: impl Into<ItemLocation<'a>>,
        dest_folder: impl Into<ItemLocation<'b>>,
        dest_name: Option<&FileName>,
        option: DriveItemPutOption,
    ) -> Result<DriveItem> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Req<'a> {
            parent_reference: ItemReference<'a>,
            name: Option<&'a str>,
            #[serde(rename = "@microsoft.graph.conflictBehavior")]
            conflict_behavior: ConflictBehavior,
        }

        let conflict_behavior = option
            .get_conflict_behavior()
            .unwrap_or(ConflictBehavior::Fail);
        self.client
            .patch(api_url![&self.drive, &source_item.into()])
            .bearer_auth(&self.token)
            .apply(option)
            .json(&Req {
                parent_reference: ItemReference {
                    path: api_path!(&dest_folder.into()),
                },
                name: dest_name.map(FileName::as_str),
                conflict_behavior,
            })
            .send()
            .await?
            .parse()
            .await
    }

    /// Shortcut to `move_with_option` with `ConflictBehavior::Fail`.
    ///
    /// # See also
    /// [`move_with_option`][with_opt]
    ///
    /// [with_opt]: #method.move_with_option
    pub async fn move_<'a, 'b>(
        &self,
        source_item: impl Into<ItemLocation<'a>>,
        dest_folder: impl Into<ItemLocation<'b>>,
        dest_name: Option<&FileName>,
    ) -> Result<DriveItem> {
        self.move_with_option(source_item, dest_folder, dest_name, Default::default())
            .await
    }

    /// Delete a `DriveItem`.
    ///
    /// Delete a [`DriveItem`][drive_item] by using its ID or path. Note that deleting items using
    /// this method will move the items to the recycle bin instead of permanently
    /// deleting the item.
    ///
    /// # Error
    /// Will result in error with HTTP `412 PRECONDITION_FAILED` if [`if_match`][if_match] is set but
    /// does not match the item.
    ///
    /// # Panics
    /// [`conflict_behavior`][conflict_behavior] is **NOT** supported. Set it will cause a panic.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delete?view=graph-rest-1.0)
    ///
    /// [drive_item]: ./resource/struct.DriveItem.html
    /// [if_match]: ./option/struct.CollectionOption.html#method.if_match
    /// [conflict_behavior]: ./option/struct.DriveItemPutOption.html#method.conflict_behavior
    pub async fn delete_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        option: DriveItemPutOption,
    ) -> Result<()> {
        assert!(
            option.get_conflict_behavior().is_none(),
            "`conflict_behavior` is not supported by `delete[_with_option]`",
        );

        self.client
            .delete(api_url![&self.drive, &item.into()])
            .bearer_auth(&self.token)
            .apply(option)
            .send()
            .await?
            .parse_no_content()
            .await
    }

    /// Shortcut to `delete_with_option`.
    ///
    /// # See also
    /// [`delete_with_option`][with_opt]
    ///
    /// [with_opt]: #method.delete_with_option
    pub async fn delete<'a>(&self, item: impl Into<ItemLocation<'a>>) -> Result<()> {
        self.delete_with_option(item, Default::default()).await
    }

    /// Track changes for root folder from initial state (empty state) to snapshot of current states.
    ///
    /// This method allows your app to track changes to a drive and its children over time.
    /// Deleted items are returned with the deleted facet. Items with this property set
    /// should be removed from your local state.
    ///
    /// Note: you should only delete a folder locally if it is empty after
    /// syncing all the changes.
    ///
    /// # Panics
    /// Track Changes API does not support [`$count=true` query parameter][dollar_count].
    /// If [`CollectionOption::get_count`][opt_get_count] is set in option, it will panic.
    ///
    /// # Results
    /// Return a fetcher for fetching changes from initial state (empty) to the snapshot of
    /// current states. See [`TrackChangeFetcher`][fetcher] for more details.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0)
    ///
    /// [fetcher]: ./struct.TrackChangeFetcher.html
    /// [dollar_count]: https://docs.microsoft.com/en-us/graph/query-parameters#count-parameter
    /// [opt_get_count]: ./option/struct.CollectionOption.html#method.get_count
    pub async fn track_root_changes_from_initial_with_option(
        &self,
        option: CollectionOption<DriveItemField>,
    ) -> Result<TrackChangeFetcher> {
        assert!(
            !option.has_get_count(),
            "`get_count` is not supported by Track Changes API",
        );
        let resp = self
            .client
            .get(api_url![&self.drive, "root", "delta"])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse()
            .await?;
        Ok(TrackChangeFetcher::new(resp))
    }

    /// Shortcut to `track_root_changes_from_initial_with_option` with default parameters.
    ///
    /// # See also
    /// [`track_root_changes_from_initial_with_option`][with_opt]
    ///
    /// [with_opt]: #method.track_root_changes_from_initial_with_option
    pub async fn track_root_changes_from_initial(&self) -> Result<TrackChangeFetcher> {
        self.track_root_changes_from_initial_with_option(Default::default())
            .await
    }

    /// Track changes for root folder from snapshot (delta url) to snapshot of current states.
    ///
    /// # Note
    /// There is no `with_option` version of this function. Since delta URL already carries
    /// query parameters when you get it. The initial parameters will be automatically used
    /// in all following requests through delta URL.
    pub async fn track_root_changes_from_delta_url(
        &self,
        delta_url: &str,
    ) -> Result<TrackChangeFetcher> {
        let resp: DriveItemCollectionResponse = self
            .client
            .get(delta_url)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse()
            .await?;
        Ok(TrackChangeFetcher::new(resp))
    }

    /// Get a delta url representing the snapshot of current states of root folder.
    ///
    /// The delta url can be used in [`track_root_changes_from_delta_url`][track_from_delta] later
    /// to get diffs between two snapshots of states.
    ///
    /// Note that options (query parameters) are saved in delta url, so they are applied to all later
    /// requests by `track_changes_from_delta_url` without need for specifying them every time.
    ///
    /// # Panics
    /// Track Changes API does not support [`$count=true` query parameter][dollar_count].
    /// If [`CollectionOption::get_count`][opt_get_count] is set in option, it will panic.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0#retrieving-the-current-deltalink)
    ///
    /// [track_from_delta]: #method.track_root_changes_from_delta_url
    /// [dollar_count]: https://docs.microsoft.com/en-us/graph/query-parameters#count-parameter
    /// [opt_get_count]: ./option/struct.CollectionOption.html#method.get_count
    pub async fn get_root_latest_delta_url_with_option(
        &self,
        option: CollectionOption<DriveItemField>,
    ) -> Result<String> {
        assert!(
            !option.has_get_count(),
            "`get_count` is not supported by Track Changes API",
        );
        self.client
            .get(api_url![&self.drive, "root", "delta"])
            .query(&[("token", "latest")])
            .apply(option)
            .bearer_auth(&self.token)
            .send()
            .await?
            .parse::<DriveItemCollectionResponse>()
            .await?
            .delta_url
            .ok_or_else(|| {
                Error::unexpected_response(
                    "Missing field `@odata.deltaLink` for getting latest delta",
                )
            })
    }

    /// Shortcut to `get_root_latest_delta_url_with_option` with default parameters.
    ///
    /// # See also
    /// [`get_root_latest_delta_url_with_option`][with_opt]
    ///
    /// [with_opt]: #method.get_root_latest_delta_url_with_option
    pub async fn get_root_latest_delta_url(&self) -> Result<String> {
        self.get_root_latest_delta_url_with_option(Default::default())
            .await
    }
}

/// The monitor for checking the progress of a asynchronous `copy` operation.
///
/// # Notes
/// This struct is always present. But since retrieving copy progress requires beta API,
/// it is useless due to the lack of method `fetch_progress` if feature `beta` is not enabled.
///
/// # See also
/// [`OneDrive::copy`][copy]
///
/// [Microsoft docs](https://docs.microsoft.com/en-us/graph/long-running-actions-overview)
///
/// [copy]: ./struct.OneDrive.html#method.copy
#[derive(Debug, Clone)]
pub struct CopyProgressMonitor {
    monitor_url: String,
}

/// The progress of a asynchronous `copy` operation. (Beta)
///
/// # See also
/// [Microsoft Docs Beta](https://docs.microsoft.com/en-us/graph/api/resources/asyncjobstatus?view=graph-rest-beta)
#[cfg(feature = "beta")]
#[allow(missing_docs)]
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CopyProgress {
    pub percentage_complete: f64,
    pub status: CopyStatus,
}

/// The status of a `copy` operation. (Beta)
///
/// # See also
/// [`CopyProgress`][copy_progress]
///
/// [Microsoft Docs Beta](https://docs.microsoft.com/en-us/graph/api/resources/asyncjobstatus?view=graph-rest-beta#json-representation)
///
/// [copy_progress]: ./struct.CopyProgress.html
#[cfg(feature = "beta")]
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum CopyStatus {
    NotStarted,
    InProgress,
    Completed,
    Updating,
    Failed,
    DeletePending,
    DeleteFailed,
    Waiting,
}

impl CopyProgressMonitor {
    /// Make a progress monitor using existing `monitor_url`.
    ///
    /// `monitor_url` should be got from [`CopyProgressMonitor::monitor_url`][monitor_url]
    ///
    /// [monitor_url]: #method.monitor_url
    pub fn from_monitor_url(monitor_url: impl Into<String>) -> Self {
        Self {
            monitor_url: monitor_url.into(),
        }
    }

    /// Get the monitor url.
    #[must_use]
    pub fn monitor_url(&self) -> &str {
        &self.monitor_url
    }

    /// Fetch the `copy` progress. (Beta)
    ///
    /// # See also
    /// [`CopyProgress`][copy_progress]
    ///
    /// [copy_progress]: ./struct.CopyProgress.html
    #[cfg(feature = "beta")]
    pub async fn fetch_progress(&self, onedrive: &OneDrive) -> Result<CopyProgress> {
        // No bearer auth.
        onedrive
            .client
            .get(&self.monitor_url)
            .send()
            .await?
            .parse()
            .await
    }
}

#[derive(Debug, Deserialize)]
struct DriveItemCollectionResponse {
    value: Option<Vec<DriveItem>>,
    #[serde(rename = "@odata.nextLink")]
    next_url: Option<String>,
    #[serde(rename = "@odata.deltaLink")]
    delta_url: Option<String>,
}

#[derive(Debug)]
struct DriveItemFetcher {
    last_response: DriveItemCollectionResponse,
}

impl DriveItemFetcher {
    fn new(first_response: DriveItemCollectionResponse) -> Self {
        Self {
            last_response: first_response,
        }
    }

    fn resume_from(next_url: impl Into<String>) -> Self {
        Self::new(DriveItemCollectionResponse {
            value: None,
            next_url: Some(next_url.into()),
            delta_url: None,
        })
    }

    fn next_url(&self) -> Option<&str> {
        // Return `None` for the first page, or it will
        // lost items of the first page when resumed.
        match &self.last_response {
            DriveItemCollectionResponse {
                value: None,
                next_url: Some(next_url),
                ..
            } => Some(next_url),
            _ => None,
        }
    }

    fn delta_url(&self) -> Option<&str> {
        self.last_response.delta_url.as_deref()
    }

    async fn fetch_next_page(&mut self, onedrive: &OneDrive) -> Result<Option<Vec<DriveItem>>> {
        if let Some(items) = self.last_response.value.take() {
            return Ok(Some(items));
        }
        let url = match self.last_response.next_url.as_ref() {
            None => return Ok(None),
            Some(url) => url,
        };
        self.last_response = onedrive
            .client
            .get(url)
            .bearer_auth(&onedrive.token)
            .send()
            .await?
            .parse()
            .await?;
        Ok(Some(self.last_response.value.take().unwrap_or_default()))
    }

    async fn fetch_all(mut self, onedrive: &OneDrive) -> Result<(Vec<DriveItem>, Option<String>)> {
        let mut buf = vec![];
        while let Some(items) = self.fetch_next_page(onedrive).await? {
            buf.extend(items);
        }
        Ok((buf, self.delta_url().map(Into::into)))
    }
}

/// The page fetcher for listing children
///
/// # See also
/// [`OneDrive::list_children_with_option`][list_children_with_opt]
///
/// [list_children_with_opt]: ./struct.OneDrive.html#method.list_children_with_option
#[derive(Debug)]
pub struct ListChildrenFetcher {
    fetcher: DriveItemFetcher,
}

impl ListChildrenFetcher {
    fn new(first_response: DriveItemCollectionResponse) -> Self {
        Self {
            fetcher: DriveItemFetcher::new(first_response),
        }
    }

    /// Resume a fetching process from url from
    /// [`ListChildrenFetcher::next_url`][next_url].
    ///
    /// [next_url]: #method.next_url
    #[must_use]
    pub fn resume_from(next_url: impl Into<String>) -> Self {
        Self {
            fetcher: DriveItemFetcher::resume_from(next_url),
        }
    }

    /// Try to get the url to the next page.
    ///
    /// Used for resuming the fetching progress.
    ///
    /// # Error
    /// Will success only if there are more pages and the first page is already read.
    ///
    /// # Note
    /// The first page data from [`OneDrive::list_children_with_option`][list_children_with_opt]
    /// will be cached and have no idempotent url to resume/re-fetch.
    ///
    /// [list_children_with_opt]: ./struct.OneDrive.html#method.list_children_with_option
    #[must_use]
    pub fn next_url(&self) -> Option<&str> {
        self.fetcher.next_url()
    }

    /// Fetch the next page, or `None` if reaches the end.
    pub async fn fetch_next_page(&mut self, onedrive: &OneDrive) -> Result<Option<Vec<DriveItem>>> {
        self.fetcher.fetch_next_page(onedrive).await
    }

    /// Fetch all rest pages and collect all items.
    ///
    /// # Errors
    ///
    /// Any error occurs when fetching will lead to an failure, and
    /// all progress will be lost.
    pub async fn fetch_all(self, onedrive: &OneDrive) -> Result<Vec<DriveItem>> {
        self.fetcher
            .fetch_all(onedrive)
            .await
            .map(|(items, _)| items)
    }
}

/// The page fetcher for tracking operations with `Iterator` interface.
///
/// # See also
/// [`OneDrive::track_changes_from_initial`][track_initial]
///
/// [`OneDrive::track_changes_from_delta_url`][track_delta]
///
/// [track_initial]: ./struct.OneDrive.html#method.track_changes_from_initial_with_option
/// [track_delta]: ./struct.OneDrive.html#method.track_changes_from_delta_url
#[derive(Debug)]
pub struct TrackChangeFetcher {
    fetcher: DriveItemFetcher,
}

impl TrackChangeFetcher {
    fn new(first_response: DriveItemCollectionResponse) -> Self {
        Self {
            fetcher: DriveItemFetcher::new(first_response),
        }
    }

    /// Resume a fetching process from url.
    ///
    /// The url should be from [`TrackChangeFetcher::next_url`][next_url].
    ///
    /// [next_url]: #method.next_url
    #[must_use]
    pub fn resume_from(next_url: impl Into<String>) -> Self {
        Self {
            fetcher: DriveItemFetcher::resume_from(next_url),
        }
    }

    /// Try to get the url to the next page.
    ///
    /// Used for resuming the fetching progress.
    ///
    /// # Error
    /// Will success only if there are more pages and the first page is already read.
    ///
    /// # Note
    /// The first page data from
    /// [`OneDrive::track_changes_from_initial_with_option`][track_initial]
    /// will be cached and have no idempotent url to resume/re-fetch.
    ///
    /// [track_initial]: ./struct.OneDrive.html#method.track_changes_from_initial
    #[must_use]
    pub fn next_url(&self) -> Option<&str> {
        self.fetcher.next_url()
    }

    /// Try to the delta url representing a snapshot of current track change operation.
    ///
    /// Used for tracking changes from this snapshot (rather than initial) later,
    /// using [`OneDrive::track_changes_from_delta_url`][track_delta].
    ///
    /// # Error
    /// Will success only if there are no more pages.
    ///
    /// # See also
    /// [`OneDrive::track_changes_from_delta_url`][track_delta]
    ///
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0#example-last-page-in-a-set)
    ///
    /// [track_delta]: ./struct.OneDrive.html#method.track_changes_from_delta_url
    #[must_use]
    pub fn delta_url(&self) -> Option<&str> {
        self.fetcher.delta_url()
    }

    /// Fetch the next page, or `None` if reaches the end.
    pub async fn fetch_next_page(&mut self, onedrive: &OneDrive) -> Result<Option<Vec<DriveItem>>> {
        self.fetcher.fetch_next_page(onedrive).await
    }

    /// Fetch all rest pages, collect all items, and also return `delta_url`.
    ///
    /// # Errors
    ///
    /// Any error occurs when fetching will lead to an failure, and
    /// all progress will be lost.
    pub async fn fetch_all(self, onedrive: &OneDrive) -> Result<(Vec<DriveItem>, String)> {
        let (items, opt_delta_url) = self.fetcher.fetch_all(onedrive).await?;
        let delta_url = opt_delta_url.ok_or_else(|| {
            Error::unexpected_response("Missing `@odata.deltaLink` for the last page")
        })?;
        Ok((items, delta_url))
    }
}

#[derive(Serialize)]
struct ItemReference<'a> {
    path: &'a str,
}

/// An upload session for resumable file uploading process.
///
/// # See also
/// [`OneDrive::new_upload_session`][get_session]
///
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/resources/uploadsession?view=graph-rest-1.0)
///
/// [get_session]: ./struct.OneDrive.html#method.new_upload_session
#[derive(Debug)]
pub struct UploadSession {
    upload_url: String,
}

/// Metadata of an in-progress upload session
///
/// # See also
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#resuming-an-in-progress-upload)
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UploadSessionMeta {
    /// Get a collection of byte ranges that the server is missing for the file.
    ///
    /// Used for determine what to upload when resuming a session.
    pub next_expected_ranges: Vec<ExpectRange>,
    /// Get the date and time in UTC that the upload session will expire.
    ///
    /// The complete file must be uploaded before this expiration time is reached.
    pub expiration_date_time: TimestampString,
}

impl UploadSession {
    /// The upload size limit of a single [`upload_part`] call.
    ///
    /// The value is from
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#upload-bytes-to-the-upload-session)
    /// and may not be accurate or stable.
    ///
    /// [`upload_part`]: #method.upload_part
    pub const MAX_PART_SIZE: usize = 60 << 20; // 60 MiB

    /// Construct back the upload session from upload URL.
    pub fn from_upload_url(upload_url: impl Into<String>) -> Self {
        Self {
            upload_url: upload_url.into(),
        }
    }

    /// Query the metadata of the upload to find out which byte ranges
    /// have been received previously.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#resuming-an-in-progress-upload)
    pub async fn get_meta(&self, client: &Client) -> Result<UploadSessionMeta> {
        // No bearer auth.
        client
            .get(&self.upload_url)
            .send()
            .await?
            .parse::<UploadSessionMeta>()
            .await
    }

    /// The URL endpoint accepting PUT requests.
    ///
    /// It is exactly what you passed in [`UploadSession::from_upload_url`].
    ///
    /// [`UploadSession::from_upload_url`]: #method.new
    #[must_use]
    pub fn upload_url(&self) -> &str {
        &self.upload_url
    }

    /// Cancel the upload session
    ///
    /// This cleans up the temporary file holding the data previously uploaded.
    /// This should be used in scenarios where the upload is aborted, for example,
    /// if the user cancels the transfer.
    ///
    /// Temporary files and their accompanying upload session are automatically
    /// cleaned up after the `expirationDateTime` has passed. Temporary files may
    /// not be deleted immediately after the expiration time has elapsed.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#cancel-the-upload-session)
    pub async fn delete(&self, client: &Client) -> Result<()> {
        // No bearer auth.
        client
            .delete(&self.upload_url)
            .send()
            .await?
            .parse_no_content()
            .await
    }

    /// Upload bytes to an upload session
    ///
    /// You can upload the entire file, or split the file into multiple byte ranges,
    /// as long as the maximum bytes in any given request is less than 60 MiB.
    /// The fragments of the file must be uploaded sequentially in order. Uploading
    /// fragments out of order will result in an error.
    ///
    /// # Notes
    /// If your app splits a file into multiple byte ranges, the size of each
    /// byte range MUST be a multiple of 320 KiB (327,680 bytes). Using a fragment
    /// size that does not divide evenly by 320 KiB will result in errors committing
    /// some files. The 60 MiB limit and 320 KiB alignment are not checked locally since
    /// they may change in the future.
    ///
    /// The `file_size` of all part upload requests should be identical.
    ///
    /// # Results
    /// - If the part is uploaded successfully, but the file is not complete yet,
    ///   will return `None`.
    /// - If this is the last part and it is uploaded successfully,
    ///   will return `Some(<newly_created_drive_item>)`.
    ///
    /// # Errors
    /// When the file is completely uploaded, if an item with the same name is created
    /// during uploading, the last `upload_to_session` call will return `Err` with
    /// HTTP `409 CONFLICT`.
    ///
    /// # Panics
    /// Panic if `remote_range` is invalid or not match the length of `data`.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#upload-bytes-to-the-upload-session)
    pub async fn upload_part(
        &self,
        data: impl Into<Bytes>,
        remote_range: std::ops::Range<u64>,
        file_size: u64,
        client: &Client,
    ) -> Result<Option<DriveItem>> {
        use std::convert::TryFrom as _;

        let data = data.into();
        assert!(!data.is_empty(), "Empty data");
        assert!(
            remote_range.start < remote_range.end && remote_range.end <= file_size
            // `Range<u64>` has no method `len()`.
            && remote_range.end - remote_range.start <= u64::try_from(data.len()).unwrap(),
            "Invalid remote range",
        );

        // No bearer auth.
        client
            .put(&self.upload_url)
            .header(
                header::CONTENT_RANGE,
                format!(
                    "bytes {}-{}/{}",
                    remote_range.start,
                    // Inclusive.
                    // We checked `remote_range.start < remote_range.end`,
                    // so this never overflows.
                    remote_range.end - 1,
                    file_size,
                ),
            )
            .body(data)
            .send()
            .await?
            .parse_optional()
            .await
    }
}

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

    #[test]
    fn test_api_url() {
        let mock_item_id = ItemId("1234".to_owned());
        assert_eq!(
            api_path!(&ItemLocation::from_id(&mock_item_id)),
            "/drive/items/1234",
        );

        assert_eq!(
            api_path!(&ItemLocation::from_path("/dir/file name").unwrap()),
            "/drive/root:%2Fdir%2Ffile%20name:",
        );
    }

    #[test]
    fn test_path_name_check() {
        let invalid_names = ["", ".*?", "a|b", "a<b>b", ":run", "/", "\\"];
        let valid_names = [
            "QAQ",
            "0",
            ".",
            "a-a:", // Unicode colon "\u{ff1a}"
            "魔理沙",
        ];

        let check_name = |s: &str| FileName::new(s).is_some();
        let check_path = |s: &str| ItemLocation::from_path(s).is_some();

        for s in &valid_names {
            assert!(check_name(s), "{}", s);
            let path = format!("/{s}");
            assert!(check_path(&path), "{}", path);

            for s2 in &valid_names {
                let mut path = format!("/{s}/{s2}");
                assert!(check_path(&path), "{}", path);
                path.push('/'); // Trailing
                assert!(check_path(&path), "{}", path);
            }
        }

        for s in &invalid_names {
            assert!(!check_name(s), "{}", s);

            // `/` and `/xx/` is valid and is tested below.
            if s.is_empty() {
                continue;
            }

            let path = format!("/{s}");
            assert!(!check_path(&path), "{}", path);

            for s2 in &valid_names {
                let path = format!("/{s2}/{s}");
                assert!(!check_path(&path), "{}", path);
            }
        }

        assert!(check_path("/"));
        assert!(check_path("/a"));
        assert!(check_path("/a/"));
        assert!(check_path("/a/b"));
        assert!(check_path("/a/b/"));

        assert!(!check_path(""));
        assert!(!check_path("/a/b//"));
        assert!(!check_path("a"));
        assert!(!check_path("a/"));
        assert!(!check_path("//"));
    }
}