spotifyrs 0.2.0

A Rust-built wrapper for the Spotify Web API that focuses on consistent and reliable developer interaction with the many objects in the API (artists, tracks, etc)
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
use crate::spotify::{
    Device, Playback, PlayedTrack, RepeatState, Spotify, SpotifyCollection, SpotifyContext,
    SpotifyError, SpotifyObject, Track,
};
use crate::srequest::RequestMethod;
use chrono::NaiveDateTime;
use serde_json::{Map, Number, Value};
use std::collections::HashMap;

impl Spotify {
    /// Gets current playback state of current user: <https://developer.spotify.com/documentation/web-api/reference/#/operations/get-information-about-the-users-current-playback>
    /// Note: currently only supports Tracks and not Episodes. Unexpected behavior may occur with Episodes.
    ///
    /// Requires scope: user-read-playback-state
    ///
    /// # Arguments
    /// * `market` - An ISO 3166-1 alpha-2 country code.
    ///
    pub fn get_playback_state(&self, market: Option<&str>) -> Result<Playback, SpotifyError> {
        let mut url_extension = String::from("me/player?additional_types=track"); // create url extension (Note: only supporting tracks, not episodes)

        self.check_scope("user-read-playback-state")?; // check scope

        if let Some(market) = market {
            // if market is Some then add it to url extension
            url_extension.push_str(&format!("&market={}", market));
        }
        let response = self.spotify_request(&url_extension, RequestMethod::Get)?; // send request

        return Ok(Playback::new(&response)); // return playback
    }

    /// Transfers playback to another device and whether or not the new device should play: <https://developer.spotify.com/documentation/web-api/reference/#/operations/transfer-a-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `device_id` - The device id to transfer playback to
    /// * `play` - Whether or not to start playback on the new device
    ///
    pub fn transfer_playback(&self, device_id: &str, play: bool) -> Result<(), SpotifyError> {
        let url_extension = String::from("me/player"); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        let mut body: HashMap<String, Value> = HashMap::new(); // create body
        body.insert(
            "device_ids".to_string(),
            Value::Array(vec![Value::String(device_id.to_string())]),
        ); // insert device id
        body.insert("play".to_string(), Value::Bool(play)); // insert play

        self.spotify_request(&url_extension, RequestMethod::Put(body))?; // send request

        return Ok(());
    }

    /// Gets all the available spotify devices for playback: <https://developer.spotify.com/documentation/web-api/reference/#/operations/get-a-users-available-devices>
    ///
    /// Requires scope: user-read-playback-state
    ///
    pub fn get_available_devices(&self) -> Result<Vec<Device>, SpotifyError> {
        let url_extension = String::from("me/player/devices"); // create url extension

        self.check_scope("user-read-playback-state")?;

        let response = self.spotify_request(&url_extension, RequestMethod::Get)?; // send request

        let mut devices: Vec<Device> = Vec::new(); // empty vector to store devices

        for device in response["devices"].members() {
            // iterate through devices
            devices.push(Device::new(&device)); // push device to vector
        }

        return Ok(devices); // return vector
    }

    /// Gets the currently playing track: <https://developer.spotify.com/documentation/web-api/reference/#/operations/get-the-users-currently-playing-track>
    /// Note: Currently this only supports tracks and not episodes. Weird behavior may occur if an episode is being played.
    ///
    /// Requires scope: user-read-currently-playing
    ///
    /// # Arguments
    /// * `market` - An ISO 3166-1 alpha-2 country code which the returned track should be in the market of
    ///
    pub fn get_currently_playing_track(
        &self,
        market: Option<&str>,
    ) -> Result<Playback, SpotifyError> {
        let mut url_extension = String::from("me/player/currently-playing?additional_types=track"); // create url extension. Only supporting tracks right now

        self.check_scope("user-read-currently-playing")?; // check scope

        if let Some(market) = market {
            // if market is Some then add it to url extension
            url_extension.push_str(&format!("&market={}", market));
        }

        let response = self.spotify_request(&url_extension, RequestMethod::Get)?; // send request

        return Ok(Playback::new(&response)); // return playback
    }

    /// Start a new context in player or resume playback of a device: <https://developer.spotify.com/documentation/web-api/reference/#/operations/start-a-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `device_id` - The id of the device to start playback on
    /// * `context` - The context to start playback on. Valid contexts: Album, Artist, Playlist
    /// * `track_ids` - The track ids to start playback on
    /// * `offset_position` - Indicates where in the context the playback should start. For example, starting on the 2nd song of an album with offset=1.
    /// * `offset_track` - Indicates which track in context to begin playback on. This is a track id. Note: this will be ignored if offset_position is set.
    /// * `position_ms` - Where in the song to begin playback
    ///
    pub fn start_resume_playback(
        &self,
        device_id: Option<&str>,
        context: Option<SpotifyContext>,
        track_ids: Option<Vec<&str>>,
        offset_position: Option<i32>,
        offset_track: Option<&str>,
        position_ms: Option<i32>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = String::from("me/player/play"); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("?device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        let mut body: HashMap<String, Value> = HashMap::new(); // create body

        if let Some(context) = context {
            body.insert("context_uri".to_string(), Value::String(context.uri()));
            // if context is supplied, then add it to body
        }

        if let Some(track_ids) = track_ids {
            let mut tracks: Vec<Value> = Vec::new(); // create vector to store track ids

            for track_id in track_ids {
                tracks.push(Value::String(track_id.to_string())); // push track id to vector
            }

            body.insert("uris".to_string(), Value::Array(tracks)); // insert track ids into body
        }

        if let Some(offset) = offset_position {
            let mut m = Map::new();
            m.insert("position".to_string(), Value::Number(Number::from(offset))); // if offset_position is supplied, then add it to body

            body.insert("offset".to_string(), Value::Object(m)); // if offset is supplied, then add it to body
        }

        if offset_position.is_none() {
            //if offset_position wasn't supplied
            if let Some(track_id) = offset_track {
                let mut m = Map::new();
                m.insert(
                    "uri".to_string(),
                    Value::String(format!("spotify:track:{}", track_id)),
                ); // if offset_track is supplied, then add it to body

                body.insert("offset".to_string(), Value::Object(m)); // if offset is supplied, then add it to body
            }
        }

        if let Some(position_ms) = position_ms {
            body.insert(
                "position_ms".to_string(),
                Value::Number(Number::from(position_ms)),
            ); // if position_ms is supplied, then add it to body
        }

        self.spotify_request(&url_extension, RequestMethod::Put(body))?; // send request

        return Ok(());
    }

    /// Pauses the user's playback: <https://developer.spotify.com/documentation/web-api/reference/#/operations/pause-a-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `device_id` - The id of the device to pause playback on
    ///
    pub fn pause_playback(&self, device_id: Option<&str>) -> Result<(), SpotifyError> {
        let mut url_extension = String::from("me/player/pause"); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("?device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Put(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Skips the currently playing track to the next track: <https://developer.spotify.com/documentation/web-api/reference/#/operations/skip-users-playback-to-next-track>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `device_id` - The id of the device to skip on
    ///
    pub fn skip_next(&self, device_id: Option<&str>) -> Result<(), SpotifyError> {
        let mut url_extension = String::from("me/player/next"); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("?device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Post(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Skips the currently playing track to the previous track: <https://developer.spotify.com/documentation/web-api/reference/#/operations/skip-users-playback-to-previous-track>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `device_id` - The id of the device to skip on
    ///
    pub fn skip_previous(&self, device_id: Option<&str>) -> Result<(), SpotifyError> {
        let mut url_extension = String::from("me/player/previous"); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("?device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Post(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Seeks to specified position in currently playing track: <https://developer.spotify.com/documentation/web-api/reference/#/operations/seek-to-position-in-currently-playing-track>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `position` - The position in milliseconds to seek to
    /// * `device_id` - The id of the device to seek on
    ///
    pub fn seek_position(
        &self,
        position: i32,
        device_id: Option<&str>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = format!("me/player/seek?position_ms={}", position); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("&device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Put(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Sets the repeat mode for the user's playback: <https://developer.spotify.com/documentation/web-api/reference/#/operations/set-repeat-mode-on-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `state` - The repeat state to set. Valid values are: track, context, off
    /// * `device_id` - The id of the device to set repeat mode on
    ///
    pub fn set_repeat_mode(
        &self,
        state: RepeatState,
        device_id: Option<&str>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = format!("me/player/repeat?state={}", state.to_string()); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("&device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Put(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Sets the volume for the user's playback: <https://developer.spotify.com/documentation/web-api/reference/#/operations/set-volume-for-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `volume` - The volume to set. Must be a value from 0 to 100 inclusive
    /// * `device_id` - The id of the device to set volume on
    ///
    pub fn set_playback_volume(
        &self,
        volume: i32,
        device_id: Option<&str>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = format!("me/player/volume?volume_percent={}", volume); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("&device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Put(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Toggles shuffle state: <https://developer.spotify.com/documentation/web-api/reference/#/operations/toggle-shuffle-for-users-playback>
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `state` - The shuffle state to set. Valid values are: true, false
    /// * `device_id` - The id of the device to set shuffle on
    ///
    pub fn toggle_shuffle(
        &self,
        state: bool,
        device_id: Option<&str>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = format!("me/player/shuffle?state={}", state); // create url extension

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("&device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        }

        self.spotify_request(&url_extension, RequestMethod::Put(HashMap::new()))?; // send request

        return Ok(());
    }

    /// Returns user's recently played items: <https://developer.spotify.com/documentation/web-api/reference/#/operations/get-recently-played>
    ///
    /// Requires scope: user-read-recently-played
    ///
    /// # Arguments
    /// * `after` - Returns all items *after* this time stamp.
    /// * `before` - Returns all items *before* this time stamp. Will be ignored if after is specified
    /// * `limit` - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50
    ///
    pub fn get_recently_played_tracks(
        &self,
        after: Option<NaiveDateTime>,
        before: Option<NaiveDateTime>,
        limit: Option<i32>,
    ) -> Result<SpotifyCollection<PlayedTrack>, SpotifyError> {
        let mut url_extension = String::from("me/player/recently-played"); // create url extension

        self.check_scope("user-read-recently-played")?; // check scope

        if !after.is_none() || !before.is_none() || !limit.is_none() {
            url_extension.push_str("?"); // if any of the optional arguments are supplied, then add a ? to the url extension
        }

        if let Some(after) = after {
            url_extension.push_str(&format!("&after={}", after.timestamp_millis()));
            // if after is supplied, then add it to url extension
        }

        if after.is_none() {
            // only if after isn't supplied consider before
            if let Some(before) = before {
                url_extension.push_str(&format!("&before={}", before.timestamp_millis()));
                // if before is supplied, then add it to url extension
            }
        }

        if let Some(limit) = limit {
            url_extension.push_str(&format!("&limit={}", limit)); // if limit is supplied, then add it to url extension
        }

        let response = self.spotify_request(&url_extension, RequestMethod::Get)?; // send request

        return Ok(SpotifyCollection::<PlayedTrack>::new(&response)); // return response
    }

    /// Returns the user's currently playing track and queue: <https://developer.spotify.com/documentation/web-api/reference/#/operations/get-queue>
    /// Note: This wrapper currently only supports tracks and unexpected errors may occur if the queue contains episodes
    ///
    /// Requires scope: user-read-currently-playing user-read-playback-state
    ///
    pub fn get_users_queue(&self) -> Result<(Track, Vec<Track>), SpotifyError> {
        let url_extension = String::from("me/player/queue"); // create url extension

        self.check_scope("user-read-currently-playing user-read-playback-state")?; // check scope

        let response = self.spotify_request(&url_extension, RequestMethod::Get)?; // send request

        let track = Track::new(&response["currently_playing"]); // get and format currently playing field

        let mut tracks = Vec::new(); // create vector to store tracks

        for track in response["queue"].members() {
            tracks.push(Track::new(&track)); // add track to vector
        }

        return Ok((track, tracks)); // return response
    }

    /// Adds specified item to the playback queue: <https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue>
    /// Note: currently only tracks are supported, episode ids will have unexpected results
    ///
    /// Requires scope: user-modify-playback-state
    ///
    /// # Arguments
    /// * `track_id` - The id of the track to add to the queue
    /// * `device_id` - The id of the device to add the track to
    ///
    pub fn add_track_to_queue(
        &self,
        track_id: &str,
        device_id: Option<&str>,
    ) -> Result<(), SpotifyError> {
        let mut url_extension = format!("me/player/queue?uri=spotify:track:{}", track_id); // create url extension (specifically with track as input)

        self.check_scope("user-modify-playback-state")?; // check scope

        if let Some(device_id) = device_id {
            url_extension.push_str(&format!("&device_id={}", device_id)); // if device_id is supplied, then add it to url extension
        };

        self.spotify_request(&url_extension, RequestMethod::Post(HashMap::new()))?; // send request

        return Ok(()); // return response
    }
}