spotify_web_api 0.2.0

A wrapper for the Spotify Web 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
use super::{ContextType, Cursors, EpisodeId, ExternalUrls, ItemType, Track, TrackId, TrackItem};
use serde::{Deserialize, Serialize};

/// A playback device (speaker, phone, computer, etc.).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Device {
    /// The device ID. This ID is unique and persistent to some extent.
    /// However, this is not guaranteed and any cached `device_id` should periodically be cleared out and refetched as necessary.
    pub id: Option<String>,

    /// If this device is the currently active device.
    pub is_active: bool,

    /// If this device is currently in a private session.
    pub is_private_session: bool,

    /// Whether controlling this device is restricted.
    /// At present if this is "true" then no Web API commands will be accepted by this device.
    pub is_restricted: bool,

    /// A human-readable name for the device. Some devices have a name that the user can configure (e.g. "Loudest speaker")
    /// and some devices have a generic name associated with the manufacturer or device model.
    pub name: String,

    #[serde(rename = "type")]
    /// Device type, such as "computer", "smartphone" or "speaker".
    pub type_: String,

    /// The current volume in percent.
    pub volume_percent: Option<u8>,

    /// If this device can be used to set the volume.
    pub supports_volume: bool,
}

/// A list of available playback devices.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Devices {
    /// The list of devices.
    #[serde(default)]
    pub devices: Vec<Device>,
}

/// The repeat mode state for playback.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum RepeatState {
    Track,
    Context,
    Off,
}

impl std::fmt::Display for RepeatState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Track => "track",
            Self::Context => "context",
            Self::Off => "off",
        };
        write!(f, "{s}")
    }
}

/// The playback context (album, playlist, artist, etc.).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Context {
    /// The object type.
    #[serde(rename = "type")]
    pub type_: ItemType,

    /// A link to the Web API endpoint providing full details of the track.
    pub href: Option<String>,

    /// External URLs for this context.
    pub external_urls: ExternalUrls,

    /// The Spotify URI for the context.
    pub uri: String,
}

/// The type of the currently playing item.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum CurrentlyPlayingType {
    Track,
    Episode,
    Ad,
    Unknown,
}

/// The current playback state including device, track, and progress.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlaybackState {
    /// The device that is currently active.
    pub device: Device,

    /// off, track, context
    pub repeat_state: RepeatState,

    /// If shuffle is on or off.
    pub shuffle_state: bool,

    /// The context object.
    pub context: Option<Context>,

    /// Unix Millisecond Timestamp when data was fetched.
    pub timestamp: Option<i64>,

    /// Progress into the currently playing track or episode.
    pub progress_ms: Option<u32>,

    /// If something is currently playing, return true.
    pub is_playing: bool,

    /// The currently playing track or episode.
    pub item: Option<TrackItem>,

    /// The object type of the currently playing item. Can be one of track, episode, ad or unknown.
    pub currently_playing_type: CurrentlyPlayingType,

    /// Allows to update the user interface based on which playback actions are available within the current context.
    pub actions: Actions,
}

/// Available playback actions in the current context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Actions {
    /// Interrupting playback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interrupting_playback: Option<bool>,

    /// Pausing playback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pausing: Option<bool>,

    /// Resuming playback.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resuming: Option<bool>,

    /// Seeking playback location.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seeking: Option<bool>,

    /// Skipping to the next context.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skipping_next: Option<bool>,

    /// Skipping to the previous context.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skipping_prev: Option<bool>,

    /// Toggling repeat context flag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toggling_repeat_context: Option<bool>,

    /// Toggling shuffle flag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toggling_shuffle: Option<bool>,

    /// Toggling repeat track flag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub toggling_repeat_track: Option<bool>,

    /// Transferring playback between devices.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transferring_playback: Option<bool>,
}

/// Information about the currently playing track or episode.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CurrentlyPlaying {
    /// The context object.
    pub context: Option<Context>,

    /// Unix Millisecond Timestamp when data was fetched.
    pub timestamp: Option<i64>,

    /// Progress into the currently playing track or episode.
    pub progress_ms: Option<u32>,

    /// If something is currently playing, return true.
    pub is_playing: bool,

    /// The currently playing track or episode.
    pub item: Option<TrackItem>,

    /// The object type of the currently playing item. Can be one of track, episode, ad or unknown.
    pub currently_playing_type: CurrentlyPlayingType,

    /// Allows to update the user interface based on which playback actions are available within the current context.
    pub actions: Actions,
}

/// A track in the user's play history.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PlayHistory {
    /// The track the user listened to.
    pub track: Track,

    /// The date and time the track was played.
    pub played_at: String,

    /// The context the track was played from.
    pub context: Context,
}

/// A list of recently played tracks.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RecentlyPlayedTracks {
    /// A link to the Web API endpoint returning the full result of the request.
    pub href: String,

    /// The maximum number of items in the response (as set in the query or by default).
    pub limit: usize,

    /// URL to the next page of items.
    pub next: Option<String>,

    /// The cursors used to find the next set of items.
    pub cursors: Option<Cursors>,

    /// The total number of items available to return.
    pub total: Option<usize>,

    /// The play history items.
    pub items: Vec<PlayHistory>,
}

/// The user's playback queue.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Queue {
    /// The currently playing track or episode.
    pub currently_playing: Option<TrackItem>,

    /// The tracks or episodes in the queue.
    pub queue: Vec<TrackItem>,
}

/// An offset for starting playback at a specific position or URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Offset {
    Position(usize),
    Uri(ContextType),
}

impl From<usize> for Offset {
    fn from(position: usize) -> Self {
        Self::Position(position)
    }
}

/// A time range for querying recently played tracks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QueryRange {
    Before(i64),
    After(i64),
}

/// An item that can be added to a playlist (track or episode).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlaylistItem {
    Track(TrackId),
    Episode(EpisodeId),
}

impl From<TrackId> for PlaylistItem {
    fn from(track: TrackId) -> Self {
        Self::Track(track)
    }
}

impl From<EpisodeId> for PlaylistItem {
    fn from(episode: EpisodeId) -> Self {
        Self::Episode(episode)
    }
}

impl std::fmt::Display for PlaylistItem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Track(track) => track.uri(),
            Self::Episode(episode) => episode.uri(),
        };
        write!(f, "{s}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn playback_state() {
        let json = r#"
        {
			"device": {
				"id": "string",
				"is_active": false,
				"is_private_session": false,
				"is_restricted": false,
				"name": "Kitchen speaker",
				"type": "computer",
				"volume_percent": 59,
				"supports_volume": false
			},
			"repeat_state": "off",
			"shuffle_state": false,
			"context": {
				"type": "track",
				"href": "string",
				"external_urls": {
					"spotify": "string"
				},
				"uri": "string"
			},
			"timestamp": 0,
			"progress_ms": 0,
			"is_playing": false,
			"item": {
				"album": {
					"album_type": "compilation",
					"total_tracks": 9,
					"available_markets": ["CA", "BR", "IT"],
					"external_urls": {
						"spotify": "string"
					},
					"href": "string",
					"id": "2up3OPMp9Tb4dAKM2erWXQ",
					"images": [
						{
							"url": "https://i.scdn.co/image/ab67616d00001e02ff9ca10b55ce82ae553c8228",
							"height": 300,
							"width": 300
						}
					],
					"name": "string",
					"release_date": "1981-12",
					"release_date_precision": "year",
					"restrictions": {
						"reason": "market"
					},
					"type": "album",
					"uri": "spotify:album:2up3OPMp9Tb4dAKM2erWXQ",
					"artists": [
						{
							"external_urls": {
								"spotify": "string"
							},
							"href": "string",
							"id": "string",
							"name": "string",
							"type": "artist",
							"uri": "string"
						}
					]
				},
				"artists": [
					{
						"external_urls": {
							"spotify": "string"
						},
						"followers": {
							"href": "string",
							"total": 0
						},
						"genres": ["Prog rock", "Grunge"],
						"href": "string",
						"id": "string",
						"images": [
							{
								"url": "https://i.scdn.co/image/ab67616d00001e02ff9ca10b55ce82ae553c8228",
								"height": 300,
								"width": 300
							}
						],
						"name": "string",
						"popularity": 0,
						"type": "artist",
						"uri": "string"
					}
				],
				"available_markets": ["US"],
				"disc_number": 0,
				"duration_ms": 0,
				"explicit": false,
				"external_ids": {
					"isrc": "string",
					"ean": "string",
					"upc": "string"
				},
				"external_urls": {
					"spotify": "string"
				},
				"href": "string",
				"id": "string",
				"is_playable": false,
				"linked_from": {},
				"restrictions": {
					"reason": "string"
				},
				"name": "string",
				"popularity": 0,
				"preview_url": "string",
				"track_number": 0,
				"type": "track",
				"uri": "string",
				"is_local": false
			},
			"currently_playing_type": "unknown",
			"actions": {
				"interrupting_playback": false,
				"pausing": false,
				"resuming": false,
				"seeking": false,
				"skipping_next": false,
				"skipping_prev": false,
				"toggling_repeat_context": false,
				"toggling_shuffle": false,
				"toggling_repeat_track": false,
				"transferring_playback": false
			}
        }
        "#;

        crate::test::assert_deserialized!(PlaybackState, json);
    }
}