Skip to content

Instantly share code, notes, and snippets.

@pjaspers
Created November 26, 2013 12:34
Show Gist options
  • Save pjaspers/7657620 to your computer and use it in GitHub Desktop.
Save pjaspers/7657620 to your computer and use it in GitHub Desktop.
class Song
# Create a new Song.
#
# path - The spotify path
#
# Returns nothing.
def initialize(options={})
self.path = options[:path] if options[:path]
cache_album_art
end
# Sets the path for this Song. Once the path is set, go in and read the file
# from disk and intialize those values in-memory.
#
# path - The String path on disk of the music file.
#
# Returns the path.
def path=(path)
@path = path.chomp
spotify_id = path
track = MetaSpotify::Track.lookup(spotify_id) rescue nil
return unless track
@artist = Artist.new(:name => track.artists.first.try(:name))
@album = Album.new(:artist => @artist, :name => track.album.name)
@title = track.name
@seconds = track.length.to_i
@path
end
# Cache a songs album art.
#
# Stores a cache of the album art data to Play.album_art_cache_path
# so we don't have to shell out for every song to get the album art.
#
# Returns the String path if we've written new art.
def cache_album_art
FileUtils.mkdir_p(Play.album_art_cache_path)
art_cache_path = "#{Play.album_art_cache_path}/#{art_file}"
if !File.exists?(art_cache_path)
json = JSON.parse(open("https://embed.spotify.com/oembed/?url=#{@path}").read) rescue {}
puts "Fetched #{json.inspect}"
if url = json.fetch("thumbnail_url", nil)
data = open(url).read
puts "Writing to #{art_cache_path}"
File.open(art_cache_path, 'wb') do |file|
file.write(data)
end
art_cache_path
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment