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
use crate::error::{Error, Result};
use crate::query_option::{CollectionOption, ObjectOption};
use crate::resource::*;
use crate::util::*;
use reqwest::header;
use serde::{de, Deserialize, Serialize};

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

macro_rules! api_path {
    ($($t:tt)*) => {
        api_url![@"path://"; $($t)*].path()
    };
}

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

impl DriveClient {
    /// Create a DriveClient to perform operations in a Drive.
    pub fn new(token: String, drive: impl Into<DriveLocation>) -> Self {
        DriveClient {
            client: ::reqwest::Client::new(),
            token,
            drive: drive.into(),
        }
    }

    /// Get [`Drive`][drive].
    ///
    /// Retrieve the properties and relationships of a [`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 fn get_drive_with_option(&self, option: ObjectOption<DriveField>) -> Result<Drive> {
        self.client
            .get(api_url![&self.drive])
            .query(&option.params().collect::<Vec<_>>())
            .bearer_auth(&self.token)
            .send()?
            .parse()
    }

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

    /// List children of a [`DriveItem`][drive_item].
    ///
    /// Return a collection of [`DriveItem`][drive_item]s in the children relationship
    /// of the given one.
    ///
    /// # Note
    /// Will return `Ok(None)` if `if_none_match` is set and matches the item.
    ///
    /// # 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
    pub fn list_children_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        if_none_match: Option<&Tag>,
        option: CollectionOption<DriveItemField>,
    ) -> Result<Option<ListChildrenFetcher>> {
        self.client
            .get(api_url![&self.drive, &item.into(), "children"])
            .query(&option.params().collect::<Vec<_>>())
            .bearer_auth(&self.token)
            .opt_header(header::IF_NONE_MATCH, if_none_match)
            .send()?
            .parse_optional()
            .map(|opt_resp| opt_resp.map(|resp| ListChildrenFetcher::new(self, resp)))
    }

    /// Shortcut to [`list_children_with_option`][with_opt] with default params and fetch all.
    ///
    /// [with_opt]: #method.list_children_with_option
    pub fn list_children<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        if_none_match: Option<&Tag>,
    ) -> Result<Option<Vec<DriveItem>>> {
        self.list_children_with_option(item.into(), if_none_match, Default::default())?
            .map(|fetcher| fetcher.fetch_all())
            .transpose()
    }

    /// Get a [`DriveItem`][drive_item] resource.
    ///
    /// Retrieve the metadata for a [`DriveItem`][drive_item] by file system path or ID.
    ///
    /// # Errors
    /// Will return `Ok(None)` if `if_none_match` is set and matches the item .
    ///
    /// # 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
    pub fn get_item_with_option<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        if_none_match: Option<&Tag>,
        option: ObjectOption<DriveItemField>,
    ) -> Result<Option<DriveItem>> {
        self.client
            .get(api_url![&self.drive, &item.into()])
            .query(&option.params().collect::<Vec<_>>())
            .bearer_auth(&self.token)
            .opt_header(header::IF_NONE_MATCH, if_none_match)
            .send()?
            .parse_optional()
    }

    /// Shortcut to [`get_item_with_option`][with_opt] with default parameters.
    ///
    /// [with_opt]: #method.get_item_with_option
    pub fn get_item<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        if_none_match: Option<&Tag>,
    ) -> Result<Option<DriveItem>> {
        self.get_item_with_option(item.into(), if_none_match, Default::default())
    }

    /// Create a new folder in a drive
    ///
    /// Create a new folder [`DriveItem`][drive_item] with a specified parent item or path.
    ///
    /// # Errors
    /// Will return `Err` with HTTP CONFLICT if 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
    pub fn create_folder<'a>(
        &self,
        parent_item: impl Into<ItemLocation<'a>>,
        name: &FileName,
    ) -> Result<DriveItem> {
        #[derive(Serialize)]
        struct Folder {}

        #[derive(Serialize)]
        struct Request<'a> {
            name: &'a str,
            folder: Folder,
            // https://docs.microsoft.com/en-us/graph/api/resources/driveitem?view=graph-rest-1.0#instance-attributes
            #[serde(rename = "@microsoft.graph.conflictBehavior")]
            conflict_behavior: &'a str,
        }

        self.client
            .post(api_url![&self.drive, &parent_item.into(), "children"])
            .bearer_auth(&self.token)
            .json(&Request {
                name: name.as_str(),
                folder: Folder {},
                conflict_behavior: "fail", // TODO
            })
            .send()?
            .parse()
    }

    const UPLOAD_SMALL_LIMIT: usize = 4_000_000; // 4 MB

    /// Upload or replace the contents of a [`DriveItem`][drive_item]
    ///
    /// 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 4MB in size.
    ///
    /// # 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 fn upload_small<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        data: &[u8],
    ) -> Result<DriveItem> {
        assert!(
            data.len() <= Self::UPLOAD_SMALL_LIMIT,
            "Data too large for upload_small ({} B > {} B)",
            data.len(),
            Self::UPLOAD_SMALL_LIMIT,
        );

        self.client
            .put(api_url![&self.drive, &item.into(), "content"])
            .bearer_auth(&self.token)
            .body(data.to_owned())
            .send()?
            .parse()
    }

    /// 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 PRECONDITION_FAILED if `if_match` is set
    /// but does not match the item.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#create-an-upload-session)
    pub fn new_upload_session<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        overwrite: bool,
        if_match: Option<&Tag>,
    ) -> Result<UploadSession> {
        #[derive(Serialize)]
        struct Item {
            #[serde(rename = "@microsoft.graph.conflictBehavior")]
            conflict_behavior: &'static str,
        }

        #[derive(Serialize)]
        struct Request {
            item: Item,
        }

        self.client
            .post(api_url![&self.drive, &item.into(), "createUploadSession"])
            .opt_header(header::IF_MATCH, if_match)
            .bearer_auth(&self.token)
            .json(&Request {
                item: Item {
                    conflict_behavior: if overwrite { "overwrite" } else { "fail" },
                },
            })
            .send()?
            .parse()
    }

    /// Resuming an in-progress upload
    ///
    /// Query the status 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 fn get_upload_session(&self, upload_url: &str) -> Result<UploadSession> {
        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct UploadSessionResponse {
            // TODO: Incompleted
            upload_url: Option<String>,
            next_expected_ranges: Vec<ExpectRange>,
            // expiration_date_time: Timestamp,
        }

        self.client
            .get(upload_url)
            .send()?
            .parse::<UploadSessionResponse>()
            .map(|resp| UploadSession {
                upload_url: upload_url.to_owned(),
                next_expected_ranges: resp.next_expected_ranges,
            })
    }

    /// 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 immedately 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 fn delete_upload_session(&self, sess: &UploadSession) -> Result<()> {
        self.client
            .delete(&sess.upload_url)
            .send()?
            .parse_no_content()
    }

    const UPLOAD_SESSION_PART_LIMIT: usize = 60 << 20; // 60 MiB

    /// Upload bytes to the 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.
    ///
    /// Note: 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.
    ///
    /// # 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 fn upload_to_session(
        &self,
        session: &UploadSession,
        data: &[u8],
        remote_range: ::std::ops::Range<usize>,
        total_size: usize,
    ) -> Result<Option<DriveItem>> {
        // FIXME: https://github.com/rust-lang/rust-clippy/issues/3807
        #[allow(clippy::len_zero)]
        {
            assert!(
                remote_range.len() > 0 && remote_range.end <= total_size,
                "Invalid range",
            );
        }
        assert_eq!(
            data.len(),
            remote_range.end - remote_range.start,
            "Length mismatch"
        );
        assert!(
            data.len() <= Self::UPLOAD_SESSION_PART_LIMIT,
            "Data too large for one part ({} B > {} B)",
            data.len(),
            Self::UPLOAD_SESSION_PART_LIMIT,
        );

        self.client
            .put(&session.upload_url)
            // No auth token
            .header(
                header::CONTENT_RANGE,
                format!(
                    "bytes {}-{}/{}",
                    remote_range.start,
                    remote_range.end - 1,
                    total_size
                ),
            )
            .body(data.to_owned())
            .send()?
            .parse_optional()
    }

    /// Copy a DriveItem.
    ///
    /// Asynchronously creates a copy of an driveItem (including any children),
    /// under a new parent item or with a new name.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-copy?view=graph-rest-1.0)
    pub fn copy<'a, 'b>(
        &self,
        source_item: impl Into<ItemLocation<'a>>,
        dest_folder: impl Into<ItemLocation<'b>>,
        dest_name: &FileName,
    ) -> Result<()> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Request<'a> {
            parent_reference: ItemReference<'a>,
            name: &'a str,
        }

        self.client
            .post(api_url![&self.drive, &source_item.into(), "copy"])
            .bearer_auth(&self.token)
            .json(&Request {
                parent_reference: ItemReference {
                    path: api_path![&self.drive, &dest_folder.into()],
                },
                name: dest_name.as_str(),
            })
            .send()?
            .parse_no_content() // TODO: Handle async copy
    }

    /// 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.
    ///
    /// # Errors
    /// Will return `Err` with HTTP PRECONDITION_FAILED if `if_match` is set
    /// but doesn't match the item.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0)
    pub fn move_<'a, 'b>(
        &self,
        source_item: impl Into<ItemLocation<'a>>,
        dest_directory: impl Into<ItemLocation<'b>>,
        dest_name: Option<&FileName>,
        if_match: Option<&Tag>,
    ) -> Result<DriveItem> {
        #[derive(Serialize)]
        #[serde(rename_all = "camelCase")]
        struct Request<'a> {
            parent_reference: ItemReference<'a>,
            name: Option<&'a str>,
        }

        self.client
            .patch(api_url![&self.drive, &source_item.into()])
            .bearer_auth(&self.token)
            .opt_header(header::IF_MATCH, if_match)
            .json(&Request {
                parent_reference: ItemReference {
                    path: api_path![&self.drive, &dest_directory.into()],
                },
                name: dest_name.map(FileName::as_str),
            })
            .send()?
            .parse()
    }

    /// Delete a [`DriveItem`][drive_item].
    ///
    /// 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.
    ///
    /// # Errors
    /// Will return `Err` with HTTP PRECONDITION_FAILED if `if_match` is set but
    /// does not match the item.
    ///
    /// # 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
    pub fn delete<'a>(
        &self,
        item: impl Into<ItemLocation<'a>>,
        if_match: Option<&Tag>,
    ) -> Result<()> {
        self.client
            .delete(api_url![&self.drive, &item.into()])
            .bearer_auth(&self.token)
            .opt_header(header::IF_MATCH, if_match)
            .send()?
            .parse_no_content()
    }

    /// Track changes for a 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.
    ///
    /// # Return
    /// The fetcher for fetching all changes from initial state (empty) to the snapshot of
    /// current states.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0)
    pub fn track_changes_from_initial_with_option<'a>(
        &self,
        folder: impl Into<ItemLocation<'a>>,
        option: CollectionOption<DriveItemField>,
    ) -> Result<TrackChangeFetcher> {
        self.client
            .get(&api_url![&self.drive, &folder.into(), "delta"].into_string())
            .query(&option.params().collect::<Vec<_>>())
            .bearer_auth(&self.token)
            .send()?
            .parse()
            .map(|resp| TrackChangeFetcher::new(self, resp))
    }

    /// Shortcut to [`track_changes_from_initial_with_option`][with_opt] with default parameters.
    ///
    /// [with_opt]: #method.track_changes_from_initial_with_option
    pub fn track_changes_from_initial<'a>(
        &self,
        folder: impl Into<ItemLocation<'a>>,
    ) -> Result<(Vec<DriveItem>, String)> {
        self.track_changes_from_initial_with_option(folder.into(), Default::default())?
            .fetch_all()
    }

    /// Track changes for a folder from snapshot (delta url) to snapshot of current states.
    ///
    /// # See also
    /// [`DriveClient::track_changes_from_initial_with_option`][track_initial]
    ///
    /// [track_initial]: #method.track_changes_from_initial_with_option
    pub fn track_changes_from_delta_url(&self, delta_url: &str) -> Result<TrackChangeFetcher> {
        self.client
            .get(delta_url)
            .bearer_auth(&self.token)
            .send()?
            .parse()
            .map(|resp| TrackChangeFetcher::new(self, resp))
    }

    /// Get a delta url representing the snapshot of current states.
    ///
    /// # See also
    /// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-delta?view=graph-rest-1.0)
    pub fn get_latest_delta_url<'a>(&self, folder: impl Into<ItemLocation<'a>>) -> Result<String> {
        self.client
            .get(&api_url![&self.drive, &folder.into(), "delta"].into_string())
            .query(&[("token", "latest")])
            .bearer_auth(&self.token)
            .send()?
            .parse()
            .and_then(|resp: DriveItemCollectionResponse| {
                resp.delta_url.ok_or_else(|| {
                    Error::unexpected_response(
                        "Missing field `@odata.deltaLink` for getting latest delta",
                    )
                })
            })
    }
}

#[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 {
    client: reqwest::Client,
    token: String,
    response: DriveItemCollectionResponse,
}

impl DriveItemFetcher {
    fn new(client: &DriveClient, response: DriveItemCollectionResponse) -> Self {
        Self {
            client: client.client.clone(),
            token: client.token.clone(),
            response,
        }
    }

    fn get_next_url(&self) -> Option<&str> {
        match (&self.response.value, &self.response.next_url) {
            (None, Some(url)) => Some(url),
            _ => None,
        }
    }

    fn fetch_next(&mut self) -> Option<Result<Vec<DriveItem>>> {
        if let Some(v) = self.response.value.take() {
            return Some(Ok(v));
        }

        // Not `take` here. Will remain unchanged if failed to fetch.
        let url = self.response.next_url.as_ref()?;
        match (|| {
            self.client
                .get(url)
                .bearer_auth(&self.token)
                .send()?
                .parse::<DriveItemCollectionResponse>()
        })() {
            Err(err) => Some(Err(err)),
            Ok(DriveItemCollectionResponse {
                next_url: Some(_),
                value: None,
                ..
            }) => Some(Err(Error::unexpected_response(
                "Missing field `value` when not finished",
            ))),
            Ok(resp) => {
                self.response = resp;
                Some(Ok(self.response.value.take()?))
            }
        }
    }

    fn fetch_all(&mut self) -> Result<Vec<DriveItem>> {
        let mut buf = vec![];
        while let Some(ret) = self.fetch_next() {
            buf.append(&mut ret?);
        }
        Ok(buf)
    }
}

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

impl ListChildrenFetcher {
    fn new(client: &DriveClient, response: DriveItemCollectionResponse) -> Self {
        Self {
            fetcher: DriveItemFetcher::new(client, response),
        }
    }

    /// Resume a fetching process from url from
    /// [`ListChildrenFetcher::get_next_url`][get_next_url].
    ///
    /// [get_next_url]: #method.get_next_url
    pub fn resume_from(client: &DriveClient, next_url: String) -> Self {
        Self::new(
            client,
            DriveItemCollectionResponse {
                value: None,
                next_url: Some(next_url),
                delta_url: None,
            },
        )
    }

    /// 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 readed.
    ///
    /// # Note
    /// The first page data from [`DriveClient::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.DriveClient.html#method.list_children_with_option
    pub fn get_next_url(&self) -> Option<&str> {
        self.fetcher.get_next_url()
    }

    /// Fetch all rest pages and return all items concated.
    ///
    /// # Errors
    /// Will return `Err` if any error occurs during fetching.
    ///
    /// Note that you will lose all progress unless all requests are success,
    /// so it is preferred to use `Iterator::next` to make it more error-tolerant.
    pub fn fetch_all(mut self) -> Result<Vec<DriveItem>> {
        self.fetcher.fetch_all()
    }
}

impl Iterator for ListChildrenFetcher {
    type Item = Result<Vec<DriveItem>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.fetcher.fetch_next()
    }
}

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

impl TrackChangeFetcher {
    fn new(client: &DriveClient, response: DriveItemCollectionResponse) -> Self {
        Self {
            fetcher: DriveItemFetcher::new(client, response),
        }
    }

    /// Resume a fetching process from url.
    ///
    /// The url should be from [`TrackChangeFetcher::get_next_url`][get_next_url].
    ///
    /// [get_next_url]: #method.get_next_url
    pub fn resume_from(client: &DriveClient, next_url: String) -> Self {
        Self {
            fetcher: DriveItemFetcher {
                client: client.client.clone(),
                token: client.token.clone(),
                response: DriveItemCollectionResponse {
                    value: None,
                    delta_url: None,
                    next_url: Some(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 readed.
    ///
    /// # Note
    /// The first page data from
    /// [`DriveClient::track_changes_from_initial_with_option`][track_initial]
    /// will be cached and have no idempotent url to resume/re-fetch.
    ///
    /// [track_initial]: ./struct.DriveClient.html#method.track_changes_from_initial
    pub fn get_next_url(&self) -> Option<&str> {
        self.fetcher.get_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 [`DriveClient::track_changes_from_delta_url`][track_delta].
    ///
    /// # Error
    /// Will success only if there are no more pages.
    ///
    /// # See also
    /// [`DriveClient::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.DriveClient.html#method.track_changes_from_delta_url
    pub fn get_delta_url(&self) -> Option<&str> {
        match &self.fetcher.response {
            DriveItemCollectionResponse {
                value: None,
                delta_url: Some(url),
                ..
            } => Some(url),
            _ => None,
        }
    }

    /// Fetch all rest pages and return all items concated with a delta url.
    ///
    /// # Errors
    /// Will return `Err` if any error occurs during fetching.
    ///
    /// Note that you will lose all progress unless all requests are success,
    /// so it is preferred to use `Iterator::next` to make it more error-tolerant.
    pub fn fetch_all(mut self) -> Result<(Vec<DriveItem>, String)> {
        let v = self.fetcher.fetch_all()?;
        // Must not be None if `fetch_all` succeed.
        Ok((v, self.fetcher.response.delta_url.unwrap()))
    }
}

impl Iterator for TrackChangeFetcher {
    type Item = Result<Vec<DriveItem>>;

    fn next(&mut self) -> Option<Self::Item> {
        match (self.fetcher.fetch_next(), &self.fetcher.response.delta_url) {
            (None, None) => Some(Err(Error::unexpected_response(
                "Missing field `@odata.deltaLink` for the last page",
            ))),
            (ret, _) => ret,
        }
    }
}

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

/// An upload session for resumable file uploading process.
///
/// # See also
/// [`DriveClient::new_upload_session`][get_session]
///
/// [Microsoft Docs](https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#create-an-upload-session)
///
/// [get_session]: ./struct.DriveClient.html#method.new_upload_session
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UploadSession {
    // TODO: Incompleted
    upload_url: String,
    next_expected_ranges: Vec<ExpectRange>,
    // expiration_date_time: Timestamp,
}

impl UploadSession {
    /// Get the url for the upload session.
    ///
    /// It can be used to resume the session using [`DriveClient::get_upload_session`][get_session].
    ///
    /// [get_session]: ./struct.DriveClient.html#method.get_upload_session
    pub fn get_url(&self) -> &str {
        &self.upload_url
    }

    /// Get next byte ranges the server expected.
    ///
    /// Used for determine what to upload when resuming a session.
    pub fn get_next_expected_ranges(&self) -> &[ExpectRange] {
        &self.next_expected_ranges
    }
}

/// A half-open byte range `start..end` or `start..`.
#[derive(Debug, PartialEq, Eq)]
pub struct ExpectRange {
    /// The lower bound of the range (inclusive).
    pub start: u64,
    /// The optional upper bound of the range (exclusive).
    pub end: Option<u64>,
}

impl<'de> de::Deserialize<'de> for ExpectRange {
    fn deserialize<D: de::Deserializer<'de>>(
        deserializer: D,
    ) -> ::std::result::Result<Self, D::Error> {
        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = ExpectRange;

            fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f, "Expect Range")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> ::std::result::Result<Self::Value, E> {
                let parse = || -> Option<ExpectRange> {
                    let mut it = v.split('-');
                    let start = it.next()?.parse().ok()?;
                    let end = match it.next()? {
                        "" => None,
                        s => {
                            let end = s.parse::<u64>().ok()?.checked_add(1)?; // Exclusive.
                            if end <= start {
                                return None;
                            }
                            Some(end)
                        }
                    };
                    if it.next().is_some() {
                        return None;
                    }

                    Some(ExpectRange { start, end })
                };
                match parse() {
                    Some(v) => Ok(v),
                    None => Err(E::invalid_value(
                        de::Unexpected::Str(v),
                        &"`{lower}-` or `{lower}-{upper}`",
                    )),
                }
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_api_url() {
        assert_eq!(
            api_url!["a", &DriveLocation::me(), "b"].path(),
            "/v1.0/a/drive/b",
        );

        let mock_drive_id = DriveId::new("1234".to_owned());
        assert_eq!(
            api_path![&DriveLocation::from_id(mock_drive_id)],
            "/drives/1234",
        );

        assert_eq!(
            api_path![&ItemLocation::from_path("/dir/file name").unwrap()],
            "/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("//"));
    }

    #[test]
    fn test_range_parsing() {
        let cases = [
            (
                "42-196",
                Some(ExpectRange {
                    start: 42,
                    end: Some(197),
                }),
            ), // [left, right)
            (
                "418-",
                Some(ExpectRange {
                    start: 418,
                    end: None,
                }),
            ),
            ("", None),
            ("42-4", None),
            ("-9", None),
            ("-", None),
            ("1-2-3", None),
            ("0--2", None),
            ("-1-2", None),
        ];

        for &(s, ref expect) in &cases {
            let ret = serde_json::from_str(&serde_json::to_string(s).unwrap());
            assert_eq!(
                ret.as_ref().ok(),
                expect.as_ref(),
                "Failed: Got {:?} on {:?}",
                ret,
                s,
            );
        }
    }
}