prawn 0.0.3

Rust Client for the Tidal API providing comprehensive API coverag, and easy OAuth management
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
use std::ops::Deref;
use std::sync::{Arc, RwLock};
use std::vec::IntoIter;

use crate::apis::configuration::Configuration;
use crate::apis::{Api, ApiClient};
use crate::auth_provider::{self, AccessTokenWithExpiry, AuthProvider, AuthProviderError};
use chrono::{DateTime, Utc};
use oauth2::basic::BasicTokenType;
use oauth2::http::{Extensions, HeaderValue};
use oauth2::{basic::BasicClient, EndpointNotSet, EndpointSet, TokenResponse};
use oauth2::{
    AuthType, AuthUrl, AuthorizationCode, ClientId, CsrfToken, DeviceAuthorizationRequest,
    EmptyExtraTokenFields, PkceCodeChallenge, PkceCodeVerifier, RedirectUrl, RefreshToken, Scope,
    StandardTokenResponse, TokenUrl,
};
use reqwest::{Request, Response, StatusCode};
use reqwest_middleware::{ClientBuilder, Extension, Middleware, Next};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Display;
use url::{OpaqueOrigin, Url};

type Result<T> = std::result::Result<T, TidalClientError>;

static TIDAL_AUTH_URI: &str = "https://login.tidal.com/authorize";
static TIDAL_TOKEN_URI: &str = "https://auth.tidal.com/v1/oauth2/token";

#[derive(Debug)]
pub struct TidalClientError {
    msg: String,
    cause: String,
}

impl Error for TidalClientError {}

impl Display for TidalClientError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.msg, self.cause)
    }
}

impl From<TidalClientError> for String {
    fn from(value: TidalClientError) -> Self {
        value.to_string()
    }
}

/// TidalClient is the entrypoint for the Tidal API.
/// It manages tokens, provides OAuth helper methods,
/// and exposes methods for calling the Tidal API.
#[derive(Clone)]
pub struct TidalClient {
    api_client: ApiClient,
    oauth_client: oauth2::basic::BasicClient<
        EndpointSet,
        EndpointNotSet,
        EndpointNotSet,
        EndpointNotSet,
        EndpointSet,
    >,
    oauth_http_client: oauth2::reqwest::Client,
}

/// Contains token information used to call Tidal API after authenticating.
///
/// Used in initializing [`TidalClient`] via  [`TidalClient::new`] within
/// a [`TidalClientConfig`], or adding to a copy of an existing client with
/// [`TidalClient::with_token`].
pub struct Token {
    /// Passed in API requests as Bearer token.
    pub access_token: String,
    /// Used to request new access_tokens after expiration has passed.
    pub refresh_token: String,
    /// RFC3339 string indicating the time that `access_token` expires.
    pub expiry: String,
}

impl From<StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>> for Token {
    fn from(value: StandardTokenResponse<EmptyExtraTokenFields, BasicTokenType>) -> Self {
        let expires_in = value.expires_in().clone().unwrap_or_default();

        let expiry = Utc::now() + expires_in;

        Token {
            access_token: value.access_token().clone().into_secret(),
            refresh_token: value
                .refresh_token()
                .unwrap_or(&oauth2::RefreshToken::new(String::from("")))
                .clone()
                .into_secret(),
            expiry: expiry.to_rfc3339(),
        }
    }
}

/// [`TidalClient`] configuration used to initialize new
/// client with [`TidalClient::new`].
pub struct TidalClientConfig {
    /// Token configuration. Has information about
    /// access token, refresh token, and expiration.
    pub auth_token: Option<Token>,
    /// Configuration for OAuth helper methods.
    pub oauth_config: OAuthConfig,
}

/// OAuth configuration used in [`TidalClientConfig`].
#[derive(Debug, Clone)]
pub struct OAuthConfig {
    /// The redirect URI used during Authorization code flow. Will be added
    /// to the URL generated by [`TidalClient::get_authorize_url_and_state`].
    pub redirect_uri: String,
    pub client_id: String,
    pub client_secret: Option<String>,
}

type OAuthClient = oauth2::basic::BasicClient<
    EndpointSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointNotSet,
    EndpointSet,
>;

struct AuthTokenRefreshMiddleware {
    auth_provider: crate::auth_provider::AuthProvider,
    http_client: oauth2::reqwest::Client,
    oauth_client: OAuthClient,
}

impl AuthTokenRefreshMiddleware {
    async fn refresh_access_token(&self) -> Result<AccessTokenWithExpiry> {
        let refresh_token = self.auth_provider.get_refresh_token();

        let maybe_token = self
            .oauth_client
            .exchange_refresh_token(&refresh_token)
            .request_async(&self.http_client)
            .await;

        let token = match maybe_token {
            Ok(t) => t,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to refresh token"),
                    cause: e.to_string(),
                })
            }
        };

        let Some(expires_in) = token.expires_in() else {
            return Err(TidalClientError {
                msg: String::from("failed to refresh access token"),
                cause: String::from("expires_in was missing"),
            });
        };

        let expiry = Utc::now() + expires_in;

        Ok(AccessTokenWithExpiry {
            access_token: token.access_token().clone(),
            expiry,
        })
    }
}
#[async_trait::async_trait]
impl Middleware for AuthTokenRefreshMiddleware {
    async fn handle(
        &self,
        mut req: Request,
        extensions: &mut Extensions,
        next: Next<'_>,
    ) -> reqwest_middleware::Result<Response> {
        let token = match self.auth_provider.get_access_token() {
            Ok(t) => t.into_secret(),
            Err(AuthProviderError::TokenExpiredError) => {
                let token = match self.refresh_access_token().await {
                    Ok(t) => t,
                    Err(e) => {
                        return Err(reqwest_middleware::Error::middleware(TidalClientError {
                            msg: String::from("failed to refresh access token"),
                            cause: e.to_string(),
                        }))
                    }
                };

                match self.auth_provider.update_access_token(token.clone()) {
                    Ok(_) => {}
                    Err(e) => {
                        return Err(reqwest_middleware::Error::middleware(TidalClientError {
                            msg: String::from("failed to set new access token"),
                            cause: e.to_string(),
                        }))
                    }
                };

                token.access_token.into_secret()
            }
            Err(e) => {
                return Err(reqwest_middleware::Error::middleware(TidalClientError {
                    msg: String::from("failed to get access token from auth provider"),
                    cause: e.to_string(),
                }))
            }
        };

        let header = match HeaderValue::from_str(format!("Bearer {}", token).as_str()) {
            Ok(h) => h,
            Err(e) => {
                return Err(reqwest_middleware::Error::middleware(TidalClientError {
                    msg: String::from("failed to get access token from auth provider"),
                    cause: e.to_string(),
                }))
            }
        };

        req.headers_mut().insert("Authorization", header);

        next.run(req, extensions).await
    }
}

impl Deref for TidalClient {
    type Target = ApiClient;
    fn deref(&self) -> &Self::Target {
        &self.api_client
    }
}

fn to_scopes(scopes: Vec<&str>) -> Vec<Scope> {
    return scopes
        .into_iter()
        .map(|s| -> Scope { Scope::new(s.to_string()) })
        .collect();
}

impl TidalClient {
    fn api_client_from_token(
        oauth_http_client: reqwest::Client,
        oauth_client: OAuthClient,
        auth_token: Token,
    ) -> Result<ApiClient> {
        let api_http_client = reqwest::Client::new();
        let expiry = match DateTime::parse_from_rfc3339(&auth_token.expiry) {
            Ok(e) => e,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to parse expiry"),
                    cause: e.to_string(),
                })
            }
        }
        .to_utc();

        let auth_provider = AuthProvider {
            access_token: Arc::new(RwLock::new(AccessTokenWithExpiry {
                access_token: oauth2::AccessToken::new(auth_token.access_token),
                expiry,
            })),
            refresh_token: oauth2::RefreshToken::new(auth_token.refresh_token),
        };

        let refresh_middleware = AuthTokenRefreshMiddleware {
            auth_provider,
            http_client: oauth_http_client,
            oauth_client: oauth_client,
        };

        let middleware_client = ClientBuilder::new(api_http_client)
            .with(refresh_middleware)
            .build();

        Ok(ApiClient::new(Arc::new(Configuration {
            client: middleware_client,
            oauth_access_token: None,
            ..Default::default()
        })))
    }

    ///  Return a new copy of this client with updated or initialized token information.
    ///  Useful if you're using the client credentials flow to not have to duplicate configuration.
    ///
    ///  Example
    ///
    /// ```no_run
    /// use prawn::client::{TidalClient, TidalClientConfig, OAuthConfig};
    /// # use prawn::apis::Api;
    /// # smol::block_on(async {
    /// let client_id = "<your client id>";
    /// let client_secret = "<your client secret>";
    ///
    /// let redirect_uri = "https://example.com/callback";
    ///
    /// let config = TidalClientConfig {
    ///   oauth_config: OAuthConfig {
    ///       redirect_uri: redirect_uri.to_string(),
    ///       client_id: client_id.to_string(),
    ///       client_secret: Some(client_secret.to_string()),
    ///   },
    ///   auth_token: None, // we haven't authorized yet, so we  don't have  this.
    /// };
    ///
    /// let client = TidalClient::new(config)?;
    ///
    /// let scopes = vec!["user.read"];
    /// let token = client.exchange_client_credentials_for_token(scopes).await?;
    ///
    /// let client_with_token =  client.with_token(token)?;
    /// let resp = client_with_token.tracks_api().get_track("<some track id>", None, None, None).await;
    ///
    /// # Ok::<(), String>(())
    /// });
    /// ```
    pub fn with_token(self, auth_token: Token) -> Result<Self> {
        let api_client = Self::api_client_from_token(
            self.oauth_http_client.clone(),
            self.oauth_client.clone(),
            auth_token,
        )?;

        Ok(Self {
            api_client,
            oauth_client: self.oauth_client,
            oauth_http_client: self.oauth_http_client,
        })
    }

    /// Initializes a new TidalClient.
    ///
    /// If you provide token configuration, the TidalClient will manage refreshing tokens and updating its own token information from refreshed tokens.
    /// Otherwise, exposes helpful methods for initiating various OAuth flows.
    /// Right now the flows that are implemented are:
    ///     - PKCE Auth code
    ///     - Client credentials
    ///
    /// Examples
    ///
    /// # No token yet
    ///
    /// ```
    /// use prawn::client::{TidalClientConfig, TidalClient, OAuthConfig};
    /// let client_id = "<your client id>";
    ///
    /// let redirect_uri = "https://example.com/callback";
    ///
    /// let config = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: None
    ///     },
    ///     auth_token: None, // we haven't authorized yet, so we  don't have  this.
    /// };
    ///
    /// let client = TidalClient::new(config)?;
    ///
    /// let (challenge, verifier) = client.generate_pkce_challenge_and_verifier();
    ///
    /// let scopes = vec!["user.read"];
    ///
    /// let (auth_url, state) = client.get_authorize_url_and_state(challenge, scopes.to_vec());
    ///
    /// println!("visit {} to authorize", auth_url);
    /// # Ok::<(), String>(())
    /// ```
    ///
    ///
    /// ### Already have a token
    ///
    /// Will refresh your access_token in the background and update the token reference internally.
    ///
    /// ```no_run
    /// use prawn::client::{TidalClientConfig, TidalClient, OAuthConfig, Token};
    /// # use prawn::apis::Api;
    /// # smol::block_on(async {
    /// let client_id = "[client_id]";
    /// let redirect_uri = "https://example.com/callback";
    /// let scopes = vec!["user.read"];
    /// let token = Token {
    ///     access_token: String::from("[stored token]"),
    ///     refresh_token: String::from("[stored refresh token]"),
    ///     expiry:  String::from("[stored expiration info]")
    /// };
    ///
    /// let config_with_token = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: None,
    ///     },
    ///     auth_token: Some(token),
    /// };
    ///
    /// let client_with_token =  TidalClient::new(config_with_token)?;
    ///
    /// let resp = client_with_token.tracks_api().get_track("<some track id>", None, None, None).await;
    ///
    /// # Ok::<(), String>(())
    /// });
    /// ```
    pub fn new(config: TidalClientConfig) -> Result<Self> {
        let oauth_http_client = match oauth2::reqwest::ClientBuilder::new()
            .redirect(oauth2::reqwest::redirect::Policy::none())
            .build()
        {
            Ok(cb) => cb,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to build oauth http client"),
                    cause: e.to_string(),
                })
            }
        };

        let redirect_url = match RedirectUrl::new(config.oauth_config.redirect_uri.to_string()) {
            Ok(r) => r,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to parse redirect uri"),
                    cause: e.to_string(),
                })
            }
        };

        let auth_url = match AuthUrl::new(TIDAL_AUTH_URI.to_string()) {
            Ok(a) => a,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to parse auth uri"),
                    cause: e.to_string(),
                })
            }
        };

        let token_url = match TokenUrl::new(TIDAL_TOKEN_URI.to_string()) {
            Ok(a) => a,
            Err(e) => {
                return Err(TidalClientError {
                    msg: e.to_string(),
                    cause: e.to_string(),
                });
            }
        };

        let oauth_client = oauth2::basic::BasicClient::new(ClientId::new(
            config.oauth_config.client_id.to_string(),
        ))
        .set_redirect_uri(redirect_url)
        .set_auth_uri(auth_url)
        .set_token_uri(token_url);

        let oauth_client = match config.oauth_config.client_secret {
            Some(client_secret) => {
                oauth_client.set_client_secret(oauth2::ClientSecret::new(client_secret))
            }
            None => oauth_client,
        };

        let api_client = match config.auth_token {
            Some(auth_token) => Self::api_client_from_token(
                oauth_http_client.clone(),
                oauth_client.clone(),
                auth_token,
            )?,
            None => {
                let api_http_client = reqwest::Client::new();
                let middleware_client = ClientBuilder::new(api_http_client).build();
                ApiClient::new(Arc::new(Configuration {
                    client: middleware_client,
                    ..Default::default()
                }))
            }
        };

        return Ok(TidalClient {
            api_client: api_client,
            oauth_client,
            oauth_http_client,
        });
    }

    /// Generate a PKCE challenge code and verifier for use by [`TidalClient::get_authorize_url_and_state`] and [`TidalClient::exchange_code_for_token`]
    pub fn generate_pkce_challenge_and_verifier(&self) -> (PkceCodeChallenge, PkceCodeVerifier) {
        oauth2::PkceCodeChallenge::new_random_sha256()
    }

    /// Get the /authorize URL given a code challenge and scopes, returns
    /// URL as well as a CSRF state token
    ///
    /// Caller must generate PKCE challenge code and verifier separately
    /// because they should be used in subsequent requests. Use [`TidalClient::generate_pkce_challenge_and_verifier`]
    /// to generate challenge + verifier pair.
    ///
    /// The second return value is an [`oauth2::CsrfToken`] usually called `state` used to protect against cross-site request forgery.
    /// When the link generated by this function is followed, the state param will be passed back to your configured `redirect_uri`,
    /// where you can use it to verify that the state value you generated is the same one that is contained in the param.
    ///
    /// Example
    ///
    /// ```
    /// use prawn::client::{TidalClientConfig, TidalClient, OAuthConfig};
    /// let client_id = "<your client id>";
    ///
    /// let redirect_uri = "https://example.com/callback";
    ///
    /// let config = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: None
    ///     },
    ///     auth_token: None, // we haven't authorized yet, so we  don't have  this.
    /// };
    ///
    /// let client = TidalClient::new(config)?;
    ///
    /// let (challenge, verifier) = client.generate_pkce_challenge_and_verifier();
    ///
    /// let scopes = vec!["user.read"];
    ///
    /// let (auth_url, state) = client.get_authorize_url_and_state(challenge, scopes.to_vec());
    ///
    /// println!("visit {} to authorize", auth_url);
    ///
    /// # Ok::<(), String>(())
    /// ```
    pub fn get_authorize_url_and_state(
        &self,
        code_challenge: PkceCodeChallenge,
        scopes: Vec<&str>,
    ) -> (Url, CsrfToken) {
        let (url, csrf_token) = self
            .oauth_client
            .authorize_url(CsrfToken::new_random)
            .set_pkce_challenge(code_challenge)
            .add_scopes(to_scopes(scopes))
            .url();

        return (url, csrf_token);
    }

    /// Exchanges client_id and client_secret for an access token.
    ///
    /// Example
    ///
    /// ### Client Credentials flow
    ///
    /// ```no_run
    /// use prawn::client::{TidalClientConfig, TidalClient, OAuthConfig};
    /// # use prawn::apis::Api;
    /// # smol::block_on(async {
    /// let client_id = "<your client id>";
    /// let client_secret = "<your client secret>";
    ///
    /// let redirect_uri = "https://example.com/callback";
    ///
    /// let config = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: Some(client_secret.to_string()),
    ///     },
    ///     auth_token: None // we haven't authorized yet, so we  don't have  this.
    /// };
    ///
    /// let client = TidalClient::new(config)?;
    ///
    /// let scopes = vec!["user.read"];
    /// let token = client.exchange_client_credentials_for_token(scopes.to_vec()).await?;
    ///
    /// let config_with_token = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: None
    ///     },
    ///     auth_token: Some(token)
    /// };
    ///
    /// let client_with_token =  TidalClient::new(config_with_token)?;
    ///
    /// let resp = client_with_token.tracks_api().get_track("<some track id>", None, None, None).await;
    ///
    /// # Ok::<(), String>(())
    /// });
    /// ```
    pub async fn exchange_client_credentials_for_token(&self, scopes: Vec<&str>) -> Result<Token> {
        match self
            .oauth_client
            .exchange_client_credentials()
            .add_scopes(to_scopes(scopes))
            .request_async(&self.oauth_http_client)
            .await
        {
            Ok(resp) => Ok(resp.into()),
            Err(e) => Err(TidalClientError {
                msg: String::from("failed to exchange client credentials for token"),
                cause: e.to_string(),
            }),
        }
    }

    /// Calls the /token URL and returns an access and refresh token if the
    /// request is successful
    ///
    /// Example
    ///
    /// ### Exchange url for token and call API
    ///
    /// ```no_run
    /// use prawn::client::{TidalClientConfig, TidalClient, OAuthConfig, Token};
    /// # use prawn::apis::Api;
    /// # smol::block_on(async {
    /// // ... /callback implementation ...
    /// let code = "<extract from query params>";
    /// let verifier = "<stored somewhere>";
    ///
    /// let client_id = "<your client id>";
    ///
    /// let redirect_uri = "https://example.com/callback";
    ///
    /// let config = TidalClientConfig {
    ///     oauth_config: OAuthConfig {
    ///         redirect_uri: redirect_uri.to_string(),
    ///         client_id: client_id.to_string(),
    ///         client_secret: None
    ///     },
    ///     auth_token: None, // we haven't authorized yet, so we  don't have  this.
    /// };
    ///
    /// let client = TidalClient::new(config)?;
    ///
    /// let token: Token = client.exchange_code_for_token(verifier.to_string(), code.to_string()).await?;
    ///
    /// let client_with_token =  client.with_token(token)?;
    ///
    /// let resp = client_with_token.tracks_api().get_track("<some track id>", None, None, None).await;
    ///
    /// # Ok::<(), String>(())
    /// });
    /// ```
    pub async fn exchange_code_for_token(
        &self,
        code_verifier: String,
        code: String,
    ) -> Result<Token> {
        let verifier = PkceCodeVerifier::new(code_verifier);
        let auth_code = AuthorizationCode::new(code);
        let resp = self
            .oauth_client
            .exchange_code(auth_code)
            .set_pkce_verifier(verifier)
            .request_async(&self.oauth_http_client)
            .await;

        let token_resp = match resp {
            Ok(t) => t,
            Err(e) => {
                return Err(TidalClientError {
                    msg: String::from("failed to exchange auth code"),
                    cause: e.to_string(),
                })
            }
        };

        let Some(refresh_token) = token_resp.refresh_token() else {
            return Err(TidalClientError {
                msg: String::from("failed to exchange auth code"),
                cause: String::from("response missing refresh token"),
            });
        };

        let Some(expires_in) = token_resp.expires_in() else {
            return Err(TidalClientError {
                msg: String::from("failed to exchange auth code"),
                cause: String::from("response missing expires_in"),
            });
        };

        let expiry = Utc::now() + expires_in;

        Ok(Token {
            access_token: token_resp.access_token().clone().into_secret(),
            refresh_token: refresh_token.clone().into_secret(),
            expiry: expiry.to_rfc3339(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    static SCOPES: &'static [&'static str] = &["user.read", "user.write"];

    mod get_authorize_url_and_state {
        use super::*;

        #[test]
        fn test_get_authorize_url_adds_configured_values() -> std::result::Result<(), String> {
            let redirect_uri = "https://example.com/callback";
            let client_id = "abc123";

            let client_config = TidalClientConfig {
                oauth_config: OAuthConfig {
                    redirect_uri: String::from(redirect_uri),
                    client_id: String::from(client_id),
                    client_secret: None,
                },
                auth_token: None,
            };

            let client = TidalClient::new(client_config)?;

            let (challenge, _verifier) = client.generate_pkce_challenge_and_verifier();

            let (authorize_url, state) =
                client.get_authorize_url_and_state(challenge.clone(), SCOPES.to_vec());

            let has_redirect_uri = authorize_url
                .query_pairs()
                .any(|(name, val)| -> bool { name == "redirect_uri" && val == redirect_uri });

            let has_client_id = authorize_url
                .query_pairs()
                .any(|(name, val)| -> bool { name == "client_id" && val == client_id });

            let has_scopes = authorize_url
                .query_pairs()
                .any(|(name, val)| -> bool { name == "scope" && val == SCOPES.join(" ") });

            let has_state = authorize_url.query_pairs().any(|(name, val)| -> bool {
                name == "state" && val == state.clone().into_secret()
            });

            let has_challenge = authorize_url.query_pairs().any(|(name, val)| -> bool {
                name == "code_challenge" && val == challenge.as_str()
            });
            assert!(has_redirect_uri);
            assert!(has_client_id);
            assert!(has_scopes);
            assert!(has_state);
            assert!(has_challenge);
            Ok(())
        }
    }

    mod test_auth_refresh_middleware {
        use std::time::Duration;

        use super::*;
        use httptest::{matchers::*, responders::*, Expectation, Server};
        use oauth2::AccessToken;
        use reqwest::header::AUTHORIZATION;

        struct TestMiddleware {
            auth_header: String,
        }

        #[async_trait::async_trait]
        impl Middleware for TestMiddleware {
            async fn handle(
                &self,
                req: Request,
                extensions: &mut Extensions,
                next: Next<'_>,
            ) -> reqwest_middleware::Result<Response> {
                assert_eq!(
                    req.headers()
                        .get(AUTHORIZATION)
                        .expect("missing auth header"),
                    format!("Bearer {}", self.auth_header).as_str()
                );
                next.run(req, extensions).await
            }
        }

        #[tokio::test]
        async fn test_auth_refresh_middleware_refreshes_expires_tokens(
        ) -> std::result::Result<(), String> {
            let server = Server::run();

            let client_id = "1234567";
            let path = "/v1/oauth/token";
            let token_url = TokenUrl::from_url(
                Url::parse(server.url(path).to_string().as_str()).expect("failed to  parse url"),
            );

            server.expect(
                Expectation::matching(all_of![request::method_path("POST", path)]).respond_with(
                    status_code(200).body(
                        r#"{
                    "access_token": "abc123",
                    "token_type": "Bearer",
                    "expires_in": 86400,
                    "scope": "user.read"
                }"#,
                    ),
                ),
            );

            let oauth_client =
                oauth2::basic::BasicClient::new(ClientId::new(client_id.to_string()))
                    .set_redirect_uri(RedirectUrl::from_url(
                        Url::parse("https://example.com/callback").expect("failed to parse url"),
                    ))
                    .set_auth_uri(AuthUrl::from_url(
                        Url::parse("https://example.com/authorize").expect("failed to parse url"),
                    ))
                    .set_token_uri(token_url);

            let oauth_http_client = match oauth2::reqwest::ClientBuilder::new()
                .redirect(oauth2::reqwest::redirect::Policy::none())
                .build()
            {
                Ok(cb) => cb,
                Err(e) => {
                    panic!("failed to build oauth http client: {}", e)
                }
            };

            let refresh_token = "refreshing!";
            let auth_provider = AuthProvider {
                access_token: Arc::new(RwLock::new(AccessTokenWithExpiry {
                    access_token: AccessToken::new("def456".to_string()),
                    expiry: Utc::now() - Duration::from_millis(1),
                })),
                refresh_token: RefreshToken::new(refresh_token.to_string()),
            };

            let middleware = AuthTokenRefreshMiddleware {
                oauth_client,
                http_client: oauth_http_client,
                auth_provider: auth_provider.clone(),
            };

            let test_middleware = TestMiddleware {
                auth_header: "abc123".to_string(),
            };

            let http_client = reqwest::Client::new();

            let client = reqwest_middleware::ClientBuilder::new(http_client)
                .with(middleware)
                .with(test_middleware)
                .build();

            _ = client
                .get(Url::parse("https://example.com").expect("failed to parse url"))
                .send()
                .await
                .expect("oh no!");

            assert_eq!(
                auth_provider
                    .clone()
                    .access_token
                    .read()
                    .expect("unable to lock")
                    .access_token
                    .clone()
                    .into_secret(),
                "abc123".to_string()
            );
            Ok(())
        }

        #[tokio::test]
        async fn test_auth_refresh_middleware_does_not_refresh_unexpired_toknes(
        ) -> std::result::Result<(), String> {
            let server = Server::run();

            let client_id = "1234567";
            let path = "/v1/oauth/token";
            let token_url = TokenUrl::from_url(
                Url::parse(server.url(path).to_string().as_str()).expect("failed to  parse url"),
            );

            let oauth_client =
                oauth2::basic::BasicClient::new(ClientId::new(client_id.to_string()))
                    .set_redirect_uri(RedirectUrl::from_url(
                        Url::parse("https://example.com/callback").expect("failed to parse url"),
                    ))
                    .set_auth_uri(AuthUrl::from_url(
                        Url::parse("https://example.com/authorize").expect("failed to parse url"),
                    ))
                    .set_token_uri(token_url);

            let oauth_http_client = match oauth2::reqwest::ClientBuilder::new()
                .redirect(oauth2::reqwest::redirect::Policy::none())
                .build()
            {
                Ok(cb) => cb,
                Err(e) => {
                    panic!("failed to build oauth http client: {}", e)
                }
            };

            let refresh_token = "refreshing!";
            let auth_provider = AuthProvider {
                access_token: Arc::new(RwLock::new(AccessTokenWithExpiry {
                    access_token: AccessToken::new("def456".to_string()),
                    expiry: Utc::now() + Duration::from_millis(86400),
                })),
                refresh_token: RefreshToken::new(refresh_token.to_string()),
            };

            let middleware = AuthTokenRefreshMiddleware {
                oauth_client,
                http_client: oauth_http_client,
                auth_provider: auth_provider.clone(),
            };

            let test_middleware = TestMiddleware {
                auth_header: "def456".to_string(),
            };

            let http_client = reqwest::Client::new();

            let client = reqwest_middleware::ClientBuilder::new(http_client)
                .with(middleware)
                .with(test_middleware)
                .build();

            _ = client
                .get(Url::parse("https://example.com").expect("failed to parse url"))
                .send()
                .await
                .expect("oh no!");

            assert_eq!(
                auth_provider
                    .clone()
                    .access_token
                    .read()
                    .expect("unable to lock")
                    .access_token
                    .clone()
                    .into_secret(),
                "def456".to_string()
            );
            Ok(())
        }
    }
}