Skip to content

Commit

Permalink
Get artist images on the client side
Browse files Browse the repository at this point in the history
  • Loading branch information
timjb authored and sunny committed Feb 10, 2011
1 parent c019407 commit f3f6d95
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
30 changes: 28 additions & 2 deletions public/script.js
Expand Up @@ -2,7 +2,31 @@ $.fn.background = function(bg) {
return $(this).css('backgroundImage', bg ? 'url('+bg+')' : 'none')
}

Array.prototype.random = function() {
return this[Math.floor(Math.random() * this.length)]
}

// call a function asynchronously to minimize codepaths
function async(fn) {
setTimeout(fn, 10)
}

$(function() {
function artistImage(artist, callback) {
if (!artist) { async(callback); return }
artist = encodeURI(artist)
var last_fm_uri = "http://ws.audioscrobbler.com/2.0/?format=json&method=artist.getimages&artist=%s&api_key=b25b959554ed76058ac220b7b2e0a026"
$.ajax({
url: last_fm_uri.replace('%s', artist),
dataType: 'jsonp',
success: function(obj) {
var images = obj.images.image
callback(images.length ? images.random().sizes.size[0]['#text'] : null)
},
error: function() {}
})
}

function updateInformation(obj) {
obj = obj || {}
var artist = obj.artist || '',
Expand All @@ -16,10 +40,12 @@ $(function() {
if (!title && !title) {
$('title').html('So nice')
} else {
$('title').html(artist + (artist && title ? '–' : '') + title)
$('title').html(artist + (artist && title ? ' – ' : '') + title)
}

$('body').background(obj.image_uri)
artistImage(obj.artist, function(url) {
$('body').background(url)
})
}

// XHR updating the text regularly
Expand Down
4 changes: 2 additions & 2 deletions sonice.rb
Expand Up @@ -54,11 +54,11 @@ def artist_image(artist)
@title = $player.track
@artist = $player.artist
@album = $player.album
@image_uri = artist_image(@artist)
if request.xhr?
content_type :json
{ :title => h(@title), :artist => h(@artist), :album => h(@album), :image_uri => @image_uri }.to_json
{ :title => h(@title), :artist => h(@artist), :album => h(@album) }.to_json
else
@image_uri = artist_image(@artist)
haml :index
end
end
Expand Down

0 comments on commit f3f6d95

Please sign in to comment.