1
0
Fork 0

Search and suggestions backend

This commit is contained in:
magnolia-fan 2011-06-18 03:37:49 +04:00
parent 17f5edf841
commit 24ca64a945
3 changed files with 25 additions and 8 deletions

View File

@ -7,13 +7,16 @@ class ArtistController < ApplicationController
name = params[:name].gsub('%20', ' ').gsub('+', ' ')
artist = Artist.find_by_name(name)
unless artist
mb_artist = MusicBrainzArtist.getByName(name)
if mb_artist
results = ArtistController.musicBrainzSearch(name)
if results[0].downcase == name.downcase and results[0] != name
render :json => {correct: results[0]}
return
elsif results[0] == name
ImportController.importArtist(name)
render :json => {error:'loading'}
render :json => {status: 'loading'}
return
else
render :json => {error:404}
render :json => {suggestions: results}
return
end
end
@ -49,7 +52,7 @@ class ArtistController < ApplicationController
return render :nothing => true if autocomplete.nil?
suggestions = []
autocomplete["response"]["docs"].each do |doc|
suggestions << doc["artist"] unless suggestions.include?(doc["artist"]) or doc["artist"].nil?
suggestions << doc["artist"] unless suggestions.include?(doc["artist"]) or doc["artist"].nil? or doc['restype'] != 6
end
render :json => {
:query => params[:query],
@ -57,7 +60,7 @@ class ArtistController < ApplicationController
}
end
def self.getLastFmAutocomplete(query)
def self.getLastFmAutocomplete query
return nil if query.nil? or query.strip.empty?
json = ActiveSupport::JSON.decode(open(
'http://www.last.fm/search/autocomplete' <<
@ -65,4 +68,17 @@ class ArtistController < ApplicationController
).read)
return json.empty? ? nil : json
end
def self.musicBrainzSearch(query)
begin
response = ActiveSupport::JSON.decode(open('http://search.test.musicbrainz.org/ws/2/artist/?fmt=json&query='+ URI.escape(query).gsub(/\&/, '%26').gsub(/\?/, '%3F') +'~').read)
artists = []
response['artist-list']['artist'].each do |artist|
artists << artist['name']
end
return artists
rescue
return {}
end
end
end

View File

@ -5,14 +5,14 @@ class ImportController < ApplicationController
# Get artist info
artist_mb_xml = open(
'http://musicbrainz.org/ws/2/artist/?query='+ URI.escape(name) +'&limit=1',
'http://musicbrainz.org/ws/2/artist/?query='+ URI.escape(name).gsub(/\&/, '%26').gsub(/\?/, '%3F') +'&limit=1',
'User-Agent' => @@user_agent
).read
artist_mb_data = artist_mb_xml.scan(/<artist.*?type=\"(.+?)\"\sid=\"([a-f0-9-]+?)\">.*?<name>(.+?)<\/name>/m)
artist_lastfm_xml = open(
'http://ws.audioscrobbler.com/2.0/'+
'?method=artist.getinfo&api_key='+ @@lastfm_api_key +
'&artist='+ URI.escape(name)
'&artist='+ URI.escape(name).gsub(/\&/, '%26').gsub(/\?/, '%3F')
).read
# Save artist

View File

@ -57,5 +57,6 @@ Beathaven::Application.routes.draw do
# match ':controller(/:action(/:id(.:format)))'
match 'artist/autocomplete' => 'artist#autocomplete'
match 'artist/search' => 'artist#search'
match 'artist/(:name)/' => 'artist#data', :constraints => { :name => /[^\/]*/ }
end