spotify-rs 0.4.1

A Rust wrapper for the Spotify API.
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
use std::{fmt::Debug, marker::PhantomData};

use reqwest::Method;
use serde::Serialize;
use serde_json::{json, Value};

use crate::{
    auth::{AuthFlow, Authorised},
    client::Body,
    error::Result,
    model::{
        player::{CurrentlyPlayingItem, Device, Devices, PlayHistory, PlaybackState, Queue},
        CursorPage,
    },
    Nil,
};

use super::{Client, Endpoint};

impl Endpoint for TransferPlaybackEndpoint {}
impl Endpoint for StartPlaybackEndpoint {}
impl Endpoint for SeekToPositionEndpoint {}
impl Endpoint for SetRepeatModeEndpoint {}
impl Endpoint for SetPlaybackVolumeEndpoint {}
impl Endpoint for ToggleShuffleEndpoint {}
impl<T: TimestampMarker> Endpoint for RecentlyPlayedTracksEndpoint<T> {
    fn endpoint_url(&self) -> &'static str {
        "/me/player/recently-played"
    }
}
impl Endpoint for AddItemToQueueEndpoint {}

pub async fn get_playback_state(
    market: Option<&str>,
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<PlaybackState> {
    let market = market.map(|m| [("market", m)]);
    spotify
        .get::<[(&str, &str); 1], _>("/me/player".to_owned(), market)
        .await
}

pub fn transfer_playback(device_id: impl Into<String>) -> TransferPlaybackEndpoint {
    TransferPlaybackEndpoint {
        device_ids: vec![device_id.into()],
        play: None,
    }
}

pub async fn get_available_devices(
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<Vec<Device>> {
    spotify
        .get::<(), _>("/me/player/devices".to_owned(), None)
        .await
        .map(|d: Devices| d.devices)
}

pub async fn get_currently_playing_track(
    market: Option<&str>,
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<CurrentlyPlayingItem> {
    let market = market.map(|m| [("market", m)]);
    spotify
        .get::<Option<[(&str, &str); 1]>, _>("/me/player/currently-playing".to_owned(), market)
        .await
}

pub fn start_playback() -> StartPlaybackEndpoint {
    StartPlaybackEndpoint::default()
}

pub async fn pause_playback(
    device_id: Option<&str>,
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<Nil> {
    let device_id = device_id.map(|d| [("device_id", d)]);
    spotify
        .request(Method::PUT, "/me/player/pause".to_owned(), device_id, None)
        .await
}

pub async fn skip_to_next(
    device_id: Option<&str>,
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<Nil> {
    let device_id = device_id.map(|d| [("device_id", d)]);
    spotify
        .request(Method::POST, "/me/player/next".to_owned(), device_id, None)
        .await
}

pub async fn skip_to_previous(
    device_id: Option<&str>,
    spotify: &Client<impl AuthFlow + Authorised>,
) -> Result<Nil> {
    let device_id = device_id.map(|d| [("device_id", d)]);
    spotify
        .request(
            Method::POST,
            "/me/player/previous".to_owned(),
            device_id,
            None,
        )
        .await
}

pub fn seek_to_position(position: u32) -> SeekToPositionEndpoint {
    SeekToPositionEndpoint {
        position_ms: position,
        device_id: None,
    }
}

pub fn set_repeat_mode(repeat_mode: RepeatMode) -> SetRepeatModeEndpoint {
    SetRepeatModeEndpoint {
        state: repeat_mode,
        device_id: None,
    }
}

pub fn set_playback_volume(volume: u32) -> SetPlaybackVolumeEndpoint {
    SetPlaybackVolumeEndpoint {
        volume_percent: volume,
        device_id: None,
    }
}

pub fn toggle_playback_shuffle(shuffle: bool) -> ToggleShuffleEndpoint {
    ToggleShuffleEndpoint {
        state: shuffle,
        device_id: None,
    }
}

pub fn recently_played_tracks() -> RecentlyPlayedTracksEndpoint {
    RecentlyPlayedTracksEndpoint::default()
}

pub async fn get_user_queue(spotify: &Client<impl AuthFlow + Authorised>) -> Result<Queue> {
    spotify
        .get::<(), _>("/me/player/queue".to_owned(), None)
        .await
}

pub fn add_item_to_queue(uri: impl Into<String>) -> AddItemToQueueEndpoint {
    AddItemToQueueEndpoint {
        uri: uri.into(),
        device_id: None,
    }
}

#[derive(Clone, Copy, Debug, Default, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RepeatMode {
    Track,
    Context,
    #[default]
    Off,
}

mod private {
    use super::{After, Before, Unspecified};

    pub trait Sealed {}

    impl Sealed for After {}
    impl Sealed for Before {}
    impl Sealed for Unspecified {}
}

pub trait TimestampMarker: private::Sealed + Debug {}
impl TimestampMarker for Before {}
impl TimestampMarker for After {}
impl TimestampMarker for Unspecified {}

#[derive(Clone, Copy, Debug, Default)]
pub struct After;

#[derive(Clone, Copy, Debug, Default)]
pub struct Before;

#[derive(Clone, Copy, Debug, Default)]
pub struct Unspecified;

#[derive(Clone, Debug, Default, Serialize)]
pub struct TransferPlaybackEndpoint {
    pub(crate) device_ids: Vec<String>,
    pub(crate) play: Option<bool>,
}

impl TransferPlaybackEndpoint {
    /// If `true`, ensure playback happens on the new device.
    /// Otherwise, keep the current playback state.
    pub fn play(mut self, play: bool) -> Self {
        self.play = Some(play);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify.put("/me/player".to_owned(), Body::Json(self)).await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct StartPlaybackEndpoint {
    #[serde(skip)]
    pub(crate) device_id: Option<String>,
    pub(crate) context_uri: Option<String>,
    pub(crate) uris: Option<Vec<String>>,
    pub(crate) offset: Option<Value>,
    pub(crate) position_ms: Option<u32>,
}

impl StartPlaybackEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    /// The *URI* of the context to play. Valid contexts are albums, artists and playlists.
    pub fn context_uri(mut self, context_uri: impl Into<String>) -> Self {
        self.context_uri = Some(context_uri.into());
        self
    }

    /// The *URI*s of the tracks to play.
    pub fn uris(mut self, uris: &[&str]) -> Self {
        self.uris = Some(uris.iter().map(ToString::to_string).collect());
        self
    }

    #[doc = include_str!("../docs/offset.md")]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(json!({ "position": offset }));
        self
    }

    /// The *URI* of the track to start/resume playback.
    /// The track must be in the context specified by `context_uri`.
    pub fn offset_uri(mut self, uri: &str) -> Self {
        self.offset = Some(json!({ "uri": uri }));
        self
    }

    /// The position at which to start/resume the playback.
    pub fn position_ms(mut self, position_ms: u32) -> Self {
        self.position_ms = Some(position_ms);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        let endpoint = match self.device_id {
            Some(ref id) => format!("/me/player/play?device_id={id}"),
            None => "/me/player/play".to_owned(),
        };

        spotify.put(endpoint, Body::Json(self)).await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct SeekToPositionEndpoint {
    pub(crate) position_ms: u32,
    pub(crate) device_id: Option<String>,
}

impl SeekToPositionEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify
            .request(Method::PUT, "/me/player/seek".to_owned(), self.into(), None)
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct SetRepeatModeEndpoint {
    pub(crate) state: RepeatMode,
    pub(crate) device_id: Option<String>,
}

impl SetRepeatModeEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify
            .request(
                Method::PUT,
                "/me/player/repeat".to_owned(),
                self.into(),
                None,
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct SetPlaybackVolumeEndpoint {
    pub(crate) volume_percent: u32,
    pub(crate) device_id: Option<String>,
}

impl SetPlaybackVolumeEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify
            .request(
                Method::PUT,
                "/me/player/volume".to_owned(),
                self.into(),
                None,
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct ToggleShuffleEndpoint {
    pub(crate) state: bool,
    pub(crate) device_id: Option<String>,
}

impl ToggleShuffleEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify
            .request(
                Method::PUT,
                "/me/player/shuffle".to_owned(),
                self.into(),
                None,
            )
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct RecentlyPlayedTracksEndpoint<T: TimestampMarker = Unspecified> {
    pub(crate) limit: Option<u32>,
    pub(crate) after: Option<u64>,
    pub(crate) before: Option<u64>,
    marker: PhantomData<T>,
}

impl RecentlyPlayedTracksEndpoint<Unspecified> {
    /// A Unix timestamp in miliseconds. Returns all items after (but not including) this cursor position.
    pub fn after(self, after: u64) -> RecentlyPlayedTracksEndpoint<After> {
        RecentlyPlayedTracksEndpoint {
            limit: self.limit,
            after: Some(after),
            before: self.before,
            marker: PhantomData,
        }
    }

    /// A Unix timestamp in miliseconds. Returns all items before (but not including) this cursor position.
    pub fn before(self, before: u64) -> RecentlyPlayedTracksEndpoint<Before> {
        RecentlyPlayedTracksEndpoint {
            limit: self.limit,
            after: self.after,
            before: Some(before),
            marker: PhantomData,
        }
    }
}

impl<T: TimestampMarker + Default> RecentlyPlayedTracksEndpoint<T> {
    #[doc = include_str!("../docs/limit.md")]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn get(
        self,
        spotify: &Client<impl AuthFlow + Authorised>,
    ) -> Result<CursorPage<PlayHistory, Self>> {
        spotify
            .get("/me/player/recently-played".to_owned(), self)
            .await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct AddItemToQueueEndpoint {
    pub(crate) uri: String,
    pub(crate) device_id: Option<String>,
}

impl AddItemToQueueEndpoint {
    #[doc = include_str!("../docs/device_id.md")]
    pub fn device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    #[doc = include_str!("../docs/send.md")]
    pub async fn send(self, spotify: &Client<impl AuthFlow + Authorised>) -> Result<Nil> {
        spotify
            .request(
                Method::POST,
                "/me/player/queue".to_owned(),
                self.into(),
                None,
            )
            .await
    }
}