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
use crate::{
    auth_urls,
    clients::{
        convert_result,
        pagination::{paginate, paginate_with_ctx, Paginator},
    },
    http::{BaseHttpClient, Form, Headers, HttpClient, Query},
    join_ids,
    model::*,
    sync::Mutex,
    util::build_map,
    ClientError, ClientResult, Config, Credentials, Token,
};

use std::{collections::HashMap, fmt, ops::Not, sync::Arc};

use chrono::Utc;
use maybe_async::maybe_async;
use serde_json::Value;

/// This trait implements the basic endpoints from the Spotify API that may be
/// accessed without user authorization, including parts of the authentication
/// flow that are shared, and the endpoints.
#[cfg_attr(target_arch = "wasm32", maybe_async(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), maybe_async)]
pub trait BaseClient
where
    Self: Send + Sync + Default + Clone + fmt::Debug,
{
    fn get_config(&self) -> &Config;
    fn get_http(&self) -> &HttpClient;
    fn get_creds(&self) -> &Credentials;

    /// Note that the token is wrapped by a `Mutex` in order to allow interior
    /// mutability. This is required so that the entire client doesn't have to
    /// be mutable (the token is accessed to from every endpoint).
    fn get_token(&self) -> Arc<Mutex<Option<Token>>>;

    /// Returns the absolute URL for an endpoint in the API.
    fn api_url(&self, url: &str) -> String {
        let mut base = self.get_config().api_base_url.clone();
        if !base.ends_with('/') {
            base.push('/');
        }
        base + url
    }

    /// Returns the absolute URL for an authentication step in the API.
    fn auth_url(&self, url: &str) -> String {
        let mut base = self.get_config().auth_base_url.clone();
        if !base.ends_with('/') {
            base.push('/');
        }
        base + url
    }

    /// Refetch the current access token given a refresh token.
    async fn refetch_token(&self) -> ClientResult<Option<Token>>;

    /// Re-authenticate the client automatically if it's configured to do so,
    /// which uses the refresh token to obtain a new access token.
    async fn auto_reauth(&self) -> ClientResult<()> {
        if !self.get_config().token_refreshing {
            return Ok(());
        }

        // NOTE: It's important to not leave the token locked, or else a
        // deadlock when calling `refresh_token` will occur.
        let should_reauth = self
            .get_token()
            .lock()
            .await
            .unwrap()
            .as_ref()
            .map_or(false, Token::is_expired);

        if should_reauth {
            self.refresh_token().await
        } else {
            Ok(())
        }
    }

    /// Refreshes the current access token given a refresh token. The obtained
    /// token will be saved internally.
    async fn refresh_token(&self) -> ClientResult<()> {
        let token = self.refetch_token().await?;
        *self.get_token().lock().await.unwrap() = token;
        self.write_token_cache().await
    }

    /// The headers required for authenticated requests to the API.
    ///
    /// Since this is accessed by authenticated requests always, it's where the
    /// automatic reauthentication takes place, if enabled.
    #[doc(hidden)]
    async fn auth_headers(&self) -> ClientResult<Headers> {
        self.auto_reauth().await?;

        Ok(self
            .get_token()
            .lock()
            .await
            .unwrap()
            .as_ref()
            .ok_or(ClientError::InvalidToken)?
            .auth_headers())
    }

    // HTTP-related methods for the Spotify client. They wrap up the basic HTTP
    // client with its specific usage for endpoints or authentication.

    /// Convenience method to send GET requests related to an endpoint in the
    /// API.
    #[doc(hidden)]
    #[inline]
    async fn api_get(&self, url: &str, payload: &Query<'_>) -> ClientResult<String> {
        let url = self.api_url(url);
        let headers = self.auth_headers().await?;
        Ok(self.get_http().get(&url, Some(&headers), payload).await?)
    }

    /// Convenience method to send POST requests related to an endpoint in the
    /// API.
    #[doc(hidden)]
    #[inline]
    async fn api_post(&self, url: &str, payload: &Value) -> ClientResult<String> {
        let url = self.api_url(url);
        let headers = self.auth_headers().await?;
        Ok(self.get_http().post(&url, Some(&headers), payload).await?)
    }

    /// Convenience method to send PUT requests related to an endpoint in the
    /// API.
    #[doc(hidden)]
    #[inline]
    async fn api_put(&self, url: &str, payload: &Value) -> ClientResult<String> {
        let url = self.api_url(url);
        let headers = self.auth_headers().await?;
        Ok(self.get_http().put(&url, Some(&headers), payload).await?)
    }

    /// Convenience method to send DELETE requests related to an endpoint in the
    /// API.
    #[doc(hidden)]
    #[inline]
    async fn api_delete(&self, url: &str, payload: &Value) -> ClientResult<String> {
        let url = self.api_url(url);
        let headers = self.auth_headers().await?;
        Ok(self
            .get_http()
            .delete(&url, Some(&headers), payload)
            .await?)
    }

    /// Convenience method to send POST requests related to the authentication
    /// process.
    #[doc(hidden)]
    #[inline]
    async fn auth_post(
        &self,
        url: &str,
        headers: Option<&Headers>,
        payload: &Form<'_>,
    ) -> ClientResult<String> {
        let url = self.auth_url(url);
        Ok(self.get_http().post_form(&url, headers, payload).await?)
    }

    /// Updates the cache file at the internal cache path.
    ///
    /// This should be used whenever it's possible to, even if the cached token
    /// isn't configured, because this will already check `Config::token_cached`
    /// and do nothing in that case already.
    async fn write_token_cache(&self) -> ClientResult<()> {
        if !self.get_config().token_cached {
            log::info!("Token cache write ignored (not configured)");
            return Ok(());
        }

        log::info!("Writing token cache");
        if let Some(tok) = self.get_token().lock().await.unwrap().as_ref() {
            tok.write_cache(&self.get_config().cache_path)?;
        }

        Ok(())
    }

    /// Sends a request to Spotify for an access token.
    async fn fetch_access_token(
        &self,
        payload: &Form<'_>,
        headers: Option<&Headers>,
    ) -> ClientResult<Token> {
        let response = self.auth_post(auth_urls::TOKEN, headers, payload).await?;

        let mut tok = serde_json::from_str::<Token>(&response)?;
        tok.expires_at = Utc::now().checked_add_signed(tok.expires_in);
        Ok(tok)
    }

    /// Returns a single track given the track's ID, URI or URL.
    ///
    /// Parameters:
    /// - track_id - a spotify URI, URL or ID
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-track)
    async fn track(
        &self,
        track_id: TrackId<'_>,
        market: Option<Market>,
    ) -> ClientResult<FullTrack> {
        let params = build_map([("market", market.map(Into::into))]);

        let url = format!("tracks/{}", track_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Returns a list of tracks given a list of track IDs, URIs, or URLs.
    ///
    /// Parameters:
    /// - track_ids - a list of spotify URIs, URLs or IDs
    /// - market - an ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-several-tracks)
    async fn tracks<'a>(
        &self,
        track_ids: impl IntoIterator<Item = TrackId<'a>> + Send + 'a,
        market: Option<Market>,
    ) -> ClientResult<Vec<FullTrack>> {
        let ids = join_ids(track_ids);
        let params = build_map([("market", market.map(Into::into))]);

        let url = format!("tracks/?ids={ids}");
        let result = self.api_get(&url, &params).await?;
        convert_result::<FullTracks>(&result).map(|x| x.tracks)
    }

    /// Returns a single artist given the artist's ID, URI or URL.
    ///
    /// Parameters:
    /// - artist_id - an artist ID, URI or URL
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-artist)
    async fn artist(&self, artist_id: ArtistId<'_>) -> ClientResult<FullArtist> {
        let url = format!("artists/{}", artist_id.id());
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result(&result)
    }

    /// Returns a list of artists given the artist IDs, URIs, or URLs.
    ///
    /// Parameters:
    /// - artist_ids - a list of artist IDs, URIs or URLs
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-multiple-artists)
    async fn artists<'a>(
        &self,
        artist_ids: impl IntoIterator<Item = ArtistId<'a>> + Send + 'a,
    ) -> ClientResult<Vec<FullArtist>> {
        let ids = join_ids(artist_ids);
        let url = format!("artists/?ids={ids}");
        let result = self.api_get(&url, &Query::new()).await?;

        convert_result::<FullArtists>(&result).map(|x| x.artists)
    }

    /// Get Spotify catalog information about an artist's albums.
    ///
    /// Parameters:
    /// - artist_id - the artist ID, URI or URL
    /// - include_groups -  a list of album type like 'album', 'single' that will be used to filter response. if not supplied, all album types will be returned.
    /// - market - limit the response to one particular country.
    /// - limit  - the number of albums to return
    /// - offset - the index of the first album to return
    ///
    /// See [`Self::artist_albums_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-artists-albums)
    fn artist_albums<'a>(
        &'a self,
        artist_id: ArtistId<'a>,
        include_groups: impl IntoIterator<Item = AlbumType> + Send + Copy + 'a,
        market: Option<Market>,
    ) -> Paginator<'_, ClientResult<SimplifiedAlbum>> {
        paginate_with_ctx(
            (self, artist_id),
            move |(slf, artist_id), limit, offset| {
                slf.artist_albums_manual(
                    artist_id.as_ref(),
                    include_groups,
                    market,
                    Some(limit),
                    Some(offset),
                )
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::artist_albums`].
    async fn artist_albums_manual<'a>(
        &self,
        artist_id: ArtistId<'_>,
        include_groups: impl IntoIterator<Item = AlbumType> + Send + 'a,
        market: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedAlbum>> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let include_groups_vec = include_groups
            .into_iter()
            .map(|t| t.into())
            .collect::<Vec<&'static str>>();
        let include_groups_opt = include_groups_vec
            .is_empty()
            .not()
            .then_some(include_groups_vec)
            .map(|t| t.join(","));

        let params = build_map([
            ("include_groups", include_groups_opt.as_deref()),
            ("market", market.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let url = format!("artists/{}/albums", artist_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information about an artist's top 10 tracks by
    /// country.
    ///
    /// Parameters:
    /// - artist_id - the artist ID, URI or URL
    /// - market - limit the response to one particular country.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-artists-top-tracks)
    async fn artist_top_tracks(
        &self,
        artist_id: ArtistId<'_>,
        market: Option<Market>,
    ) -> ClientResult<Vec<FullTrack>> {
        let params = build_map([("market", market.map(Into::into))]);

        let url = format!("artists/{}/top-tracks", artist_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result::<FullTracks>(&result).map(|x| x.tracks)
    }

    /// Get Spotify catalog information about artists similar to an identified
    /// artist. Similarity is based on analysis of the Spotify community's
    /// listening history.
    ///
    /// Parameters:
    /// - artist_id - the artist ID, URI or URL
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-artists-related-artists)
    async fn artist_related_artists(
        &self,
        artist_id: ArtistId<'_>,
    ) -> ClientResult<Vec<FullArtist>> {
        let url = format!("artists/{}/related-artists", artist_id.id());
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result::<FullArtists>(&result).map(|x| x.artists)
    }

    /// Returns a single album given the album's ID, URIs or URL.
    ///
    /// Parameters:
    /// - album_id - the album ID, URI or URL
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-album)
    async fn album(
        &self,
        album_id: AlbumId<'_>,
        market: Option<Market>,
    ) -> ClientResult<FullAlbum> {
        let params = build_map([("market", market.map(Into::into))]);

        let url = format!("albums/{}", album_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Returns a list of albums given the album IDs, URIs, or URLs.
    ///
    /// Parameters:
    /// - albums_ids - a list of album IDs, URIs or URLs
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-multiple-albums)
    async fn albums<'a>(
        &self,
        album_ids: impl IntoIterator<Item = AlbumId<'a>> + Send + 'a,
        market: Option<Market>,
    ) -> ClientResult<Vec<FullAlbum>> {
        let params = build_map([("market", market.map(Into::into))]);

        let ids = join_ids(album_ids);
        let url = format!("albums/?ids={ids}");
        let result = self.api_get(&url, &params).await?;
        convert_result::<FullAlbums>(&result).map(|x| x.albums)
    }

    /// Search for an Item. Get Spotify catalog information about artists,
    /// albums, tracks or playlists that match a keyword string.
    ///
    /// Parameters:
    /// - q - the search query
    /// - limit  - the number of items to return
    /// - offset - the index of the first item to return
    /// - type - the type of item to return. One of 'artist', 'album', 'track',
    ///  'playlist', 'show' or 'episode'
    /// - market - An ISO 3166-1 alpha-2 country code or the string from_token.
    /// - include_external: Optional.Possible values: audio. If
    ///   include_external=audio is specified the response will include any
    ///   relevant audio content that is hosted externally.  
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/search)
    async fn search(
        &self,
        q: &str,
        _type: SearchType,
        market: Option<Market>,
        include_external: Option<IncludeExternal>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<SearchResult> {
        let limit = limit.map(|s| s.to_string());
        let offset = offset.map(|s| s.to_string());
        let params = build_map([
            ("q", Some(q)),
            ("type", Some(_type.into())),
            ("market", market.map(Into::into)),
            ("include_external", include_external.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let result = self.api_get("search", &params).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information about an album's tracks.
    ///
    /// Parameters:
    /// - album_id - the album ID, URI or URL
    /// - limit  - the number of items to return
    /// - offset - the index of the first item to return
    ///
    /// See [`Self::album_track_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-albums-tracks)
    fn album_track<'a>(
        &'a self,
        album_id: AlbumId<'a>,
        market: Option<Market>,
    ) -> Paginator<'_, ClientResult<SimplifiedTrack>> {
        paginate_with_ctx(
            (self, album_id),
            move |(slf, album_id), limit, offset| {
                slf.album_track_manual(album_id.as_ref(), market, Some(limit), Some(offset))
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::album_track`].
    async fn album_track_manual(
        &self,
        album_id: AlbumId<'_>,
        market: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedTrack>> {
        let limit = limit.map(|s| s.to_string());
        let offset = offset.map(|s| s.to_string());
        let params = build_map([
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
            ("market", market.map(Into::into)),
        ]);

        let url = format!("albums/{}/tracks", album_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Gets basic profile information about a Spotify User.
    ///
    /// Parameters:
    /// - user - the id of the usr
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-profile)
    async fn user(&self, user_id: UserId<'_>) -> ClientResult<PublicUser> {
        let url = format!("users/{}", user_id.id());
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result(&result)
    }

    /// Get full details about Spotify playlist.
    ///
    /// Parameters:
    /// - playlist_id - the id of the playlist
    /// - market - an ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-playlist)
    async fn playlist(
        &self,
        playlist_id: PlaylistId<'_>,
        fields: Option<&str>,
        market: Option<Market>,
    ) -> ClientResult<FullPlaylist> {
        let params = build_map([("fields", fields), ("market", market.map(Into::into))]);

        let url = format!("playlists/{}", playlist_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Gets playlist of a user.
    ///
    /// Parameters:
    /// - user_id - the id of the user
    /// - playlist_id - the id of the playlist
    /// - fields - which fields to return
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-list-users-playlists)
    async fn user_playlist(
        &self,
        user_id: UserId<'_>,
        playlist_id: Option<PlaylistId<'_>>,
        fields: Option<&str>,
    ) -> ClientResult<FullPlaylist> {
        let params = build_map([("fields", fields)]);

        let url = match playlist_id {
            Some(playlist_id) => format!("users/{}/playlists/{}", user_id.id(), playlist_id.id()),
            None => format!("users/{}/starred", user_id.id()),
        };
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Check to see if the given users are following the given playlist.
    ///
    /// Parameters:
    /// - playlist_id - the id of the playlist
    /// - user_ids - the ids of the users that you want to check to see if they
    ///   follow the playlist. Maximum: 5 ids.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/check-if-user-follows-playlist)
    async fn playlist_check_follow(
        &self,
        playlist_id: PlaylistId<'_>,
        user_ids: &[UserId<'_>],
    ) -> ClientResult<Vec<bool>> {
        debug_assert!(
            user_ids.len() <= 5,
            "The maximum length of user ids is limited to 5 :-)"
        );
        let url = format!(
            "playlists/{}/followers/contains?ids={}",
            playlist_id.id(),
            user_ids.iter().map(Id::id).collect::<Vec<_>>().join(","),
        );
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information for a single show identified by its unique Spotify ID.
    ///
    /// Path Parameters:
    /// - id: The Spotify ID for the show.
    ///
    /// Query Parameters
    /// - market(Optional): An ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-show)
    async fn get_a_show(&self, id: ShowId<'_>, market: Option<Market>) -> ClientResult<FullShow> {
        let params = build_map([("market", market.map(Into::into))]);

        let url = format!("shows/{}", id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information for multiple shows based on their
    /// Spotify IDs.
    ///
    /// Query Parameters
    /// - ids(Required) A comma-separated list of the Spotify IDs for the shows. Maximum: 50 IDs.
    /// - market(Optional) An ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-multiple-shows)
    async fn get_several_shows<'a>(
        &self,
        ids: impl IntoIterator<Item = ShowId<'a>> + Send + 'a,
        market: Option<Market>,
    ) -> ClientResult<Vec<SimplifiedShow>> {
        let ids = join_ids(ids);
        let params = build_map([("ids", Some(&ids)), ("market", market.map(Into::into))]);

        let result = self.api_get("shows", &params).await?;
        convert_result::<SeversalSimplifiedShows>(&result).map(|x| x.shows)
    }

    /// Get Spotify catalog information about an show’s episodes. Optional
    /// parameters can be used to limit the number of episodes returned.
    ///
    /// Path Parameters
    /// - id: The Spotify ID for the show.
    ///
    /// Query Parameters
    /// - limit: Optional. The maximum number of episodes to return. Default: 20. Minimum: 1. Maximum: 50.
    /// - offset: Optional. The index of the first episode to return. Default: 0 (the first object). Use with limit to get the next set of episodes.
    /// - market: Optional. An ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// See [`Self::get_shows_episodes_manual`] for a manually paginated version
    /// of this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-shows-episodes)
    fn get_shows_episodes<'a>(
        &'a self,
        id: ShowId<'a>,
        market: Option<Market>,
    ) -> Paginator<'_, ClientResult<SimplifiedEpisode>> {
        paginate_with_ctx(
            (self, id),
            move |(slf, id), limit, offset| {
                slf.get_shows_episodes_manual(id.as_ref(), market, Some(limit), Some(offset))
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::get_shows_episodes`].
    async fn get_shows_episodes_manual(
        &self,
        id: ShowId<'_>,
        market: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedEpisode>> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let params = build_map([
            ("market", market.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let url = format!("shows/{}/episodes", id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information for a single episode identified by its unique Spotify ID.
    ///
    /// Path Parameters
    /// - id: The Spotify ID for the episode.
    ///
    /// Query Parameters
    /// - market: Optional. An ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-an-episode)
    async fn get_an_episode(
        &self,
        id: EpisodeId<'_>,
        market: Option<Market>,
    ) -> ClientResult<FullEpisode> {
        let url = format!("episodes/{}", id.id());
        let params = build_map([("market", market.map(Into::into))]);

        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Get Spotify catalog information for multiple episodes based on their Spotify IDs.
    ///
    /// Query Parameters
    /// - ids: Required. A comma-separated list of the Spotify IDs for the episodes. Maximum: 50 IDs.
    /// - market: Optional. An ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-multiple-episodes)
    async fn get_several_episodes<'a>(
        &self,
        ids: impl IntoIterator<Item = EpisodeId<'a>> + Send + 'a,
        market: Option<Market>,
    ) -> ClientResult<Vec<FullEpisode>> {
        let ids = join_ids(ids);
        let params = build_map([("ids", Some(&ids)), ("market", market.map(Into::into))]);

        let result = self.api_get("episodes", &params).await?;
        convert_result::<EpisodesPayload>(&result).map(|x| x.episodes)
    }

    /// Get audio features for a track
    ///
    /// Parameters:
    /// - track - track URI, URL or ID
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-audio-features)
    async fn track_features(&self, track_id: TrackId<'_>) -> ClientResult<AudioFeatures> {
        let url = format!("audio-features/{}", track_id.id());
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result(&result)
    }

    /// Get Audio Features for Several Tracks
    ///
    /// Parameters:
    /// - tracks a list of track URIs, URLs or IDs
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-several-audio-features)
    async fn tracks_features<'a>(
        &self,
        track_ids: impl IntoIterator<Item = TrackId<'a>> + Send + 'a,
    ) -> ClientResult<Option<Vec<AudioFeatures>>> {
        let url = format!("audio-features/?ids={}", join_ids(track_ids));

        let result = self.api_get(&url, &Query::new()).await?;
        if result.is_empty() {
            Ok(None)
        } else if let Some(payload) = convert_result::<Option<AudioFeaturesPayload>>(&result)? {
            let audio_features = payload.audio_features.into_iter().flatten().collect();
            Ok(Some(audio_features))
        } else {
            Ok(None)
        }
    }

    /// Get Audio Analysis for a Track
    ///
    /// Parameters:
    /// - track_id - a track URI, URL or ID
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-audio-analysis)
    async fn track_analysis(&self, track_id: TrackId<'_>) -> ClientResult<AudioAnalysis> {
        let url = format!("audio-analysis/{}", track_id.id());
        let result = self.api_get(&url, &Query::new()).await?;
        convert_result(&result)
    }

    /// Get a list of new album releases featured in Spotify
    ///
    /// Parameters:
    /// - country - An ISO 3166-1 alpha-2 country code or string from_token.
    /// - locale - The desired language, consisting of an ISO 639 language code
    ///   and an ISO 3166-1 alpha-2 country code, joined by an underscore.
    /// - limit - The maximum number of items to return. Default: 20.
    ///   Minimum: 1. Maximum: 50
    /// - offset - The index of the first item to return. Default: 0 (the first
    ///   object). Use with limit to get the next set of items.
    ///
    /// See [`Self::categories_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-categories)
    fn categories<'a>(
        &'a self,
        locale: Option<&'a str>,
        country: Option<Market>,
    ) -> Paginator<'_, ClientResult<Category>> {
        paginate(
            move |limit, offset| self.categories_manual(locale, country, Some(limit), Some(offset)),
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::categories`].
    async fn categories_manual(
        &self,
        locale: Option<&str>,
        country: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<Category>> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let params = build_map([
            ("locale", locale),
            ("country", country.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);
        let result = self.api_get("browse/categories", &params).await?;
        convert_result::<PageCategory>(&result).map(|x| x.categories)
    }

    /// Get a list of playlists in a category in Spotify
    ///
    /// Parameters:
    /// - category_id - The category id to get playlists from.
    /// - country - An ISO 3166-1 alpha-2 country code or the string from_token.
    /// - limit - The maximum number of items to return. Default: 20.
    ///   Minimum: 1. Maximum: 50
    /// - offset - The index of the first item to return. Default: 0 (the first
    ///   object). Use with limit to get the next set of items.
    ///
    /// See [`Self::category_playlists_manual`] for a manually paginated version
    /// of this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-categories-playlists)
    fn category_playlists<'a>(
        &'a self,
        category_id: &'a str,
        country: Option<Market>,
    ) -> Paginator<'_, ClientResult<SimplifiedPlaylist>> {
        paginate(
            move |limit, offset| {
                self.category_playlists_manual(category_id, country, Some(limit), Some(offset))
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::category_playlists`].
    async fn category_playlists_manual(
        &self,
        category_id: &str,
        country: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedPlaylist>> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let params = build_map([
            ("country", country.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let url = format!("browse/categories/{category_id}/playlists");
        let result = self.api_get(&url, &params).await?;
        convert_result::<CategoryPlaylists>(&result).map(|x| x.playlists)
    }

    /// Get a list of Spotify featured playlists.
    ///
    /// Parameters:
    /// - locale - The desired language, consisting of a lowercase ISO 639
    ///   language code and an uppercase ISO 3166-1 alpha-2 country code,
    ///   joined by an underscore.
    /// - country - An ISO 3166-1 alpha-2 country code or the string from_token.
    /// - timestamp - A timestamp in ISO 8601 format: yyyy-MM-ddTHH:mm:ss. Use
    ///   this parameter to specify the user's local time to get results
    ///   tailored for that specific date and time in the day
    /// - limit - The maximum number of items to return. Default: 20.
    ///   Minimum: 1. Maximum: 50
    /// - offset - The index of the first item to return. Default: 0
    ///   (the first object). Use with limit to get the next set of
    ///   items.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-featured-playlists)
    async fn featured_playlists(
        &self,
        locale: Option<&str>,
        country: Option<Market>,
        timestamp: Option<chrono::DateTime<chrono::Utc>>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<FeaturedPlaylists> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let timestamp = timestamp.map(|x| x.to_rfc3339());
        let params = build_map([
            ("locale", locale),
            ("country", country.map(Into::into)),
            ("timestamp", timestamp.as_deref()),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let result = self.api_get("browse/featured-playlists", &params).await?;
        convert_result(&result)
    }

    /// Get a list of new album releases featured in Spotify.
    ///
    /// Parameters:
    /// - country - An ISO 3166-1 alpha-2 country code or string from_token.
    /// - limit - The maximum number of items to return. Default: 20.
    ///   Minimum: 1. Maximum: 50
    /// - offset - The index of the first item to return. Default: 0 (the first
    ///   object). Use with limit to get the next set of items.
    ///
    /// See [`Self::new_releases_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-new-releases)
    fn new_releases(
        &self,
        country: Option<Market>,
    ) -> Paginator<'_, ClientResult<SimplifiedAlbum>> {
        paginate(
            move |limit, offset| self.new_releases_manual(country, Some(limit), Some(offset)),
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::new_releases`].
    async fn new_releases_manual(
        &self,
        country: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedAlbum>> {
        let limit = limit.map(|x| x.to_string());
        let offset = offset.map(|x| x.to_string());
        let params = build_map([
            ("country", country.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let result = self.api_get("browse/new-releases", &params).await?;
        convert_result::<PageSimplifiedAlbums>(&result).map(|x| x.albums)
    }

    /// Get Recommendations Based on Seeds
    ///
    /// Parameters:
    /// - attributes - restrictions on attributes for the selected tracks, such
    ///   as `min_acousticness` or `target_duration_ms`.
    /// - seed_artists - a list of artist IDs, URIs or URLs
    /// - seed_tracks - a list of artist IDs, URIs or URLs
    /// - seed_genres - a list of genre names. Available genres for
    /// - market - An ISO 3166-1 alpha-2 country code or the string from_token.
    ///   If provided, all results will be playable in this country.
    /// - limit - The maximum number of items to return. Default: 20.
    ///   Minimum: 1. Maximum: 100
    /// - `min/max/target_<attribute>` - For the tuneable track attributes
    ///   listed in the documentation, these values provide filters and
    ///   targeting on results.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-recommendations)
    async fn recommendations<'a>(
        &self,
        attributes: impl IntoIterator<Item = RecommendationsAttribute> + Send + 'a,
        seed_artists: Option<impl IntoIterator<Item = ArtistId<'a>> + Send + 'a>,
        seed_genres: Option<impl IntoIterator<Item = &'a str> + Send + 'a>,
        seed_tracks: Option<impl IntoIterator<Item = TrackId<'a>> + Send + 'a>,
        market: Option<Market>,
        limit: Option<u32>,
    ) -> ClientResult<Recommendations> {
        let seed_artists = seed_artists.map(join_ids);
        let seed_genres = seed_genres.map(|x| x.into_iter().collect::<Vec<_>>().join(","));
        let seed_tracks = seed_tracks.map(join_ids);
        let limit = limit.map(|x| x.to_string());
        let mut params = build_map([
            ("seed_artists", seed_artists.as_deref()),
            ("seed_genres", seed_genres.as_deref()),
            ("seed_tracks", seed_tracks.as_deref()),
            ("market", market.map(Into::into)),
            ("limit", limit.as_deref()),
        ]);

        // First converting the attributes into owned `String`s
        let owned_attributes = attributes
            .into_iter()
            .map(|attr| (<&str>::from(attr).to_owned(), attr.value_string()))
            .collect::<HashMap<_, _>>();
        // Afterwards converting the values into `&str`s; otherwise they
        // wouldn't live long enough
        let borrowed_attributes = owned_attributes
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str()));
        // And finally adding all of them to the payload
        params.extend(borrowed_attributes);

        let result = self.api_get("recommendations", &params).await?;
        convert_result(&result)
    }

    /// Get full details of the items of a playlist owned by a user.
    ///
    /// Parameters:
    /// - playlist_id - the id of the playlist
    /// - fields - which fields to return
    /// - limit - the maximum number of tracks to return
    /// - offset - the index of the first track to return
    /// - market - an ISO 3166-1 alpha-2 country code or the string from_token.
    ///
    /// See [`Self::playlist_items_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-playlists-tracks)
    fn playlist_items<'a>(
        &'a self,
        playlist_id: PlaylistId<'a>,
        fields: Option<&'a str>,
        market: Option<Market>,
    ) -> Paginator<'_, ClientResult<PlaylistItem>> {
        paginate_with_ctx(
            (self, playlist_id, fields),
            move |(slf, playlist_id, fields), limit, offset| {
                slf.playlist_items_manual(
                    playlist_id.as_ref(),
                    *fields,
                    market,
                    Some(limit),
                    Some(offset),
                )
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::playlist_items`].
    async fn playlist_items_manual(
        &self,
        playlist_id: PlaylistId<'_>,
        fields: Option<&str>,
        market: Option<Market>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<PlaylistItem>> {
        let limit = limit.map(|s| s.to_string());
        let offset = offset.map(|s| s.to_string());
        let params = build_map([
            ("fields", fields),
            ("market", market.map(Into::into)),
            ("limit", limit.as_deref()),
            ("offset", offset.as_deref()),
        ]);

        let url = format!("playlists/{}/tracks", playlist_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }

    /// Gets playlists of a user.
    ///
    /// Parameters:
    /// - user_id - the id of the usr
    /// - limit  - the number of items to return
    /// - offset - the index of the first item to return
    ///
    /// See [`Self::user_playlists_manual`] for a manually paginated version of
    /// this.
    ///
    /// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-list-users-playlists)
    fn user_playlists<'a>(
        &'a self,
        user_id: UserId<'a>,
    ) -> Paginator<'_, ClientResult<SimplifiedPlaylist>> {
        paginate_with_ctx(
            (self, user_id),
            move |(slf, user_id), limit, offset| {
                slf.user_playlists_manual(user_id.as_ref(), Some(limit), Some(offset))
            },
            self.get_config().pagination_chunks,
        )
    }

    /// The manually paginated version of [`Self::user_playlists`].
    async fn user_playlists_manual(
        &self,
        user_id: UserId<'_>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> ClientResult<Page<SimplifiedPlaylist>> {
        let limit = limit.map(|s| s.to_string());
        let offset = offset.map(|s| s.to_string());
        let params = build_map([("limit", limit.as_deref()), ("offset", offset.as_deref())]);

        let url = format!("users/{}/playlists", user_id.id());
        let result = self.api_get(&url, &params).await?;
        convert_result(&result)
    }
}