Class: RSpotify::User

Inherits:
Base
  • Object
show all
Defined in:
lib/rspotify/user.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

#complete!, #embed, #method_missing, #respond_to?

Constructor Details

#initialize(options = {}) ⇒ User

Returns a new instance of User.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/rspotify/user.rb', line 71

def initialize(options = {})
  credentials = options['credentials']
  extra       = options['extra'].to_h
  options     = options['info'] if options['info']
  options.merge!(extra['raw_info'].to_h)

  @birthdate    ||= options['birthdate']
  @country      ||= options['country']
  @display_name ||= options['display_name']
  @email        ||= options['email']
  @followers    ||= options['followers']
  @images       ||= options['images']
  @product      ||= options['product']

  super(options)

  if credentials
    @@users_credentials ||= {}
    @@users_credentials[@id] = credentials
    @credentials = @@users_credentials[@id]
  end
end

Dynamic Method Handling

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

Instance Attribute Details

#birthdateString

The user’s date-of-birth. This field is only available when the current user has granted access to the user-read-birthdate scope.

Returns:

  • (String)

    the current value of birthdate



12
13
14
# File 'lib/rspotify/user.rb', line 12

def birthdate
  @birthdate
end

#countryString

The country of the user, as set in the user’s account profile. An ISO 3166-1 alpha-2 country code. This field is only available when the current user has granted access to the user-read-private scope.

Returns:

  • (String)

    the current value of country



12
13
14
# File 'lib/rspotify/user.rb', line 12

def country
  @country
end

#credentialsHash

The credentials generated for the user with OAuth. Includes access token, token type, token expiration time and refresh token. This field is only available when the current user has granted access to any scope.

Returns:

  • (Hash)

    the current value of credentials



12
13
14
# File 'lib/rspotify/user.rb', line 12

def credentials
  @credentials
end

#display_nameString

The name displayed on the user’s profile. This field is only available when the current user has granted access to the user-read-private scope.

Returns:

  • (String)

    the current value of display_name



12
13
14
# File 'lib/rspotify/user.rb', line 12

def display_name
  @display_name
end

#emailString

The user’s email address. This field is only available when the current user has granted access to the user-read-email scope.

Returns:

  • (String)

    the current value of email



12
13
14
# File 'lib/rspotify/user.rb', line 12

def email
  @email
end

#followersHash

Information about the followers of the user

Returns:

  • (Hash)

    the current value of followers



12
13
14
# File 'lib/rspotify/user.rb', line 12

def followers
  @followers
end

#imagesArray

The user’s profile image. This field is only available when the current user has granted access to the user-read-private scope.

Returns:

  • (Array)

    the current value of images



12
13
14
# File 'lib/rspotify/user.rb', line 12

def images
  @images
end

#productString

The user’s Spotify subscription level: “premium”, “free”, etc. This field is only available when the current user has granted access to the user-read-private scope.

Returns:

  • (String)

    the current value of product



12
13
14
# File 'lib/rspotify/user.rb', line 12

def product
  @product
end

#tracks_added_atHash

A hash containing the date and time each track was saved by the user. Note: the hash is filled and updated only when #saved_tracks is used.

Returns:

  • (Hash)

    the current value of tracks_added_at



12
13
14
# File 'lib/rspotify/user.rb', line 12

def tracks_added_at
  @tracks_added_at
end

Class Method Details

.find(id) ⇒ User

Returns User object with id provided

Examples:

user = RSpotify::User.find('wizzler')
user.class #=> RSpotify::User
user.id    #=> "wizzler"

Parameters:

  • id (String)

Returns:



23
24
25
# File 'lib/rspotify/user.rb', line 23

def self.find(id)
  super(id, 'user')
end

.oauth_send(user_id, verb, path, *params) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/rspotify/user.rb', line 54

def self.oauth_send(user_id, verb, path, *params)
  RSpotify.send(:send_request, verb, path, *params)
rescue RestClient::Unauthorized => e
  raise e if e.response !~ /access token expired/
  refresh_token(user_id)
  params[-1] = oauth_header(user_id)
  RSpotify.send(:send_request, verb, path, *params)
end

.searchObject

Spotify does not support search for users.



28
29
30
31
# File 'lib/rspotify/user.rb', line 28

def self.search(*)
  warn 'Spotify API does not support search for users'
  false
end

Instance Method Details

#create_playlist!(name, public: true) ⇒ Playlist

Creates a playlist in user’s Spotify account. This method is only available when the current user has granted access to the playlist-modify-public and playlist-modify-private scopes.

Examples:

user.create_playlist!('my-first-playlist')
user.playlists.last.name   #=> "my-first-playlist"
user.playlists.last.public #=> true

playlist = user.create_playlist!('my-second-playlist', public: false)
playlist.name   #=> "my-second-playlist"
playlist.public #=> false

Parameters:

  • name (String)

    The name for the new playlist

  • public (Boolean) (defaults to: true)

    Whether the playlist is public or private. Default: true

Returns:



109
110
111
112
113
114
115
116
# File 'lib/rspotify/user.rb', line 109

def create_playlist!(name, public: true)
  url = "users/#{@id}/playlists"
  request_data = { name: name, public: public }.to_json

  response = User.oauth_post(@id, url, request_data)
  return response if RSpotify.raw_response
  Playlist.new response
end

#currently_playingObject



118
119
120
121
122
123
# File 'lib/rspotify/user.rb', line 118

def currently_playing
  url = "me/player/currently-playing"
  response = RSpotify.resolve_auth_request(@id, url)
  return response if RSpotify.raw_response
  Track.new response["item"]
end

#follow(followed, public: true) ⇒ Artist, ...

Note:

Scopes you provide for playlists determine only whether the current user can themselves follow the playlist publicly or privately (i.e. show others what they are following), not whether the playlist itself is public or private.

Add the current user as a follower of one or more artists, other Spotify users or a playlist. Following artists or users require the user-follow-modify scope. Following a playlist publicly requires the playlist-modify-public scope; following it privately requires the playlist-modify-private scope.

Examples:

artists = RSpotify::Artist.search('John')
user.follow(artists)

playlist = RSpotify::Playlist.search('Movie').first
user.follow(playlist, public: false)

Parameters:

  • followed (Artist, Array<Artist>, User, Array<User>, Playlist)

    The artists, users or playlist to follow

  • public (Boolean) (defaults to: true)

    If true the playlist will be included in user’s public playlists, if false it will remain private.

Returns:



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/rspotify/user.rb', line 172

def follow(followed, public: true)
  if followed.is_a? Array
    ids = followed.map(&:id).join(',')
    type = followed.first.type
  else
    ids = followed.id
    type = followed.type
  end

  if type == 'playlist'
    request_body = { public: public }
    url = "users/#{followed.owner.id}/playlists/#{followed.id}/followers"
  else
    request_body = {}
    url = "me/following?type=#{type}&ids=#{ids}"
  end

  User.oauth_put(@id, url, request_body.to_json)
  followed
end

#following(type: nil, limit: 20, after: nil) ⇒ Array<Artist>

Note:

The current Spotify API implementation only supports getting followed artists

Get the current user’s followed artists or users. Requires the user-follow-read scope.

Examples:

followed_artists = user.following(type: 'artist')
followed_artists.first.class #=> RSpotify::Artist

followed_artists = user.following(type: 'artist', limit: 50)

Parameters:

  • type (String) (defaults to: nil)

    The ID type: currently only “artist” is supported

  • limit (Integer) (defaults to: 20)

    Maximum number of items to return. Maximum: 50. Minimum: 1. Default: 20.

  • after (String) (defaults to: nil)

    Optional. The last artist ID retrieved from the previous request.

Returns:



207
208
209
210
211
212
213
214
215
# File 'lib/rspotify/user.rb', line 207

def following(type: nil, limit: 20, after: nil)
  type_class = RSpotify.const_get(type.capitalize)
  url = "me/following?type=#{type}&limit=#{limit}"
  url << "&after=#{after}" if after

  response = User.oauth_get(@id, url)
  return response if RSpotify.raw_response
  response["#{type}s"]['items'].compact.map { |i| type_class.new i }
end

#follows?(followed) ⇒ Array<Boolean>

Check if the current user is following one or more artists or other Spotify users. This method is only available when the current user has granted access to the user-follow-read scope.

Examples:

artists = RSpotify::Artist.search('John')
user.follows?(artists) #=> [true, false, true...]

Parameters:

Returns:

  • (Array<Boolean>)


226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/rspotify/user.rb', line 226

def follows?(followed)
  if followed.is_a? Array
    ids = followed.map(&:id).join(',')
    type = followed.first.type
  else
    ids = followed.id
    type = followed.type
  end

  url = "me/following/contains?type=#{type}&ids=#{ids}"
  User.oauth_get(@id, url)
end

#play_track(song_uri) ⇒ Object

Allow browser to trigger playback in the user’s currently active spotify app. User must be a premium subscriber for this feature to work.



127
128
129
130
131
132
# File 'lib/rspotify/user.rb', line 127

def play_track(song_uri)
  url = "me/player/play"
  verb = 'put'
  params = {"uris": [song_uri]}
  response = User.oauth_put(@id, url, params.to_json)
end

#playlists(limit: 20, offset: 0) ⇒ Array<Playlist>

Returns all playlists from user

Examples:

playlists = user.playlists
playlists.class       #=> Array
playlists.first.class #=> RSpotify::Playlist
playlists.first.name  #=> "Movie Soundtrack Masterpieces"

Parameters:

  • limit (Integer) (defaults to: 20)

    Maximum number of playlists to return. Maximum: 50. Minimum: 1. 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:



250
251
252
253
254
255
# File 'lib/rspotify/user.rb', line 250

def playlists(limit: 20, offset: 0)
  url = "users/#{@id}/playlists?limit=#{limit}&offset=#{offset}"
  response = RSpotify.resolve_auth_request(@id, url)
  return response if RSpotify.raw_response
  response['items'].map { |i| Playlist.new i }
end

#recently_played(limit: 20) ⇒ Array<Track>

Get the current user’s recently played tracks. Requires the user-read-recently-played scope.

Examples:

recently_played = user.recently_played
recently_played.size       #=> 20
recently_played.first.name #=> "Ice to Never"

Parameters:

  • limit (Integer) (defaults to: 20)

    Optional. The number of entities to return. Default: 20. Minimum: 1. Maximum: 50.

Returns:



143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/rspotify/user.rb', line 143

def recently_played(limit: 20)
  url = "me/player/recently-played?limit=#{limit}"
  response = RSpotify.resolve_auth_request(@id, url)
  return response if RSpotify.raw_response

  json = RSpotify.raw_response ? JSON.parse(response) : response
  json['items'].map do |t|
    data = t['track']
    data['played_at'] = t['played_at']
    data['context_type'] = t['context']['type'] if t['context']
    Track.new data
  end
end

#remove_albums!(albums) ⇒ Array<Album>

Remove albums from the user’s “Your Music” library.

Examples:

albums = user.saved_albums

user.saved_albums.size #=> 20
user.remove_albums!(albums)
user.saved_albums.size #=> 0

Parameters:

  • albums (Array<Album>)

    The albums to remove. Maximum: 50.

Returns:

  • (Array<Album>)

    The albums removed.



343
344
345
346
347
348
# File 'lib/rspotify/user.rb', line 343

def remove_albums!(albums)
  albums_ids = albums.map(&:id)
  url = "me/albums?ids=#{albums_ids.join ','}"
  User.oauth_delete(@id, url)
  albums
end

#remove_tracks!(tracks) ⇒ Array<Track>

Remove tracks from the user’s “Your Music” library.

Examples:

tracks = user.saved_tracks

user.saved_tracks.size #=> 20
user.remove_tracks!(tracks)
user.saved_tracks.size #=> 0

Parameters:

  • tracks (Array<Track>)

    The tracks to remove. Maximum: 50.

Returns:

  • (Array<Track>)

    The tracks removed.



268
269
270
271
272
273
# File 'lib/rspotify/user.rb', line 268

def remove_tracks!(tracks)
  tracks_ids = tracks.map(&:id)
  url = "me/tracks?ids=#{tracks_ids.join ','}"
  User.oauth_delete(@id, url)
  tracks
end

#save_albums!(albums) ⇒ Array<Album>

Save albums to the user’s “Your Music” library.

Examples:

albums = RSpotify::Album.search('launeddas')

user.saved_albums.size #=> 0
user.save_albums!(albums)
user.saved_albums.size #=> 10

Parameters:

  • albums (Array<Album>)

    The albums to save. Maximum: 50.

Returns:

  • (Array<Album>)

    The albums saved.



361
362
363
364
365
366
367
# File 'lib/rspotify/user.rb', line 361

def save_albums!(albums)
  albums_ids = albums.map(&:id)
  url = "me/albums"
  request_body = albums_ids.inspect
  User.oauth_put(@id, url, request_body)
  albums
end

#save_tracks!(tracks) ⇒ Array<Track>

Save tracks to the user’s “Your Music” library.

Examples:

tracks = RSpotify::Track.search('Know')

user.saved_tracks.size #=> 0
user.save_tracks!(tracks)
user.saved_tracks.size #=> 20

Parameters:

  • tracks (Array<Track>)

    The tracks to save. Maximum: 100.

Returns:

  • (Array<Track>)

    The tracks saved.



286
287
288
289
290
291
292
# File 'lib/rspotify/user.rb', line 286

def save_tracks!(tracks)
  tracks_ids = tracks.map(&:id)
  url = "me/tracks"
  request_body = tracks_ids.inspect
  User.oauth_put(@id, url, request_body)
  tracks
end

#saved_albums(limit: 20, offset: 0) ⇒ Array<Album>

Returns the albums saved in the Spotify user’s “Your Music” library. ** Includes albums whose tracks you saved

Examples:

albums = user.saved_albums
albums.size       #=> 20
albums.first.name #=> "Launeddas"

Parameters:

  • limit (Integer) (defaults to: 20)

    Maximum number of albums to return. Maximum: 50. Minimum: 1. Default: 20.

  • offset (Integer) (defaults to: 0)

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

Returns:



379
380
381
382
383
384
385
386
387
388
# File 'lib/rspotify/user.rb', line 379

def saved_albums(limit: 20, offset: 0)
  url = "me/albums?limit=#{limit}&offset=#{offset}"
  response = User.oauth_get(@id, url)
  json = RSpotify.raw_response ? JSON.parse(response) : response

  albums = json['items'].select { |i| i['album'] }

  return response if RSpotify.raw_response
  albums.map { |a| Album.new a['album'] }
end

#saved_albums?(albums) ⇒ Array<Boolean>

Check if albums are already saved in the Spotify user’s “Your Music” library. ** Only returns true if the album was saved via me/albums, not if you saved each track individually.

Examples:

albums = RSpotify::Album.search('launeddas')
user.saved_albums?(albums) #=> [true, false, true...]

Parameters:

  • albums (Array<Album>)

    The albums to check. Maximum: 50.

Returns:

  • (Array<Boolean>)

    Array of booleans, in the same order in which the albums were specified.



398
399
400
401
402
# File 'lib/rspotify/user.rb', line 398

def saved_albums?(albums)
  albums_ids = albums.map(&:id)
  url = "me/albums/contains?ids=#{albums_ids.join ','}"
  User.oauth_get(@id, url)
end

#saved_tracks(limit: 20, offset: 0) ⇒ Array<Track>

Returns the tracks saved in the Spotify user’s “Your Music” library

Examples:

tracks = user.saved_tracks
tracks.size       #=> 20
tracks.first.name #=> "Do I Wanna Know?"

Parameters:

  • limit (Integer) (defaults to: 20)

    Maximum number of tracks to return. Maximum: 50. Minimum: 1. Default: 20.

  • offset (Integer) (defaults to: 0)

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

Returns:



304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/rspotify/user.rb', line 304

def saved_tracks(limit: 20, offset: 0)
  url = "me/tracks?limit=#{limit}&offset=#{offset}"
  response = User.oauth_get(@id, url)
  json = RSpotify.raw_response ? JSON.parse(response) : response

  tracks = json['items'].select { |i| i['track'] }
  @tracks_added_at = hash_for(tracks, 'added_at') do |added_at|
    Time.parse added_at
  end

  return response if RSpotify.raw_response
  tracks.map { |t| Track.new t['track'] }
end

#saved_tracks?(tracks) ⇒ Array<Boolean>

Check if tracks are already saved in the Spotify user’s “Your Music” library

Examples:

tracks = RSpotify::Track.search('Know')
user.saved_tracks?(tracks) #=> [true, false, true...]

Parameters:

  • tracks (Array<Track>)

    The tracks to check. Maximum: 50.

Returns:

  • (Array<Boolean>)

    Array of booleans, in the same order in which the tracks were specified.



326
327
328
329
330
# File 'lib/rspotify/user.rb', line 326

def saved_tracks?(tracks)
  tracks_ids = tracks.map(&:id)
  url = "me/tracks/contains?ids=#{tracks_ids.join ','}"
  User.oauth_get(@id, url)
end

#to_hashObject

Returns a hash containing all user attributes



405
406
407
408
409
410
# File 'lib/rspotify/user.rb', line 405

def to_hash
  pairs = instance_variables.map do |var|
    [var.to_s.delete('@'), instance_variable_get(var)]
  end
  Hash[pairs]
end

#top_artists(limit: 20, offset: 0, time_range: 'medium_term') ⇒ Array<Artist>

Get the current user’s top artists based on calculated affinity. Requires the user-top-read scope.

Examples:

top_artists = user.top_artists
top_artists.size       #=> 20
top_artists.first.name #=> "Nine Inch Nails"

Parameters:

  • limit (Integer) (defaults to: 20)

    Optional. The number of entities to return. Default: 20. Minimum: 1. Maximum: 50.

  • offset (Integer) (defaults to: 0)

    Optional. The index of the first entity to return. Default: 0 (i.e., the first track). Use with limit to get the next set of entities.

  • time_range (String) (defaults to: 'medium_term')

    Optional. Over what time frame the affinities are computed. Valid values: long_term (calculated from several years of data and including all new data as it becomes available), medium_term (approximately last 6 months), short_term (approximately last 4 weeks). Default: medium_term.

Returns:



423
424
425
426
427
428
# File 'lib/rspotify/user.rb', line 423

def top_artists(limit: 20, offset: 0, time_range: 'medium_term')
  url = "me/top/artists?limit=#{limit}&offset=#{offset}&time_range=#{time_range}"
  response = User.oauth_get(@id, url)
  return response if RSpotify.raw_response
  response['items'].map { |i| Artist.new i }
end

#top_tracks(limit: 20, offset: 0, time_range: 'medium_term') ⇒ Array<Track>

Get the current user’s top tracks based on calculated affinity. Requires the user-top-read scope.

Examples:

top_tracks = user.top_tracks
top_tracks.size       #=> 20
top_tracks.first.name #=> "Ice to Never"

Parameters:

  • limit (Integer) (defaults to: 20)

    Optional. The number of entities to return. Default: 20. Minimum: 1. Maximum: 50.

  • offset (Integer) (defaults to: 0)

    Optional. The index of the first entity to return. Default: 0 (i.e., the first track). Use with limit to get the next set of entities.

  • time_range (String) (defaults to: 'medium_term')

    Optional. Over what time frame the affinities are computed. Valid values: long_term (calculated from several years of data and including all new data as it becomes available), medium_term (approximately last 6 months), short_term (approximately last 4 weeks). Default: medium_term.

Returns:



441
442
443
444
445
446
# File 'lib/rspotify/user.rb', line 441

def top_tracks(limit: 20, offset: 0, time_range: 'medium_term')
  url = "me/top/tracks?limit=#{limit}&offset=#{offset}&time_range=#{time_range}"
  response = User.oauth_get(@id, url)
  return response if RSpotify.raw_response
  response['items'].map { |i| Track.new i }
end

#unfollow(unfollowed) ⇒ Artist, ...

Note:

Note that the scopes you provide for playlists relate only to whether the current user is following the playlist publicly or privately (i.e. showing others what they are following), not whether the playlist itself is public or private.

Remove the current user as a follower of one or more artists, other Spotify users or a playlist. Unfollowing artists or users require the user-follow-modify scope. Unfollowing a publicly followed playlist requires the playlist-modify-public scope; unfollowing a privately followed playlist requires the playlist-modify-private scope.

Examples:

artists = RSpotify::Artist.search('John')
user.unfollow(artists)

playlist = RSpotify::Playlist.search('Movie').first
user.unfollow(playlist)

Parameters:

Returns:



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/rspotify/user.rb', line 462

def unfollow(unfollowed)
  if unfollowed.is_a? Array
    ids = unfollowed.map(&:id).join(',')
    type = unfollowed.first.type
  else
    ids = unfollowed.id
    type = unfollowed.type
  end

  url = if type == 'playlist'
    "users/#{unfollowed.owner.id}/playlists/#{unfollowed.id}/followers"
  else
    "me/following?type=#{type}&ids=#{ids}"
  end

  User.oauth_delete(@id, url)
  unfollowed
end