Skip to content

Instantly share code, notes, and snippets.

@alexanderadam
Created December 29, 2015 11:59
Show Gist options
  • Save alexanderadam/ac412b729f33e249368b to your computer and use it in GitHub Desktop.
Save alexanderadam/ac412b729f33e249368b to your computer and use it in GitHub Desktop.
require 'spotify'
track_link = 'https://play.spotify.com/track/7c0NJuLBfMRPpVuna4Offb'
album_link = 'https://play.spotify.com/album/7impFt5ybQPaautK43RyJa'
module SpotifyTest
module_function
def session
application_key = File.binread(File.join File.dirname(__FILE__), 'spotify_appkey.key')
error, session = Spotify.session_create(api_version: Spotify::API_VERSION.to_i,
application_key: application_key,
cache_location: '.spotify/',
settings_location: '.spotify/',
user_agent: 'hi mum!',
callbacks: Spotify::SessionCallbacks.new)
raise error if error.is_a? Spotify::APIError
username = Spotify.session_remembered_user session
if username
puts "Using username #{username.inspect}"
Spotify.try :session_relogin, session
else
username = prompt('Enter Spotify username or Facebook e-mail')
password = $stdin.noecho { prompt('Spotify password or Facebook password') }
Spotify.try(:session_login, session, username, password, true, nil)
end
poll(session, '?') { Spotify.session_connectionstate(session) == :logged_in }
session
end
def poll(session, tick_string = '.')
until yield
print tick_string
Spotify.session_process_events session
sleep 0.7
end
end
def string_to_link(string)
link = Spotify.link_create_from_string string
return link unless link.nil?
*_useless, type, id = string.to_s.split '/'
Spotify.link_create_from_string "spotify:#{type}:#{id}"
end
end
puts '[open session]'
session = SpotifyTest.session
# get track and read a property
track = Spotify.link_as_track(SpotifyTest.string_to_link track_link)
puts "[reading a track]"
SpotifyTest.poll(session, '+') { Spotify.track_is_loaded track }
track_name = Spotify.track_name track
puts "=> [finished reading #{track_name.inspect}]"
# get album and read a property
album = Spotify.link_as_album(SpotifyTest.string_to_link album_link)
puts "[reading an album]"
SpotifyTest.poll(session, '…') { Spotify.album_is_loaded album }
album_name = Spotify.album_name album
puts "=> [finished reading #{album_name.inspect}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment