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
use std::fmt::Display;
use chrono::{DateTime, Utc};
use isocountry::CountryCode;
use isolanguage_1::LanguageCode;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use crate::{
AlbumSimplified, Category, Client, Error, FeaturedPlaylists, Market, Page, PlaylistSimplified,
Recommendations, Response,
};
/// Endpoint functions related to categories, featured playlists, recommendations, and new
/// releases.
#[derive(Debug, Clone, Copy)]
pub struct Browse<'a>(pub &'a Client);
impl Browse<'_> {
/// Get information about a category.
///
/// If no locale is given or Spotify does not support the given locale, then it will default to
/// American English.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-category/).
pub async fn get_category(
self,
name: &str,
locale: Option<(LanguageCode, CountryCode)>,
country: Option<CountryCode>,
) -> Result<Response<Category>, Error> {
self.0
.send_json(
self.0
.client
.get(endpoint!("/v1/browse/categories/{}", name))
.query(&(
locale.map(|locale| ("locale", format_language(locale))),
country.map(|c| ("country", c.alpha2())),
)),
)
.await
}
/// Get information about several categories.
///
/// You do not choose which categories to get. Limit must be in the range [1..50]. If no locale
/// is given or Spotify does not support the given locale, then it will default to American
/// English.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-categories/).
pub async fn get_categories(
self,
limit: usize,
offset: usize,
locale: Option<(LanguageCode, CountryCode)>,
country: Option<CountryCode>,
) -> Result<Response<Page<Category>>, Error> {
#[derive(Deserialize)]
struct CategoryPage {
categories: Page<Category>,
}
Ok(self
.0
.send_json::<CategoryPage>(self.0.client.get(endpoint!("/v1/browse/categories")).query(
&(
("limit", limit.to_string()),
("offset", offset.to_string()),
locale.map(|l| ("locale", format_language(l))),
country.map(|c| ("country", c.alpha2())),
),
))
.await?
.map(|res| res.categories))
}
/// Get a category's playlists.
///
/// Limit must be in the range [1..50].
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-categorys-playlists/).
pub async fn get_category_playlists(
self,
name: &str,
limit: usize,
offset: usize,
country: Option<CountryCode>,
) -> Result<Response<Page<PlaylistSimplified>>, Error> {
#[derive(Deserialize)]
struct Playlists {
playlists: Page<PlaylistSimplified>,
}
Ok(self
.0
.send_json::<Playlists>(
self.0
.client
.get(endpoint!("/v1/browse/categories/{}/playlists", name))
.query(&(
("limit", limit.to_string()),
("offset", offset.to_string()),
country.map(|c| ("country", c.alpha2())),
)),
)
.await?
.map(|res| res.playlists))
}
/// Get featured playlists.
///
/// Limit must be in the range [1..50]. The locale will default to American English and the
/// timestamp will default to the current UTC time.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-featured-playlists/).
pub async fn get_featured_playlists(
self,
limit: usize,
offset: usize,
locale: Option<(LanguageCode, CountryCode)>,
time: Option<DateTime<Utc>>,
country: Option<CountryCode>,
) -> Result<Response<FeaturedPlaylists>, Error> {
self.0
.send_json(
self.0
.client
.get(endpoint!("/v1/browse/featured-playlists"))
.query(&(
("limit", limit.to_string()),
("offset", offset.to_string()),
locale.map(|l| ("locale", format_language(l))),
time.map(|t| ("timestamp", t.to_rfc3339())),
country.map(|c| ("country", c.alpha2())),
)),
)
.await
}
/// Get new releases.
///
/// Limit must be in the range [1..50]. The documentation claims to also return a message string,
/// but in reality the API does not.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-new-releases/).
pub async fn get_new_releases(
self,
limit: usize,
offset: usize,
country: Option<CountryCode>,
) -> Result<Response<Page<AlbumSimplified>>, Error> {
#[derive(Deserialize)]
struct NewReleases {
albums: Page<AlbumSimplified>,
}
Ok(self
.0
.send_json::<NewReleases>(
self.0
.client
.get(endpoint!("/v1/browse/new-releases"))
.query(&(
("limit", limit.to_string()),
("offset", offset.to_string()),
country.map(|c| ("country", c.alpha2())),
)),
)
.await?
.map(|res| res.albums))
}
/// Get recommendations.
///
/// Up to 5 seed values may be provided, that can be distributed in `seed_artists`,
/// `seed_genres` and `seed_tracks` in any way. Limit must be in the range [1..100] and this
/// target number of tracks may not always be met.
///
/// `attributes` must serialize to a string to string map or sequence of key-value tuples. See
/// the reference for more info on this.
///
/// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/).
pub async fn get_recommendations<AI: IntoIterator, GI: IntoIterator, TI: IntoIterator>(
self,
seed_artists: AI,
seed_genres: GI,
seed_tracks: TI,
attributes: &impl Serialize,
limit: usize,
market: Option<Market>,
) -> Result<Response<Recommendations>, Error>
where
AI::Item: Display,
GI::Item: Display,
TI::Item: Display,
{
self.0
.send_json(
self.0
.client
.get(endpoint!("/v1/recommendations"))
.query(&(
("seed_artists", seed_artists.into_iter().join(",")),
("seed_genres", seed_genres.into_iter().join(",")),
("seed_tracks", seed_tracks.into_iter().join(",")),
("limit", limit.to_string()),
market.map(Market::query),
))
.query(attributes),
)
.await
}
}
fn format_language(locale: (LanguageCode, CountryCode)) -> String {
format!("{}_{}", locale.0.code(), locale.1.alpha2())
}
#[cfg(test)]
mod tests {
use chrono::DateTime;
use isocountry::CountryCode;
use isolanguage_1::LanguageCode;
use crate::endpoints::client;
use crate::{Market, SeedType};
#[tokio::test]
async fn test_get_category() {
let category = client()
.browse()
.get_category(
"pop",
Some((LanguageCode::En, CountryCode::GBR)),
Some(CountryCode::GBR),
)
.await
.unwrap()
.data;
assert_eq!(category.id, "pop");
assert_eq!(category.name, "Pop");
}
#[tokio::test]
async fn test_get_categories() {
let categories = client()
.browse()
.get_categories(2, 0, None, None)
.await
.unwrap()
.data;
assert_eq!(categories.limit, 2);
assert_eq!(categories.offset, 0);
assert!(categories.items.len() <= 2);
}
#[tokio::test]
async fn test_get_category_playlists() {
let playlists = client()
.browse()
.get_category_playlists("chill", 1, 3, Some(CountryCode::GBR))
.await
.unwrap()
.data;
assert_eq!(playlists.limit, 1);
assert_eq!(playlists.offset, 3);
assert!(playlists.items.len() <= 1);
}
#[tokio::test]
async fn test_get_featured_playlists() {
let playlists = client()
.browse()
.get_featured_playlists(
2,
0,
None,
Some(
DateTime::parse_from_rfc3339("2015-05-02T19:25:47Z")
.unwrap()
.into(),
),
None,
)
.await
.unwrap()
.data
.playlists;
assert_eq!(playlists.limit, 2);
assert_eq!(playlists.offset, 0);
assert!(playlists.items.len() <= 2);
}
#[tokio::test]
async fn test_get_new_releases() {
let releases = client()
.browse()
.get_new_releases(1, 0, None)
.await
.unwrap()
.data;
assert_eq!(releases.limit, 1);
assert_eq!(releases.offset, 0);
assert!(releases.items.len() <= 1);
}
#[tokio::test]
async fn test_get_recommendations() {
let recommendations = client()
.browse()
.get_recommendations(
&["unused"; 0],
&["rock"],
&["2RTkebdbPFyg4AMIzJZql1", "6fTt0CH2t0mdeB2N9XFG5r"],
&[
("max_acousticness", "0.8"),
("min_loudness", "-40"),
("target_popularity", "100"),
],
3,
Some(Market::Country(CountryCode::GBR)),
)
.await
.unwrap()
.data;
assert!(recommendations.seeds.len() <= 3);
assert_eq!(
recommendations
.seeds
.iter()
.filter(|seed| seed.entity_type == SeedType::Artist)
.count(),
0
);
assert_eq!(
recommendations
.seeds
.iter()
.filter(|seed| seed.entity_type == SeedType::Genre)
.count(),
1
);
assert_eq!(
recommendations
.seeds
.iter()
.filter(|seed| seed.entity_type == SeedType::Track)
.count(),
2
);
assert!(recommendations.tracks.len() <= 3);
}
}