]> git.r.bdr.sh - rbdr/lyricli.rb/blob - lib/lyricli.rb
928adadd19c1087e1a334fa680a9f4d92cfc6fcf
[rbdr/lyricli.rb] / lib / lyricli.rb
1 #!/usr/bin/env ruby -w
2
3 require 'uri'
4 require 'net/http'
5 require 'multi_json'
6 require 'nokogiri'
7 require 'open-uri'
8 require 'launchy'
9
10 # This shit causes a lot of warnings. Quick Hack.
11 original_verbosity = $VERBOSE
12 $VERBOSE = nil
13 require 'rdio'
14 $VERBOSE = original_verbosity
15
16 class Lyricli
17
18 # TODO: Change the whole fucking thing
19 def initialize
20 @rdio_key = "sddac5t8akqrzh5b6kg53jfm"
21 @rdio_secret = "PRcB8TggFr"
22 @token_path = File.expand_path("~/.rdio_token")
23
24 #Expand the symlink and get the path
25 if File.symlink?(__FILE__) then
26 path = File.dirname(File.readlink(__FILE__))
27 else
28 path = File.dirname(__FILE__)
29 end
30
31 # Get the current rdio track
32 @rdio = init_rdio
33 rdio_track
34
35 #Get the current iTunes track
36 current = `osascript #{path}/current_song.scpt`
37 if current and not current.empty? then
38 current = current.split("<-SEP->")
39 @artist ||= current[0]
40 @song ||= current[1]
41 end
42 end
43
44 def init_rdio
45
46 if File.exists?(@token_path)
47 f = File.new(@token_path, "r")
48 begin
49 token = MultiJson.decode(f.read)
50 rescue
51 token = create_rdio_token
52 end
53 else
54 token = create_rdio_token
55 end
56
57 Rdio::SimpleRdio.new([@rdio_key, @rdio_secret], token)
58 end
59
60
61 def exit_with_error
62 abort "Usage: #{$0} artist song"
63 end
64
65 def get_lyrics
66
67 #Use the API to search
68 uri = URI("http://lyrics.wikia.com/api.php?artist=#{self.sanitize_param @artist}&song=#{self.sanitize_param @song}&fmt=realjson")
69 begin
70 res = Net::HTTP.get(uri)
71 res = MultiJson.decode(res)
72
73 #Get the actual lyrics url
74 doc = Nokogiri::HTML(open(res['url']))
75 node = doc.search(".lyricbox").first
76 rescue
77 abort "Lyrics not found :("
78 end
79
80 #Remove the rtMatcher nodes
81 node.search(".rtMatcher").each do |n|
82 n.remove
83 end
84
85 #Maintain new lines
86 node.search("br").each do |br|
87 br.replace "\n"
88 end
89
90 #Retrieve the lyrics
91 puts node.inner_text
92 end
93
94 def check_params
95 self.exit_with_error if @artist.nil? or @artist.empty?
96 self.exit_with_error if @song.nil? or @song.empty?
97 end
98
99 def sanitize_param(p)
100 URI.encode_www_form_component(p.gsub(/ /, "+")).gsub("%2B", "+")
101 end
102 end
103
104
105 lrc = Lyricli.new
106 lrc.check_params
107 lrc.get_lyrics