Lastfm scrobbling backend ready

This commit is contained in:
magnolia-fan
2011-06-23 02:56:32 +04:00
parent 4326a4960b
commit 8c33730252
9 changed files with 78 additions and 49 deletions
+39 -42
View File
@@ -1,4 +1,5 @@
require 'open-uri'
require 'lastfm'
class LastFmController < ApplicationController
@@ -9,7 +10,10 @@ class LastFmController < ApplicationController
unless params[:sid].nil? or params[:token].nil?
session = Session.find_by_key(params[:sid])
unless session.nil?
session.user.lastfm_token = params[:token]
lastfm = Lastfm.new(@@api_key, @@secret)
lastfm.session = lastfm.auth.get_session(params[:token])
session.user.lastfm_key = lastfm.session['key']
session.user.lastfm_username = lastfm.session['name']
session.user.save
render :text => '<script>window.close();</script>'
else
@@ -21,52 +25,45 @@ class LastFmController < ApplicationController
end
def getinfo
#return unless authorized?
return unless authorized?
@res = {}
user = User.find_by_vkid(1217744)#params[:mid])
@res[:connected] = false
@res[:lastfm_login_url] = 'http://www.last.fm/api/auth?api_key='+ @@api_key +'&cb=http://localhost/lastfm/connect/?sid='+ user.session.key
unless user.lastfm_token.nil?
lastfm_response = auth_query({:method => 'auth.getSession', :token => user.lastfm_token})
render :json => lastfm_response
return
if lastfm_response
user.lastfm_token = lastfm_response[1]
user.save
@res[:connected] = true
@res[:username] = lastfm_response[0];
end
end
render :json => @res
end
private
def auth_query params
url = 'http://ws.audioscrobbler.com/2.0/?'
params[:api_key] = @@api_key
params.each do |k, v|
url << k.to_s << '=' << v << '&'
end
url << 'api_sig=' << get_signature(params)
begin
open(url).read.match(/<name>(.*?)<\/name>.*?<key>(.*?)<\/key>/m)
rescue
false
user = User.find_by_vkid(params[:mid])
unless user.lastfm_key.nil?
render :json => {
:connected => true,
:username => user.lastfm_username
}
else
render :json => {
:connected => false,
:lastfm_login_url => 'http://www.last.fm/api/auth?api_key='+ @@api_key +'&cb=http://localhost/lastfm/connect/?sid='+ user.session.key
}
end
end
def get_signature params
params = params.to_a.sort! { |a, b| a[0] <=> b[0] }
params = Hash[params]
str = '';
params.each do |k, v|
str << k.to_s << v
end
Digest::MD5.hexdigest(str + @@secret)
def listening
return unless authorized?
return if params[:artist].nil? or params[:track].nil?
user = User.find_by_vkid(params[:mid])
return unless user.lastfm_key.nil?
lastfm = Lastfm.new(@@api_key, @@secret)
lastfm.session = user.lastfm_key
lastfm.update_now_playing(params[:artist], params[:track])
end
def scrobble
return unless authorized?
return if params[:artist].nil? or params[:track].nil?
user = User.find_by_vkid(params[:mid])
return unless user.lastfm_key.nil?
lastfm = Lastfm.new(@@api_key, @@secret)
lastfm.session = user.lastfm_key
lastfm.scrobble(params[:artist], params[:track])
end
end