forked from ramsayleung/rspotify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth.rs
1356 lines (1228 loc) · 49.8 KB
/
oauth.rs
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
use crate::{
clients::{
append_device_id, convert_result,
pagination::{paginate, Paginator},
BaseClient,
},
http::Query,
join_ids,
macros::{build_json, build_map},
model::*,
ClientResult, OAuth, Token,
};
use std::{collections::HashMap, time};
use maybe_async::maybe_async;
use rspotify_model::idtypes::PlayContextId;
use serde_json::{json, Map};
use url::Url;
use super::pagination::write_paginate;
/// This trait implements the methods available strictly to clients with user
/// authorization, including some parts of the authentication flow that are
/// shared, and the endpoints.
///
/// Note that the base trait [`BaseClient`](crate::clients::BaseClient) may
/// have endpoints that conditionally require authorization like
/// [`user_playlist`](crate::clients::BaseClient::user_playlist). This trait
/// only separates endpoints that *always* need authorization from the base
/// ones.
#[maybe_async]
pub trait OAuthClient: BaseClient {
fn get_oauth(&self) -> &OAuth;
/// Obtains a user access token given a code, as part of the OAuth
/// authentication. The access token will be saved internally.
async fn request_token(&mut self, code: &str) -> ClientResult<()>;
/// Tries to read the cache file's token.
///
/// This will return an error if the token couldn't be read (e.g. it's not
/// available or the JSON is malformed). It may return `Ok(None)` if:
///
/// * The read token is expired and `allow_expired` is false
/// * Its scopes don't match with the current client (you will need to
/// re-authenticate to gain access to more scopes)
/// * The cached token is disabled in the config
///
/// # Note
/// This function's implementation differs slightly from the implementation
/// in [`ClientCredsSpotify::read_token_cache`]. The boolean parameter
/// `allow_expired` allows users to load expired tokens from the cache.
/// This functionality can be used to access the refresh token and obtain
/// a new, valid token. This option is unavailable in the implementation of
/// [`ClientCredsSpotify::read_token_cache`] since the client credentials
/// authorization flow does not have a refresh token and instead requires
/// the application re-authenticate.
///
/// [`ClientCredsSpotify::read_token_cache`]: crate::client_creds::ClientCredsSpotify::read_token_cache
async fn read_token_cache(&mut self, allow_expired: bool) -> ClientResult<Option<Token>> {
if !self.get_config().token_cached {
log::info!("Auth token cache read ignored (not configured)");
return Ok(None);
}
log::info!("Reading auth token cache");
let token = Token::from_cache(&self.get_config().cache_path)?;
if !self.get_oauth().scopes.is_subset(&token.scopes)
|| (!allow_expired && token.is_expired())
{
// Invalid token, since it doesn't have at least the currently
// required scopes or it's expired.
Ok(None)
} else {
Ok(Some(token))
}
}
/// Parse the response code in the given response url. If the URL cannot be
/// parsed or the `code` parameter is not present, this will return `None`.
///
// As the [RFC
// indicates](https://datatracker.ietf.org/doc/html/rfc6749#section-4.1),
// the state should be the same between the request and the callback. This
// will also return `None` if this is not true.
fn parse_response_code(&self, url: &str) -> Option<String> {
let url = Url::parse(url).ok()?;
let params = url.query_pairs().collect::<HashMap<_, _>>();
let code = params.get("code")?;
// Making sure the state is the same
let expected_state = &self.get_oauth().state;
let state = params.get("state").map(|cow| cow.as_ref());
if state != Some(expected_state) {
log::error!("Request state doesn't match the callback state");
return None;
}
Some(code.to_string())
}
/// Tries to open the authorization URL in the user's browser, and returns
/// the obtained code.
///
/// Note: this method requires the `cli` feature.
#[cfg(feature = "cli")]
fn get_code_from_user(&self, url: &str) -> ClientResult<String> {
use crate::ClientError;
log::info!("Opening brower with auth URL");
match webbrowser::open(url) {
Ok(_) => println!("Opened {} in your browser.", url),
Err(why) => eprintln!(
"Error when trying to open an URL in your browser: {:?}. \
Please navigate here manually: {}",
why, url
),
}
log::info!("Prompting user for code");
println!("Please enter the URL you were redirected to: ");
let mut input = String::new();
std::io::stdin().read_line(&mut input)?;
let code = self
.parse_response_code(&input)
.ok_or_else(|| ClientError::Cli("unable to parse the response code".to_string()))?;
Ok(code)
}
/// Opens up the authorization URL in the user's browser so that it can
/// authenticate. It reads from the standard input the redirect URI
/// in order to obtain the access token information. The resulting access
/// token will be saved internally once the operation is successful.
///
/// If the [`Config::token_cached`] setting is enabled for this client,
/// and a token exists in the cache, the token will be loaded and the client
/// will attempt to automatically refresh the token if it is expired. If
/// the token was unable to be refreshed, the client will then prompt the
/// user for the token as normal.
///
/// Note: this method requires the `cli` feature.
///
/// [`Config::token_cached`]: crate::Config::token_cached
#[cfg(feature = "cli")]
#[maybe_async]
async fn prompt_for_token(&mut self, url: &str) -> ClientResult<()> {
match self.read_token_cache(true).await {
Ok(Some(new_token)) => {
let expired = new_token.is_expired();
// Load token into client regardless of whether it's expired o
// not, since it will be refreshed later anyway.
*self.get_token().lock().await.unwrap() = Some(new_token);
if expired {
// Ensure that we actually got a token from the refetch
match self.refetch_token().await? {
Some(refreshed_token) => {
log::info!("Successfully refreshed expired token from token cache");
*self.get_token().lock().await.unwrap() = Some(refreshed_token)
}
// If not, prompt the user for it
None => {
log::info!("Unable to refresh expired token from token cache");
let code = self.get_code_from_user(url)?;
self.request_token(&code).await?;
}
}
}
}
// Otherwise following the usual procedure to get the token.
_ => {
let code = self.get_code_from_user(url)?;
self.request_token(&code).await?;
}
}
self.write_token_cache().await
}
/// Get current user playlists without required getting his profile.
///
/// Parameters:
/// - limit - the number of items to return
/// - offset - the index of the first item to return
///
/// See [`Self::current_user_playlists_manual`] for a manually paginated
/// version of this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-list-of-current-users-playlists)
fn current_user_playlists(&self) -> Paginator<'_, ClientResult<SimplifiedPlaylist>> {
paginate(
move |limit, offset| self.current_user_playlists_manual(Some(limit), Some(offset)),
self.get_config().pagination_chunks,
)
}
/// The manually paginated version of [`Self::current_user_playlists`].
async fn current_user_playlists_manual(
&self,
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! {
optional "limit": limit.as_deref(),
optional "offset": offset.as_deref(),
};
let result = self.endpoint_get("me/playlists", ¶ms).await?;
convert_result(&result)
}
/// Creates a playlist for a user.
///
/// Parameters:
/// - user_id - the id of the user
/// - name - the name of the playlist
/// - public - is the created playlist public
/// - description - the description of the playlist
/// - collaborative - if the playlist will be collaborative
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/create-playlist)
async fn user_playlist_create(
&self,
user_id: &UserId,
name: &str,
public: Option<bool>,
collaborative: Option<bool>,
description: Option<&str>,
) -> ClientResult<FullPlaylist> {
let params = build_json! {
"name": name,
optional "public": public,
optional "collaborative": collaborative,
optional "description": description,
};
let url = format!("users/{}/playlists", user_id.id());
let result = self.endpoint_post(&url, ¶ms).await?;
convert_result(&result)
}
/// Changes a playlist's name and/or public/private state.
///
/// Parameters:
/// - playlist_id - the id of the playlist
/// - name - optional name of the playlist
/// - public - optional is the playlist public
/// - collaborative - optional is the playlist collaborative
/// - description - optional description of the playlist
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/change-playlist-details)
async fn playlist_change_detail(
&self,
playlist_id: &PlaylistId,
name: Option<&str>,
public: Option<bool>,
description: Option<&str>,
collaborative: Option<bool>,
) -> ClientResult<String> {
let params = build_json! {
optional "name": name,
optional "public": public,
optional "collaborative": collaborative,
optional "description": description,
};
let url = format!("playlists/{}", playlist_id.id());
self.endpoint_put(&url, ¶ms).await
}
/// Unfollows (deletes) a playlist for a user.
///
/// Parameters:
/// - playlist_id - the id of the playlist
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/unfollow-playlist)
async fn playlist_unfollow(&self, playlist_id: &PlaylistId) -> ClientResult<()> {
let url = format!("playlists/{}/followers", playlist_id.id());
self.endpoint_delete(&url, &json!({})).await?;
Ok(())
}
/// Adds items to a playlist.
///
/// Parameters:
/// - playlist_id - the id of the playlist
/// - track_ids - a list of track URIs, URLs or IDs
/// - position - the position to add the tracks
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/add-tracks-to-playlist)
async fn playlist_add_items<'a>(
&self,
playlist_id: &PlaylistId,
items: impl IntoIterator<Item = &'a dyn PlayableId> + Send + 'a,
position: Option<i32>,
) -> ClientResult<PlaylistResult> {
let uris = items.into_iter().map(|id| id.uri()).collect::<Vec<_>>();
let url = format!("playlists/{}/tracks", playlist_id.id());
let chunk_size = 100;
let last_response = write_paginate(
|chunk, position| {
let params = build_json! {
"uris": chunk,
optional "position": Some(position),
};
self.endpoint_post(&url, ¶ms)
},
uris,
chunk_size,
)
.await;
convert_result(&last_response)
}
/// Replace all items in a playlist
///
/// Parameters:
/// - user - the id of the user
/// - playlist_id - the id of the playlist
/// - tracks - the list of track ids to add to the playlist
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/reorder-or-replace-playlists-tracks)
// TODO: Add write pagination
async fn playlist_replace_items<'a>(
&self,
playlist_id: &PlaylistId,
items: impl IntoIterator<Item = &'a dyn PlayableId> + Send + 'a,
) -> ClientResult<()> {
let uris = items.into_iter().map(|id| id.uri()).collect::<Vec<_>>();
let params = build_json! {
"uris": uris
};
let url = format!("playlists/{}/tracks", playlist_id.id());
self.endpoint_put(&url, ¶ms).await?;
Ok(())
}
/// Reorder items in a playlist.
///
/// Parameters:
/// - playlist_id - the id of the playlist
/// - uris - a list of Spotify URIs to replace or clear
/// - range_start - the position of the first track to be reordered
/// - insert_before - the position where the tracks should be inserted
/// - range_length - optional the number of tracks to be reordered (default:
/// 1)
/// - snapshot_id - optional playlist's snapshot ID
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/reorder-or-replace-playlists-tracks)
// TODO: Add write-pagination
async fn playlist_reorder_items(
&self,
playlist_id: &PlaylistId,
range_start: Option<i32>,
insert_before: Option<i32>,
range_length: Option<u32>,
snapshot_id: Option<&str>,
) -> ClientResult<PlaylistResult> {
let params = build_json! {
optional "range_start": range_start,
optional "insert_before": insert_before,
optional "range_length": range_length,
optional "snapshot_id": snapshot_id,
};
let url = format!("playlists/{}/tracks", playlist_id.id());
let result = self.endpoint_put(&url, ¶ms).await?;
convert_result(&result)
}
/// Removes all occurrences of the given items from the given playlist.
///
/// Parameters:
/// - playlist_id - the id of the playlist
/// - track_ids - the list of track ids to add to the playlist
/// - snapshot_id - optional id of the playlist snapshot
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/remove-tracks-playlist)
// TODO: Add write-pagination
async fn playlist_remove_all_occurrences_of_items<'a>(
&self,
playlist_id: &PlaylistId,
track_ids: impl IntoIterator<Item = &'a dyn PlayableId> + Send + 'a,
snapshot_id: Option<&str>,
) -> ClientResult<PlaylistResult> {
let tracks = track_ids
.into_iter()
.map(|id| {
let mut map = Map::with_capacity(1);
map.insert("uri".to_owned(), id.uri().into());
map
})
.collect::<Vec<_>>();
let params = build_json! {
"tracks": tracks,
optional "snapshot_id": snapshot_id,
};
let url = format!("playlists/{}/tracks", playlist_id.id());
let result = self.endpoint_delete(&url, ¶ms).await?;
convert_result(&result)
}
/// Removes specfic occurrences of the given items from the given playlist.
///
/// Parameters:
/// - playlist_id: the id of the playlist
/// - tracks: an array of map containing Spotify URIs of the tracks to
/// remove with their current positions in the playlist. For example:
///
/// ```json
/// {
/// "tracks":[
/// {
/// "uri":"spotify:track:4iV5W9uYEdYUVa79Axb7Rh",
/// "positions":[
/// 0,
/// 3
/// ]
/// },
/// {
/// "uri":"spotify:track:1301WleyT98MSxVHPZCA6M",
/// "positions":[
/// 7
/// ]
/// }
/// ]
/// }
/// ```
/// - snapshot_id: optional id of the playlist snapshot
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/remove-tracks-playlist)
// TODO: Add write-pagination
async fn playlist_remove_specific_occurrences_of_items<'a>(
&self,
playlist_id: &PlaylistId,
items: impl IntoIterator<Item = ItemPositions<'a>> + Send + 'a,
snapshot_id: Option<&str>,
) -> ClientResult<PlaylistResult> {
let tracks = items
.into_iter()
.map(|track| {
let mut map = Map::new();
map.insert("uri".to_owned(), track.id.uri().into());
map.insert("positions".to_owned(), json!(track.positions));
map
})
.collect::<Vec<_>>();
let params = build_json! {
"tracks": tracks,
optional "snapshot_id": snapshot_id,
};
let url = format!("playlists/{}/tracks", playlist_id.id());
let result = self.endpoint_delete(&url, ¶ms).await?;
convert_result(&result)
}
/// Add the current authenticated user as a follower of a playlist.
///
/// Parameters:
/// - playlist_id - the id of the playlist
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/follow-playlist)
async fn playlist_follow(
&self,
playlist_id: &PlaylistId,
public: Option<bool>,
) -> ClientResult<()> {
let url = format!("playlists/{}/followers", playlist_id.id());
let params = build_json! {
optional "public": public,
};
self.endpoint_put(&url, ¶ms).await?;
Ok(())
}
/// Get detailed profile information about the current user.
/// An alias for the 'current_user' method.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile)
async fn me(&self) -> ClientResult<PrivateUser> {
let result = self.endpoint_get("me/", &Query::new()).await?;
convert_result(&result)
}
/// Get detailed profile information about the current user.
/// An alias for the 'me' method.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile)
async fn current_user(&self) -> ClientResult<PrivateUser> {
self.me().await
}
/// Get information about the current users currently playing item.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-the-users-currently-playing-track)
async fn current_user_playing_item(&self) -> ClientResult<Option<CurrentlyPlayingContext>> {
let result = self
.endpoint_get("me/player/currently-playing", &Query::new())
.await?;
if result.is_empty() {
Ok(None)
} else {
convert_result(&result)
}
}
/// Gets a list of the albums saved in the current authorized user's
/// "Your Music" library
///
/// Parameters:
/// - limit - the number of albums to return
/// - offset - the index of the first album to return
/// - market - Provide this parameter if you want to apply Track Relinking.
///
/// See [`Self::current_user_saved_albums`] for a manually paginated version
/// of this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-saved-albums)
fn current_user_saved_albums<'a>(
&'a self,
market: Option<&'a Market>,
) -> Paginator<'a, ClientResult<SavedAlbum>> {
paginate(
move |limit, offset| {
self.current_user_saved_albums_manual(market, Some(limit), Some(offset))
},
self.get_config().pagination_chunks,
)
}
/// The manually paginated version of [`Self::current_user_saved_albums`].
async fn current_user_saved_albums_manual(
&self,
market: Option<&Market>,
limit: Option<u32>,
offset: Option<u32>,
) -> ClientResult<Page<SavedAlbum>> {
let limit = limit.map(|s| s.to_string());
let offset = offset.map(|s| s.to_string());
let params = build_map! {
optional "market": market.map(|x| x.as_ref()),
optional "limit": limit.as_deref(),
optional "offset": offset.as_deref(),
};
let result = self.endpoint_get("me/albums", ¶ms).await?;
convert_result(&result)
}
/// Get a list of the songs saved in the current Spotify user's "Your Music"
/// library.
///
/// Parameters:
/// - limit - the number of tracks to return
/// - offset - the index of the first track to return
/// - market - Provide this parameter if you want to apply Track Relinking.
///
/// See [`Self::current_user_saved_tracks_manual`] for a manually paginated
/// version of this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-saved-tracks)
fn current_user_saved_tracks<'a>(
&'a self,
market: Option<&'a Market>,
) -> Paginator<'a, ClientResult<SavedTrack>> {
paginate(
move |limit, offset| {
self.current_user_saved_tracks_manual(market, Some(limit), Some(offset))
},
self.get_config().pagination_chunks,
)
}
/// The manually paginated version of [`Self::current_user_saved_tracks`].
async fn current_user_saved_tracks_manual(
&self,
market: Option<&Market>,
limit: Option<u32>,
offset: Option<u32>,
) -> ClientResult<Page<SavedTrack>> {
let limit = limit.map(|s| s.to_string());
let offset = offset.map(|s| s.to_string());
let params = build_map! {
optional "market": market.map(|x| x.as_ref()),
optional "limit": limit.as_deref(),
optional "offset": offset.as_deref(),
};
let result = self.endpoint_get("me/tracks", ¶ms).await?;
convert_result(&result)
}
/// Gets a list of the artists followed by the current authorized user.
///
/// Parameters:
/// - after - the last artist ID retrieved from the previous request
/// - limit - the number of tracks to return
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-followed)
async fn current_user_followed_artists(
&self,
after: Option<&str>,
limit: Option<u32>,
) -> ClientResult<CursorBasedPage<FullArtist>> {
let limit = limit.map(|s| s.to_string());
let params = build_map! {
"type": Type::Artist.as_ref(),
optional "after": after,
optional "limit": limit.as_deref(),
};
let result = self.endpoint_get("me/following", ¶ms).await?;
convert_result::<CursorPageFullArtists>(&result).map(|x| x.artists)
}
/// Remove one or more tracks from the current user's "Your Music" library.
///
/// Parameters:
/// - track_ids - a list of track URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/remove-tracks-user)
// TODO: Add write-pagination
async fn current_user_saved_tracks_delete<'a>(
&self,
track_ids: impl IntoIterator<Item = &'a TrackId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/tracks/?ids={}", join_ids(track_ids));
self.endpoint_delete(&url, &json!({})).await?;
Ok(())
}
/// Check if one or more tracks is already saved in the current Spotify
/// user’s "Your Music" library.
///
/// Parameters:
/// - track_ids - a list of track URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/check-users-saved-tracks)
// TODO: Add write-pagination
async fn current_user_saved_tracks_contains<'a>(
&self,
track_ids: impl IntoIterator<Item = &'a TrackId> + Send + 'a,
) -> ClientResult<Vec<bool>> {
let url = format!("me/tracks/contains/?ids={}", join_ids(track_ids));
let result = self.endpoint_get(&url, &Query::new()).await?;
convert_result(&result)
}
/// Save one or more tracks to the current user's "Your Music" library.
///
/// Parameters:
/// - track_ids - a list of track URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/save-tracks-user)
// TODO: Add write-pagination
async fn current_user_saved_tracks_add<'a>(
&self,
track_ids: impl IntoIterator<Item = &'a TrackId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/tracks/?ids={}", join_ids(track_ids));
self.endpoint_put(&url, &json!({})).await?;
Ok(())
}
/// Get the current user's top artists.
///
/// Parameters:
/// - limit - the number of entities to return
/// - offset - the index of the first entity to return
/// - time_range - Over what time frame are the affinities computed
///
/// See [`Self::current_user_top_artists_manual`] for a manually paginated
/// version of this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-top-artists-and-tracks)
fn current_user_top_artists<'a>(
&'a self,
time_range: Option<&'a TimeRange>,
) -> Paginator<'_, ClientResult<FullArtist>> {
paginate(
move |limit, offset| {
self.current_user_top_artists_manual(time_range, Some(limit), Some(offset))
},
self.get_config().pagination_chunks,
)
}
/// The manually paginated version of [`Self::current_user_top_artists`].
async fn current_user_top_artists_manual(
&self,
time_range: Option<&TimeRange>,
limit: Option<u32>,
offset: Option<u32>,
) -> ClientResult<Page<FullArtist>> {
let limit = limit.map(|s| s.to_string());
let offset = offset.map(|s| s.to_string());
let params = build_map! {
optional "time_range": time_range.map(|x| x.as_ref()),
optional "limit": limit.as_deref(),
optional "offset": offset.as_deref(),
};
let result = self.endpoint_get("me/top/artists", ¶ms).await?;
convert_result(&result)
}
/// Get the current user's top tracks.
///
/// Parameters:
/// - limit - the number of entities to return
/// - offset - the index of the first entity to return
/// - time_range - Over what time frame are the affinities computed
///
/// See [`Self::current_user_top_tracks_manual`] for a manually paginated
/// version of this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-users-top-artists-and-tracks)
fn current_user_top_tracks<'a>(
&'a self,
time_range: Option<&'a TimeRange>,
) -> Paginator<'_, ClientResult<FullTrack>> {
paginate(
move |limit, offset| {
self.current_user_top_tracks_manual(time_range, Some(limit), Some(offset))
},
self.get_config().pagination_chunks,
)
}
/// The manually paginated version of [`Self::current_user_top_tracks`].
async fn current_user_top_tracks_manual(
&self,
time_range: Option<&TimeRange>,
limit: Option<u32>,
offset: Option<u32>,
) -> ClientResult<Page<FullTrack>> {
let limit = limit.map(|x| x.to_string());
let offset = offset.map(|x| x.to_string());
let params = build_map! {
optional "time_range": time_range.map(|x| x.as_ref()),
optional "limit": limit.as_deref(),
optional "offset": offset.as_deref(),
};
let result = self.endpoint_get("me/top/tracks", ¶ms).await?;
convert_result(&result)
}
/// Get the current user's recently played tracks.
///
/// Parameters:
/// - limit - the number of entities to return
/// - time_limit - a Unix timestamp in milliseconds. Returns all items after
/// or before (but not including) this cursor position.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-recently-played)
async fn current_user_recently_played(
&self,
limit: Option<u32>,
time_limit: Option<TimeLimits>,
) -> ClientResult<CursorBasedPage<PlayHistory>> {
let limit = limit.map(|x| x.to_string());
let mut params = build_map! {
optional "limit": limit.as_deref(),
};
let time_limit = match time_limit {
Some(TimeLimits::Before(y)) => Some(("before", y.timestamp_millis().to_string())),
Some(TimeLimits::After(y)) => Some(("after", y.timestamp_millis().to_string())),
None => None,
};
if let Some((name, value)) = time_limit.as_ref() {
params.insert(name, value);
}
let result = self
.endpoint_get("me/player/recently-played", ¶ms)
.await?;
convert_result(&result)
}
/// Add one or more albums to the current user's "Your Music" library.
///
/// Parameters:
/// - album_ids - a list of album URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/save-albums-user)
// TODO: Add write-pagination
async fn current_user_saved_albums_add<'a>(
&self,
album_ids: impl IntoIterator<Item = &'a AlbumId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/albums/?ids={}", join_ids(album_ids));
self.endpoint_put(&url, &json!({})).await?;
Ok(())
}
/// Remove one or more albums from the current user's "Your Music" library.
///
/// Parameters:
/// - album_ids - a list of album URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/remove-albums-user)
// TODO: Add write-pagination
async fn current_user_saved_albums_delete<'a>(
&self,
album_ids: impl IntoIterator<Item = &'a AlbumId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/albums/?ids={}", join_ids(album_ids));
self.endpoint_delete(&url, &json!({})).await?;
Ok(())
}
/// Check if one or more albums is already saved in the current Spotify
/// user’s "Your Music” library.
///
/// Parameters:
/// - album_ids - a list of album URIs, URLs or IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/check-users-saved-albums)
// TODO: Add write-pagination
async fn current_user_saved_albums_contains<'a>(
&self,
album_ids: impl IntoIterator<Item = &'a AlbumId> + Send + 'a,
) -> ClientResult<Vec<bool>> {
let url = format!("me/albums/contains/?ids={}", join_ids(album_ids));
let result = self.endpoint_get(&url, &Query::new()).await?;
convert_result(&result)
}
/// Follow one or more artists.
///
/// Parameters:
/// - artist_ids - a list of artist IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/follow-artists-users)
// TODO: Add write-pagination
async fn user_follow_artists<'a>(
&self,
artist_ids: impl IntoIterator<Item = &'a ArtistId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/following?type=artist&ids={}", join_ids(artist_ids));
self.endpoint_put(&url, &json!({})).await?;
Ok(())
}
/// Unfollow one or more artists.
///
/// Parameters:
/// - artist_ids - a list of artist IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/unfollow-artists-users)
// TODO: Add write-pagination
async fn user_unfollow_artists<'a>(
&self,
artist_ids: impl IntoIterator<Item = &'a ArtistId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/following?type=artist&ids={}", join_ids(artist_ids));
self.endpoint_delete(&url, &json!({})).await?;
Ok(())
}
/// Check to see if the current user is following one or more artists or
/// other Spotify users.
///
/// Parameters:
/// - artist_ids - the ids of the users that you want to
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/check-current-user-follows)
// TODO: Add write-pagination
async fn user_artist_check_follow<'a>(
&self,
artist_ids: impl IntoIterator<Item = &'a ArtistId> + Send + 'a,
) -> ClientResult<Vec<bool>> {
let url = format!(
"me/following/contains?type=artist&ids={}",
join_ids(artist_ids)
);
let result = self.endpoint_get(&url, &Query::new()).await?;
convert_result(&result)
}
/// Follow one or more users.
///
/// Parameters:
/// - user_ids - a list of artist IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/follow-artists-users)
// TODO: Add write-pagination
async fn user_follow_users<'a>(
&self,
user_ids: impl IntoIterator<Item = &'a UserId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/following?type=user&ids={}", join_ids(user_ids));
self.endpoint_put(&url, &json!({})).await?;
Ok(())
}
/// Unfollow one or more users.
///
/// Parameters:
/// - user_ids - a list of artist IDs
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/unfollow-artists-users)
// TODO: Add write-pagination
async fn user_unfollow_users<'a>(
&self,
user_ids: impl IntoIterator<Item = &'a UserId> + Send + 'a,
) -> ClientResult<()> {
let url = format!("me/following?type=user&ids={}", join_ids(user_ids));
self.endpoint_delete(&url, &json!({})).await?;
Ok(())
}
/// Get a User’s Available Devices
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-users-available-devices)
async fn device(&self) -> ClientResult<Vec<Device>> {
let result = self
.endpoint_get("me/player/devices", &Query::new())
.await?;
convert_result::<DevicePayload>(&result).map(|x| x.devices)
}
/// Get Information About The User’s Current Playback
///
/// Parameters:
/// - market: Optional. an ISO 3166-1 alpha-2 country code or the string from_token.
/// - additional_types: Optional. A list of item types that your client
/// supports besides the default track type. Valid types are: `track` and
/// `episode`.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-information-about-the-users-current-playback)
async fn current_playback<'a>(
&self,
country: Option<&Market>,
additional_types: Option<impl IntoIterator<Item = &'a AdditionalType> + Send + 'a>,
) -> ClientResult<Option<CurrentPlaybackContext>> {
let additional_types = additional_types.map(|x| {
x.into_iter()
.map(|x| x.as_ref())
.collect::<Vec<_>>()
.join(",")
});
let params = build_map! {
optional "country": country.map(|x| x.as_ref()),
optional "additional_types": additional_types.as_deref(),
};
let result = self.endpoint_get("me/player", ¶ms).await?;
if result.is_empty() {
Ok(None)
} else {
convert_result(&result)
}
}
/// Get the User’s Currently Playing Track
///
/// Parameters:
/// - market: Optional. an ISO 3166-1 alpha-2 country code or the string from_token.
/// - additional_types: Optional. A comma-separated list of item types that
/// your client supports besides the default track type. Valid types are:
/// `track` and `episode`.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/#/operations/get-recently-played)
async fn current_playing<'a>(
&self,
market: Option<&'a Market>,
additional_types: Option<impl IntoIterator<Item = &'a AdditionalType> + Send + 'a>,
) -> ClientResult<Option<CurrentlyPlayingContext>> {
let additional_types = additional_types.map(|x| {