1
0
Fork 0
oldhaven/app/controllers/artist_controller.rb

54 lines
1.9 KiB
Ruby

require 'open-uri'
require 'musicbrainz'
class ArtistController < ApplicationController
def data
# Bad params
if params[:name].nil? or params[:name].empty?
return render :json => { :status => 'loading_failed' }
end
# Searching for artist
artist_name = get_artist_name_from_query
@artist = Artist.find_by_name(artist_name, include: {artist_links: {}, albums: {tracks: {}}})
# Artist not found in DB
unless @artist
results = MusicBrainz::Artist.search(artist_name)
if results.empty?
return render :json => { :status => 'not_found' }
end
best_match = results[0][:name]
if best_match != artist_name and (best_match.downcase == artist_name.downcase or best_match.downcase == 'the '+ artist_name.downcase)
return render :json => { :status => 'corrected', :correct_name => best_match }
elsif results[0][:name] == artist_name
queue_loading(artist_name, results[0][:mbid])
@artist = { :artist => @artist, :albums => [] }
@loading = true
return render :json => { :status => 'loading', :html => render_compact_partial(:page) }
else
@suggestions = results.take(5)
return render :json => { :status => 'suggestions', :html => render_compact_partial(:suggestions) }
end
end
# Artist loading failed
if @artist.status == 2
return render :json => { :status => 'fail', :html => render_compact_partial(:fail) }
end
render json: { status: @artist.status_str, artist: @artist, html: render_compact_partial(:page) }, include: {albums: {include: {tracks: {}}}}
end
private
def get_artist_name_from_query
params[:name].gsub('%20', ' ').gsub('+', ' ').gsub('.html', '')
end
def queue_loading artist_name, mbid
@artist = Artist.create( :name => artist_name, :mbid => mbid, :status => 0 )
Delayed::Job.enqueue(LoadArtistJob.new(artist_name))
end
end