-
Notifications
You must be signed in to change notification settings - Fork 295
/
playlist.go
701 lines (624 loc) · 25.8 KB
/
playlist.go
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
package spotify
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
// PlaylistTracks contains details about the tracks in a playlist.
type PlaylistTracks struct {
// A link to the Web API endpoint where full details of
// the playlist's tracks can be retrieved.
Endpoint string `json:"href"`
// The total number of tracks in the playlist.
Total Numeric `json:"total"`
}
// SimplePlaylist contains basic info about a Spotify playlist.
type SimplePlaylist struct {
// Indicates whether the playlist owner allows others to modify the playlist.
// Note: only non-collaborative playlists are currently returned by Spotify's Web API.
Collaborative bool `json:"collaborative"`
// The playlist description. Empty string if no description is set.
Description string `json:"description"`
ExternalURLs map[string]string `json:"external_urls"`
// A link to the Web API endpoint providing full details of the playlist.
Endpoint string `json:"href"`
ID ID `json:"id"`
// The playlist image. Note: this field is only returned for modified,
// verified playlists. Otherwise the slice is empty. If returned, the source
// URL for the image is temporary and will expire in less than a day.
Images []Image `json:"images"`
Name string `json:"name"`
Owner User `json:"owner"`
IsPublic bool `json:"public"`
// The version identifier for the current playlist. Can be supplied in other
// requests to target a specific playlist version.
SnapshotID string `json:"snapshot_id"`
// A collection to the Web API endpoint where full details of the playlist's
// tracks can be retrieved, along with the total number of tracks in the playlist.
Tracks PlaylistTracks `json:"tracks"`
URI URI `json:"uri"`
}
// FullPlaylist provides extra playlist data in addition to the data provided by [SimplePlaylist].
type FullPlaylist struct {
SimplePlaylist
// Information about the followers of this playlist.
Followers Followers `json:"followers"`
Tracks PlaylistTrackPage `json:"tracks"`
}
// FeaturedPlaylists gets a [list of playlists featured by Spotify].
//
// Supported options: [Locale], [Country], [Timestamp], [Limit], [Offset].
//
// [list of playlists featured by Spotify]: https://developer.spotify.com/documentation/web-api/reference/get-featured-playlists
func (c *Client) FeaturedPlaylists(ctx context.Context, opts ...RequestOption) (message string, playlists *SimplePlaylistPage, e error) {
spotifyURL := c.baseURL + "browse/featured-playlists"
if params := processOptions(opts...).urlParams.Encode(); params != "" {
spotifyURL += "?" + params
}
var result struct {
Playlists SimplePlaylistPage `json:"playlists"`
Message string `json:"message"`
}
err := c.get(ctx, spotifyURL, &result)
if err != nil {
return "", nil, err
}
return result.Message, &result.Playlists, nil
}
// FollowPlaylist [adds the current user as a follower] of the specified
// playlist. Any playlist can be followed, regardless of its private/public
// status, as long as you know the playlist ID.
//
// If the public argument is true, then the playlist will be included in the
// user's public playlists. To be able to follow playlists privately, the user
// must have granted the [ScopePlaylistModifyPrivate] scope. The
// [ScopePlaylistModifyPublic] scope is required to follow playlists publicly.
//
// [adds the current user as a follower]: https://developer.spotify.com/documentation/web-api/reference/follow-playlist
func (c *Client) FollowPlaylist(ctx context.Context, playlist ID, public bool) error {
spotifyURL := buildFollowURI(c.baseURL, playlist)
body := strings.NewReader(strconv.FormatBool(public))
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
return c.execute(req, nil)
}
// UnfollowPlaylist [removes the current user as a follower of a playlist].
// Unfollowing a publicly followed playlist requires [ScopePlaylistModifyPublic].
// Unfolowing a privately followed playlist requies [ScopePlaylistModifyPrivate].
//
// [removes the current user as a follower of a playlist]: https://developer.spotify.com/documentation/web-api/reference/unfollow-playlist
func (c *Client) UnfollowPlaylist(ctx context.Context, playlist ID) error {
spotifyURL := buildFollowURI(c.baseURL, playlist)
req, err := http.NewRequestWithContext(ctx, "DELETE", spotifyURL, nil)
if err != nil {
return err
}
return c.execute(req, nil)
}
func buildFollowURI(url string, playlist ID) string {
return fmt.Sprintf("%splaylists/%s/followers",
url, string(playlist))
}
// GetPlaylistsForUser [gets a list of the playlists] owned or followed by a
// particular Spotify user.
//
// Private playlists and collaborative playlists are only retrievable for the
// current user. In order to read private playlists, the user must have granted
// the [ScopePlaylistReadPrivate] scope. Note that this scope alone will not
// return collaborative playlists, even though they are always private. In
// order to read collaborative playlists, the user must have granted the
// [ScopePlaylistReadCollaborative] scope.
//
// Supported options: [Limit], [Offset].
//
// [gets a list of the playlists]: https://developer.spotify.com/documentation/web-api/reference/get-list-users-playlists
func (c *Client) GetPlaylistsForUser(ctx context.Context, userID string, opts ...RequestOption) (*SimplePlaylistPage, error) {
spotifyURL := c.baseURL + "users/" + userID + "/playlists"
if params := processOptions(opts...).urlParams.Encode(); params != "" {
spotifyURL += "?" + params
}
var result SimplePlaylistPage
err := c.get(ctx, spotifyURL, &result)
if err != nil {
return nil, err
}
return &result, err
}
// GetPlaylist [fetches a playlist] from spotify.
//
// Supported options: [Fields].
//
// [fetches a playlist]: https://developer.spotify.com/documentation/web-api/reference/get-playlist
func (c *Client) GetPlaylist(ctx context.Context, playlistID ID, opts ...RequestOption) (*FullPlaylist, error) {
spotifyURL := fmt.Sprintf("%splaylists/%s", c.baseURL, playlistID)
if params := processOptions(opts...).urlParams.Encode(); params != "" {
spotifyURL += "?" + params
}
var playlist FullPlaylist
err := c.get(ctx, spotifyURL, &playlist)
if err != nil {
return nil, err
}
return &playlist, err
}
// GetPlaylistTracks [gets full details of the tracks in a playlist], given the
// playlist's Spotify ID.
//
// Supported options: [Limit], [Offset], [Market], [Fields].
//
// Deprecated: the Spotify api is moving towards supporting both tracks and episodes. Use [GetPlaylistItems] which
// supports these.
func (c *Client) GetPlaylistTracks(
ctx context.Context,
playlistID ID,
opts ...RequestOption,
) (*PlaylistTrackPage, error) {
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID)
if params := processOptions(opts...).urlParams.Encode(); params != "" {
spotifyURL += "?" + params
}
var result PlaylistTrackPage
err := c.get(ctx, spotifyURL, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// PlaylistItem contains info about an item in a playlist.
type PlaylistItem struct {
// The date and time the track was added to the playlist.
// You can use [TimestampLayout] to convert
// this field to a [time.Time].
// Warning: very old playlists may not populate this value.
AddedAt string `json:"added_at"`
// The Spotify user who added the track to the playlist.
// Warning: very old playlists may not populate this value.
AddedBy User `json:"added_by"`
// Whether this track is a local file or not.
IsLocal bool `json:"is_local"`
// Information about the track.
Track PlaylistItemTrack `json:"track"`
}
// PlaylistItemTrack is a union type for both tracks and episodes. If both
// values are null, it's likely that the piece of content is not available in
// the configured market.
type PlaylistItemTrack struct {
Track *FullTrack
Episode *EpisodePage
}
// UnmarshalJSON customises the unmarshalling based on the type flags set.
func (t *PlaylistItemTrack) UnmarshalJSON(b []byte) error {
// Spotify API will return `track: null`` where the content is not available
// in the specified market. We should respect this and just pass the null
// up...
if bytes.Equal(b, []byte("null")) {
return nil
}
itemType := struct {
Type string `json:"type"`
}{}
err := json.Unmarshal(b, &itemType)
if err != nil {
return err
}
switch itemType.Type {
case "episode":
return json.Unmarshal(b, &t.Episode)
case "track":
return json.Unmarshal(b, &t.Track)
default:
return fmt.Errorf("unrecognized item type: %s", itemType.Type)
}
}
// PlaylistItemPage contains information about items in a playlist.
type PlaylistItemPage struct {
basePage
Items []PlaylistItem `json:"items"`
}
// GetPlaylistItems [gets full details of the items in a playlist], given the
// playlist's [Spotify ID].
//
// Supported options: [Limit], [Offset], [Market], [Fields].
//
// [gets full details of the items in a playlist]: https://developer.spotify.com/documentation/web-api/reference/get-playlists-tracks
// [Spotify ID]: https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
func (c *Client) GetPlaylistItems(ctx context.Context, playlistID ID, opts ...RequestOption) (*PlaylistItemPage, error) {
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID)
// Add default as the first option so it gets override by url.Values#Set
opts = append([]RequestOption{AdditionalTypes(EpisodeAdditionalType, TrackAdditionalType)}, opts...)
if params := processOptions(opts...).urlParams.Encode(); params != "" {
spotifyURL += "?" + params
}
var result PlaylistItemPage
err := c.get(ctx, spotifyURL, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// CreatePlaylistForUser [creates a playlist] for a Spotify user.
// The playlist will be empty until you add tracks to it.
// The playlistName does not need to be unique - a user can have
// several playlists with the same name.
//
// Creating a public playlist for a user requires [ScopePlaylistModifyPublic];
// creating a private playlist requires [ScopePlaylistModifyPrivate].
//
// On success, the newly created playlist is returned.
//
// [creates a playlist]: https://developer.spotify.com/documentation/web-api/reference/create-playlist
func (c *Client) CreatePlaylistForUser(ctx context.Context, userID, playlistName, description string, public bool, collaborative bool) (*FullPlaylist, error) {
spotifyURL := fmt.Sprintf("%susers/%s/playlists", c.baseURL, userID)
body := struct {
Name string `json:"name"`
Public bool `json:"public"`
Description string `json:"description"`
Collaborative bool `json:"collaborative"`
}{
playlistName,
public,
description,
collaborative,
}
bodyJSON, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", spotifyURL, bytes.NewReader(bodyJSON))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
var p FullPlaylist
err = c.execute(req, &p, http.StatusCreated)
if err != nil {
return nil, err
}
return &p, nil
}
// ChangePlaylistName [changes the name of a playlist]. This call requires that the
// user has authorized the [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate]
// scopes (depending on whether the playlist is public or private).
// The current user must own the playlist in order to modify it.
//
// [changes the name of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details
func (c *Client) ChangePlaylistName(ctx context.Context, playlistID ID, newName string) error {
return c.modifyPlaylist(ctx, playlistID, newName, "", nil)
}
// ChangePlaylistAccess [modifies the public/private status of a playlist]. This call
// requires that the user has authorized the [ScopePlaylistModifyPublic] or
// [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is
// currently public or private). The current user must own the playlist to modify it.
//
// [modifies the public/private status of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details
func (c *Client) ChangePlaylistAccess(ctx context.Context, playlistID ID, public bool) error {
return c.modifyPlaylist(ctx, playlistID, "", "", &public)
}
// ChangePlaylistDescription [modifies the description of a playlist]. This call
// requires that the user has authorized the [ScopePlaylistModifyPublic] or
// [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is
// currently public or private). The current user must own the playlist to modify it.
//
// [modifies the description of a playlist]: https://developer.spotify.com/documentation/web-api/reference/change-playlist-details
func (c *Client) ChangePlaylistDescription(ctx context.Context, playlistID ID, newDescription string) error {
return c.modifyPlaylist(ctx, playlistID, "", newDescription, nil)
}
// ChangePlaylistNameAndAccess combines [ChangePlaylistName] and [ChangePlaylistAccess] into
// a single Web API call. It requires that the user has authorized the [ScopePlaylistModifyPublic]
// or [ScopePlaylistModifyPrivate] scopes (depending on whether the playlist is currently
// public or private). The current user must own the playlist to modify it.
func (c *Client) ChangePlaylistNameAndAccess(ctx context.Context, playlistID ID, newName string, public bool) error {
return c.modifyPlaylist(ctx, playlistID, newName, "", &public)
}
// ChangePlaylistNameAccessAndDescription combines [ChangePlaylistName], [ChangePlaylistAccess], and
// [ChangePlaylistDescription] into a single Web API call. It requires that the user has authorized
// the [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate] scopes (depending on whether the
// playlist is currently public or private). The current user must own the playlist in order to modify it.
func (c *Client) ChangePlaylistNameAccessAndDescription(ctx context.Context, playlistID ID, newName, newDescription string, public bool) error {
return c.modifyPlaylist(ctx, playlistID, newName, newDescription, &public)
}
func (c *Client) modifyPlaylist(ctx context.Context, playlistID ID, newName, newDescription string, public *bool) error {
body := struct {
Name string `json:"name,omitempty"`
Public *bool `json:"public,omitempty"`
Description string `json:"description,omitempty"`
}{
newName,
public,
newDescription,
}
bodyJSON, err := json.Marshal(body)
if err != nil {
return err
}
spotifyURL := fmt.Sprintf("%splaylists/%s", c.baseURL, string(playlistID))
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(bodyJSON))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
return c.execute(req, nil, http.StatusCreated)
}
// AddTracksToPlaylist [adds one or more tracks to a user's playlist].
// This call requires [ScopePlaylistModifyPublic] or [ScopePlaylistModifyPrivate].
// A maximum of 100 tracks can be added per call. It returns a snapshot ID that
// can be used to identify this version (the new version) of the playlist in
// future requests.
//
// [adds one or more tracks to a user's playlist]: https://developer.spotify.com/documentation/web-api/reference/add-tracks-to-playlist
func (c *Client) AddTracksToPlaylist(ctx context.Context, playlistID ID, trackIDs ...ID) (snapshotID string, err error) {
uris := make([]string, len(trackIDs))
for i, id := range trackIDs {
uris[i] = fmt.Sprintf("spotify:track:%s", id)
}
m := make(map[string]interface{})
m["uris"] = uris
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks",
c.baseURL, string(playlistID))
body, err := json.Marshal(m)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, "POST", spotifyURL, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
result := struct {
SnapshotID string `json:"snapshot_id"`
}{}
err = c.execute(req, &result, http.StatusCreated)
if err != nil {
return "", err
}
return result.SnapshotID, nil
}
// RemoveTracksFromPlaylist [removes one or more tracks from a user's playlist].
// This call requires that the user has authorized the [ScopePlaylistModifyPublic]
// or [ScopePlaylistModifyPrivate] scopes.
//
// If the track(s) occur multiple times in the specified playlist, then all occurrences
// of the track will be removed. If successful, the snapshot ID returned can be used to
// identify the playlist version in future requests.
//
// [removes one or more tracks from a user's playlist]: https://developer.spotify.com/documentation/web-api/reference/remove-tracks-playlist
func (c *Client) RemoveTracksFromPlaylist(ctx context.Context, playlistID ID, trackIDs ...ID) (newSnapshotID string, err error) {
tracks := make([]struct {
URI string `json:"uri"`
}, len(trackIDs))
for i, u := range trackIDs {
tracks[i].URI = fmt.Sprintf("spotify:track:%s", u)
}
return c.removeTracksFromPlaylist(ctx, playlistID, tracks, "")
}
// TrackToRemove specifies a track to be removed from a playlist.
// Positions is a slice of 0-based track indices.
// TrackToRemove is used with RemoveTracksFromPlaylistOpt.
type TrackToRemove struct {
URI string `json:"uri"`
Positions []int `json:"positions"`
}
// NewTrackToRemove returns a [TrackToRemove] with the specified
// track ID and playlist locations.
func NewTrackToRemove(trackID string, positions []int) TrackToRemove {
return TrackToRemove{
URI: fmt.Sprintf("spotify:track:%s", trackID),
Positions: positions,
}
}
// RemoveTracksFromPlaylistOpt is like [RemoveTracksFromPlaylist], but it supports
// optional parameters that offer more fine-grained control. Instead of deleting
// all occurrences of a track, this function takes an index with each track URI
// that indicates the position of the track in the playlist.
//
// In addition, the snapshotID parameter allows you to specify the snapshot ID
// against which you want to make the changes. Spotify will validate that the
// specified tracks exist in the specified positions and make the changes, even
// if more recent changes have been made to the playlist. If a track in the
// specified position is not found, the entire request will fail and no edits
// will take place. (Note: the snapshot is optional, pass the empty string if
// you don't care about it.)
func (c *Client) RemoveTracksFromPlaylistOpt(
ctx context.Context,
playlistID ID,
tracks []TrackToRemove,
snapshotID string,
) (newSnapshotID string, err error) {
return c.removeTracksFromPlaylist(ctx, playlistID, tracks, snapshotID)
}
func (c *Client) removeTracksFromPlaylist(
ctx context.Context,
playlistID ID,
tracks interface{},
snapshotID string,
) (newSnapshotID string, err error) {
m := make(map[string]interface{})
m["tracks"] = tracks
if snapshotID != "" {
m["snapshot_id"] = snapshotID
}
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks",
c.baseURL, string(playlistID))
body, err := json.Marshal(m)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, "DELETE", spotifyURL, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
result := struct {
SnapshotID string `json:"snapshot_id"`
}{}
err = c.execute(req, &result)
if err != nil {
return "", err
}
return result.SnapshotID, err
}
// ReplacePlaylistTracks [replaces all of the tracks in a playlist], overwriting its
// existing tracks This can be useful for replacing or reordering tracks, or for
// clearing a playlist.
//
// Modifying a public playlist requires that the user has authorized the
// [ScopePlaylistModifyPublic] scope. Modifying a private playlist requires the
// [ScopePlaylistModifyPrivate] scope.
//
// A maximum of 100 tracks are permitted in this call. Additional tracks must be
// added via [AddTracksToPlaylist].
//
// [replaces all of the tracks in a playlist]: https://developer.spotify.com/documentation/web-api/reference/reorder-or-replace-playlists-tracks
func (c *Client) ReplacePlaylistTracks(ctx context.Context, playlistID ID, trackIDs ...ID) error {
trackURIs := make([]string, len(trackIDs))
for i, u := range trackIDs {
trackURIs[i] = fmt.Sprintf("spotify:track:%s", u)
}
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks?uris=%s",
c.baseURL, playlistID, strings.Join(trackURIs, ","))
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, nil)
if err != nil {
return err
}
return c.execute(req, nil, http.StatusCreated)
}
// ReplacePlaylistItems [replaces all the items in a playlist], overwriting its
// existing tracks This can be useful for replacing or reordering tracks, or for
// clearing a playlist.
//
// Modifying a public playlist requires that the user has authorized the
// [ScopePlaylistModifyPublic] scope. Modifying a private playlist requires the
// [ScopePlaylistModifyPrivate] scope.
//
// A maximum of 100 tracks is permited in this call. Additional tracks must be
// added via AddTracksToPlaylist.
//
// [replaces all the items in a playlist]: https://developer.spotify.com/documentation/web-api/reference/reorder-or-replace-playlists-tracks
func (c *Client) ReplacePlaylistItems(ctx context.Context, playlistID ID, items ...URI) (string, error) {
m := make(map[string]interface{})
m["uris"] = items
body, err := json.Marshal(m)
if err != nil {
return "", err
}
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID)
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
result := struct {
SnapshotID string `json:"snapshot_id"`
}{}
err = c.execute(req, &result, http.StatusCreated)
if err != nil {
return "", err
}
return result.SnapshotID, nil
}
// UserFollowsPlaylist [checks if one or more (up to 5) users are following]
// a Spotify playlist, given the playlist's owner and ID.
//
// Checking if a user follows a playlist publicly doesn't require any scopes.
// Checking if the user is privately following a playlist is only possible for the
// current user when that user has granted access to the [ScopePlaylistReadPrivate] scope.
//
// [checks if one or more (up to 5) users are following]: https://developer.spotify.com/documentation/web-api/reference/check-if-user-follows-playlist
func (c *Client) UserFollowsPlaylist(ctx context.Context, playlistID ID, userIDs ...string) ([]bool, error) {
spotifyURL := fmt.Sprintf("%splaylists/%s/followers/contains?ids=%s",
c.baseURL, playlistID, strings.Join(userIDs, ","))
follows := make([]bool, len(userIDs))
err := c.get(ctx, spotifyURL, &follows)
if err != nil {
return nil, err
}
return follows, nil
}
// PlaylistReorderOptions is used with ReorderPlaylistTracks to reorder
// a track or group of tracks in a playlist.
//
// For example, in a playlist with 10 tracks, you can:
//
// - move the first track to the end of the playlist by setting
// RangeStart to 0 and InsertBefore to 10
// - move the last track to the beginning of the playlist by setting
// RangeStart to 9 and InsertBefore to 0
// - Move the last 2 tracks to the beginning of the playlist by setting
// RangeStart to 8 and RangeLength to 2.
type PlaylistReorderOptions struct {
// The position of the first track to be reordered.
// This field is required.
RangeStart Numeric `json:"range_start"`
// The amount of tracks to be reordered. This field is optional. If
// you don't set it, the value 1 will be used.
RangeLength Numeric `json:"range_length,omitempty"`
// The position where the tracks should be inserted. To reorder the
// tracks to the end of the playlist, simply set this to the position
// after the last track. This field is required.
InsertBefore Numeric `json:"insert_before"`
// The playlist's snapshot ID against which you wish to make the changes.
// This field is optional.
SnapshotID string `json:"snapshot_id,omitempty"`
}
// ReorderPlaylistTracks reorders a track or group of tracks in a playlist. It
// returns a snapshot ID that can be used to identify the (newly modified) playlist
// version in future requests.
//
// See the docs for [PlaylistReorderOptions] for information on how the reordering
// works.
//
// Reordering tracks in the current user's public playlist requires [ScopePlaylistModifyPublic].
// Reordering tracks in the user's private playlists (including collaborative playlists) requires
// [ScopePlaylistModifyPrivate].
func (c *Client) ReorderPlaylistTracks(ctx context.Context, playlistID ID, opt PlaylistReorderOptions) (snapshotID string, err error) {
spotifyURL := fmt.Sprintf("%splaylists/%s/tracks", c.baseURL, playlistID)
j, err := json.Marshal(opt)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, bytes.NewReader(j))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
result := struct {
SnapshotID string `json:"snapshot_id"`
}{}
err = c.execute(req, &result)
if err != nil {
return "", err
}
return result.SnapshotID, nil
}
// SetPlaylistImage replaces the image used to represent a playlist.
// This action can only be performed by the owner of the playlist,
// and requires [ScopeImageUpload] as well as [ScopeModifyPlaylistPublic] or
// [ScopeModifyPlaylistPrivate].
func (c *Client) SetPlaylistImage(ctx context.Context, playlistID ID, img io.Reader) error {
spotifyURL := fmt.Sprintf("%splaylists/%s/images", c.baseURL, playlistID)
// data flow:
// img (reader) -> copy into base64 encoder (writer) -> pipe (write end)
// pipe (read end) -> request body
r, w := io.Pipe()
go func() {
enc := base64.NewEncoder(base64.StdEncoding, w)
_, err := io.Copy(enc, img)
_ = enc.Close()
_ = w.CloseWithError(err)
}()
req, err := http.NewRequestWithContext(ctx, "PUT", spotifyURL, r)
if err != nil {
return err
}
req.Header.Set("Content-Type", "image/jpeg")
return c.execute(req, nil, http.StatusAccepted)
}