Created
October 13, 2009 23:52
-
-
Save dewski/209680 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LyricsController < ApplicationController | |
| def find | |
| already_have = Song.find_by_song_and_artist(params[:song], params[:artist]) | |
| unless already_have.nil? | |
| logger.info "Already has #{params[:song]} by #{params[:artist]}" | |
| already_have.increment!(:total_plays) | |
| render :text => already_have.lyrics, :content_type => "text/text" | |
| else | |
| require 'open-uri' | |
| notice = "We have updated our lyric database.\nPlease email our support if you have any comments.\nThis notice will go away 10/17.\n\n" | |
| artist = wiki_slug(params[:artist]) | |
| song = wiki_slug(params[:song]) | |
| url = "http://lyrics.wikia.com/#{artist}:#{song}" | |
| logger.info "Request to: #{url}" | |
| doc = Nokogiri::HTML(open(url)) | |
| grabbed = parse_lyrics(doc.css('div#bodyContent div.lyricbox').first.to_s) | |
| lyric = Song.find_by_artist_and_song(artist, song) | |
| unless lyric.nil? | |
| lyric.increment!(:total_plays) | |
| render :text => "#{notice}#{lyric.lyrics}", :content_type => "text/text" | |
| else | |
| unless grabbed.blank? | |
| lyric = Song.new({ | |
| :artist => artist, | |
| :song => song, | |
| :lyrics => grabbed | |
| }).save | |
| render :text => "#{notice}#{grabbed}", :content_type => "text/text" | |
| else | |
| render :text => "Not found", :content_type => "text/text" | |
| end | |
| end | |
| end | |
| end | |
| private | |
| def wiki_slug(string) | |
| string.split(' ').select {|w| w.capitalize! || w }.join(' ').gsub(' ', '_') | |
| end | |
| def parse_lyrics(string) | |
| string.gsub(/<div class="lyricbox">/, '').gsub(/<\/div>/, '').gsub(/<p>/, '').gsub(/<\/p>/, '').gsub(/<br>/, "\n").gsub(/<\/?[^>]*>/, '').gsub(/Send "(.*)" Ringtone to your Cell/, '').lstrip.rstrip | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment