Class: RSpotify::Playlist

Inherits:
Base
  • Object
show all
Defined in:
lib/rspotify/playlist.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#external_urls, #href, #id, #type, #uri

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#method_missing, #respond_to?

Constructor Details

#initialize(options = {}) ⇒ Playlist

Returns a new instance of Playlist.



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
# File 'lib/rspotify/playlist.rb', line 74

def initialize(options = {})
  @collaborative = options['collaborative']
  @description   = options['description']
  @followers     = options['followers']
  @images        = options['images']
  @name          = options['name']
  @public        = options['public']
  @snapshot_id   = options['snapshot_id']
  @total         = options['tracks']['total']

  @owner = if options['owner']
    User.new options['owner']
  end

  tracks = options['tracks']['items'] if options['tracks']
  tracks.select! { |t| t['track'] } if tracks

  @tracks_cache = if tracks
    tracks.map { |t| Track.new t['track'] }
  end

  @tracks_added_at = hash_for(tracks, 'added_at') do |added_at|
    Time.parse added_at
  end

  @tracks_added_by = hash_for(tracks, 'added_by') do |added_by|
    User.new added_by
  end

  super(options)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class RSpotify::Base

Instance Attribute Details

#collaborativeBoolean

true if the owner allows other users to modify the playlist

Returns:

  • (Boolean)

    the current value of collaborative



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def collaborative
  @collaborative
end

#descriptionString

The playlist description

Returns:

  • (String)

    the current value of description



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def description
  @description
end

#followersHash

Information about the followers of the playlist

Returns:

  • (Hash)

    the current value of followers



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def followers
  @followers
end

#imagesArray<Hash>

The playlist images

Returns:

  • (Array<Hash>)

    the current value of images



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def images
  @images
end

#nameString

The name of the playlist

Returns:

  • (String)

    the current value of name



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def name
  @name
end

#ownerUser

The user who owns the playlist

Returns:

  • (User)

    the current value of owner



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def owner
  @owner
end

#publicBoolean

true if the playlist is not marked as secret

Returns:

  • (Boolean)

    the current value of public



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def public
  @public
end

#snapshot_idString

The version identifier for the current playlist. Can be supplied in other requests to target a specific playlist version

Returns:

  • (String)

    the current value of snapshot_id



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def snapshot_id
  @snapshot_id
end

#totalInteger

The total number of tracks in the playlist

Returns:

  • (Integer)

    the current value of total



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def total
  @total
end

#tracks_added_atHash

A hash containing the date and time each track was added to the playlist. Note: the hash is updated only when #tracks is used.

Returns:

  • (Hash)

    the current value of tracks_added_at



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def tracks_added_at
  @tracks_added_at
end

#tracks_added_byHash

A hash containing the user that added each track to the playlist. Note: the hash is updated only when #tracks is used.

Returns:

  • (Hash)

    the current value of tracks_added_by



14
15
16
# File 'lib/rspotify/playlist.rb', line 14

def tracks_added_by
  @tracks_added_by
end

Class Method Details

Get a list of Spotify featured playlists (shown, for example, on a Spotify player’s “Browse” tab).

Examples:

playlists = RSpotify::Playlist.browse_featured
playlists = RSpotify::Playlist.browse_featured(locale: 'es_MX', limit: 10)
playlists = RSpotify::Playlist.browse_featured(country: 'US', timestamp: '2014-10-23T09:00:00')

Parameters:

  • limit (Integer) (defaults to: 20)

    Maximum number of playlists to return. Maximum: 50. Default: 20.

  • offset (Integer) (defaults to: 0)

    The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0.

  • locale (String)

    Optional. The desired language, consisting of a lowercase ISO 639 language code and an uppercase ISO 3166-1 alpha-2 country code, joined by an underscore. For details access / here and look for the locale parameter description.

  • country (String)

    Optional. A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want the list of returned playlists to be relevant to a particular country. If omitted, the returned playlists will be relevant to all countries.

  • timestamp (String)

    Optional. A timestamp in ISO 8601 format: yyyy-MM-ddTHH:mm:ss. Use this parameter to specify the user’s local time to get results tailored for that specific date and time in the day. If not provided, the response defaults to the current UTC time. Example: “2014-10-23T09:00:00” for a user whose local time is 9AM.

Returns:



29
30
31
32
33
34
35
36
# File 'lib/rspotify/playlist.rb', line 29

def self.browse_featured(limit: 20, offset: 0, **options)
  url = "browse/featured-playlists?limit=#{limit}&offset=#{offset}"
  options.each do |option, value|
    url << "&#{option}=#{value}"
  end
  json = RSpotify.auth_get(url)
  json['playlists']['items'].map { |i| Playlist.new i }
end

.find(user_id, id) ⇒ Playlist

Returns Playlist object with user_id and id provided. If id is “starred”, returns starred playlist from user.

Examples:

playlist = RSpotify::Playlist.find('wizzler', '00wHcTN0zQiun4xri9pmvX')
playlist.class #=> RSpotify::Playlist
playlist.name  #=> "Movie Soundtrack Masterpieces"

Parameters:

  • user_id (String)
  • id (String)

Returns:



48
49
50
51
52
53
54
55
56
# File 'lib/rspotify/playlist.rb', line 48

def self.find(user_id, id)
  url = if id == "starred"
    "users/#{user_id}/starred"
  else
    "users/#{user_id}/playlists/#{id}"
  end
  json = RSpotify.resolve_auth_request(user_id, url)
  Playlist.new json
end

.search(query, limit: 20, offset: 0) ⇒ Array<Playlist>

Returns array of Playlist objects matching the query. It’s also possible to find the total number of search results for the query

Examples:

playlists = RSpotify::Playlist.search('Indie')
playlists = RSpotify::Playlist.search('Indie', limit: 10)

RSpotify::Playlist.search('Indie').total #=> 14653

Parameters:

  • query (String)

    The search query’s keywords. See the q description in here for details.

  • limit (Integer) (defaults to: 20)

    Maximum number of playlists to return. Maximum: 50. Default: 20.

  • offset (Integer) (defaults to: 0)

    The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0.

Returns:



70
71
72
# File 'lib/rspotify/playlist.rb', line 70

def self.search(query, limit: 20, offset: 0)
  super(query, 'playlist', limit: limit, offset: offset)
end

Instance Method Details

#add_tracks!(tracks, position: nil) ⇒ Array<Track>

Adds one or more tracks to a playlist in user’s Spotify account. This method is only available when the current user has granted access to the playlist-modify and playlist-modify-private scopes.

Examples:

tracks = RSpotify::Track.search('Know', 30)
playlist = user.create_playlist!('my-awesome-playlist')

playlist.add_tracks!(tracks)
playlist.tracks.size       #=> 30
playlist.tracks.first.name #=> "Somebody That I Used To Know"

playlist.add_tracks!(tracks, position: 20)
playlist.tracks[20].name #=> "Somebody That I Used To Know"

Parameters:

  • tracks (Array<Track>)

    Tracks to be added. Maximum: 100 per request

  • position (Integer, NilClass) (defaults to: nil)

    The position to insert the tracks, a zero-based index. Default: tracks are appended to the playlist

Returns:

  • (Array<Track>)

    The tracks added



123
124
125
126
127
128
129
130
131
132
133
# File 'lib/rspotify/playlist.rb', line 123

def add_tracks!(tracks, position: nil)
  track_uris = tracks.map(&:uri).join(',')
  url = @href + "/tracks?uris=#{track_uris}"
  url << "&position=#{position}" if position

  User.oauth_post(@owner.id, url, {})
  @total += tracks.size
  @tracks_cache = nil

  tracks
end

#change_details!(**data) ⇒ Playlist

Change name and public/private state of playlist in user’s Spotify account. Changing a public playlist requires the playlist-modify scope; changing a private playlist requires the playlist-modify-private scope.

Examples:

playlist.name   #=> "Movie Soundtrack Masterpieces"
playlist.public #=> true

playlist.change_details!(name: 'Movie Tracks', public: false)

playlist.name   #=> "Movie Tracks"
playlist.public #=> false

Parameters:

  • name (String)

    Optional. The new name for the playlist.

  • public (Boolean)

    Optional. If true the playlist will be public, if false it will be private.

Returns:



150
151
152
153
154
155
156
# File 'lib/rspotify/playlist.rb', line 150

def change_details!(**data)
  User.oauth_put(@owner.id, @href, data.to_json)
  data.each do |field, value|
    instance_variable_set("@#{field}", value)
  end
  self
end

#complete!Object

Note:

It is seldom necessary to use this method explicitly, since RSpotify takes care of it automatically when needed (see Base#method_missing)

When an object is obtained undirectly, Spotify usually returns a simplified version of it. This method updates it into a full object, with all attributes filled.

Examples:

playlist = user.playlists.first
playlist.instance_variable_get("@description") #=> nil
playlist.complete!
playlist.instance_variable_get("@description") #=> "Iconic soundtracks..."


168
169
170
# File 'lib/rspotify/playlist.rb', line 168

def complete!
  initialize RSpotify.resolve_auth_request(@owner.id, @href)
end

#replace_tracks!(tracks) ⇒ Array<Track>

Replace all the tracks in a playlist, overwriting its existing tracks. Changing a public playlist requires the playlist-modify scope; changing a private playlist requires the playlist-modify-private scope.

Examples:

playlist.tracks.map(&:name) #=> ["All of Me", "Wasted Love", "Love Runs Out"]
tracks = RSpotify::Track.search('Know', limit: 2)
playlist.replace_tracks!(tracks)
playlist.tracks.map(&:name) #=> ["Somebody That I Used To Know", "Do I Wanna Know?"]

Parameters:

  • tracks (Array<Track>)

    The tracks that will replace the existing ones. Maximum: 100 per request

Returns:

  • (Array<Track>)

    The tracks that were added.



215
216
217
218
219
220
221
222
223
224
# File 'lib/rspotify/playlist.rb', line 215

def replace_tracks!(tracks)
  track_uris = tracks.map(&:uri).join(',')
  url = @href + "/tracks?uris=#{track_uris}"

  User.oauth_put(@owner.id, url, {})
  @total = tracks.size
  @tracks_cache = nil

  tracks
end

#tracks(limit: 100, offset: 0) ⇒ Array<Track>

Returns array of tracks from the playlist

Examples:

playlist = RSpotify::Playlist.find('wizzler', '00wHcTN0zQiun4xri9pmvX')
playlist.tracks.first.name #=> "Main Theme from Star Wars - Instrumental"

Parameters:

  • limit (Integer) (defaults to: 100)

    Maximum number of tracks to return. Maximum: 100. Default: 100.

  • offset (Integer) (defaults to: 0)

    The index of the first track to return. Use with limit to get the next set of objects. Default: 0.

Returns:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/rspotify/playlist.rb', line 181

def tracks(limit: 100, offset: 0)
  last_track = offset + limit - 1
  if @tracks_cache && last_track < 100
    return @tracks_cache[offset..last_track]
  end

  url = @href + "/tracks?limit=#{limit}&offset=#{offset}"
  json = RSpotify.resolve_auth_request(@owner.id, url)
  tracks = json['items'].select { |i| i['track'] }

  @tracks_added_at = hash_for(tracks, 'added_at') do |added_at|
    Time.parse added_at
  end

  @tracks_added_by = hash_for(tracks, 'added_by') do |added_by|
    User.new added_by
  end

  tracks.map! { |t| Track.new t['track'] }
  @tracks_cache = tracks if limit == 100 && offset == 0
  tracks
end