lastfm.rb plugin: a minor bugfix and additional error handling case.
[rbot] / data / rbot / plugins / lastfm.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: lastfm plugin for rbot
5 #
6 # Author:: Jeremy Voorhis
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Author:: Casey Link <unnamedrambler@gmail.com>
9 #
10 # Copyright:: (C) 2005 Jeremy Voorhis
11 # Copyright:: (C) 2007 Giuseppe Bilotta
12 # Copyright:: (C) 2008 Casey Link
13 #
14 # License:: GPL v2
15
16 require 'rexml/document'
17
18 class ::LastFmEvent
19   def initialize(url, date, artist, location, description)
20     @url = url
21     @date = date
22     @artist = artist
23     @location = location
24     @description = description
25   end
26
27   def compact_display
28     return "%s %s @ %s %s" % [@date.strftime("%a %b, %d %Y"), @artist, @location, @url]
29   end
30   alias :to_s :compact_display
31
32 end
33
34 class LastFmPlugin < Plugin
35   include REXML
36   Config.register Config::IntegerValue.new('lastfm.max_events',
37     :default => 25, :validate => Proc.new{|v| v > 1},
38     :desc => "Maximum number of events to display.")
39   Config.register Config::IntegerValue.new('lastfm.default_events',
40     :default => 3, :validate => Proc.new{|v| v > 1},
41     :desc => "Default number of events to display.")
42
43   LASTFM = "http://www.last.fm"
44
45   APIKEY = "b25b959554ed76058ac220b7b2e0a026"
46   APIURL = "http://ws.audioscrobbler.com/2.0/?api_key=#{APIKEY}&"
47
48   def initialize
49     super
50     class << @registry
51       def store(val)
52         val
53       end
54       def restore(val)
55         val
56       end
57     end
58   end
59
60   def help(plugin, topic="")
61     case (topic.intern rescue nil)
62     when :event, :events
63       _("lastfm [<num>] events in <location> => show information on events in or near <location>. lastfm [<num>] events by <artist/group> => show information on events by <artist/group>. The number of events <num> that can be displayed is optional, defaults to %{d} and cannot be higher than %{m}") % {:d => @bot.config['lastfm.default_events'], :m => @bot.config['lastfm.max_events']}
64     when :artist
65       _("lastfm artist <name> => show information on artist <name> from last.fm")
66     when :album
67       _("lastfm album <name> => show information on album <name> from last.fm [not implemented yet]")
68     when :now, :np
69       _("lastfm now [<user>] => show the now playing track from last.fm.  np [<user>] does the same.")
70     when :set
71       _("lastfm set nick <user> => associate your current irc nick with a last.fm user. lastfm set verb <present> <past> => set your preferred now playing verb. default \"listening\" and \"listened\".")
72     when :who
73       _("lastfm who [<nick>] => show who <nick> is at last.fm. if <nick> is empty, show who you are at lastfm.")
74     else
75       _("lastfm [<user>] => show your or <user>'s now playing track at lastfm. np [<user>] => same as 'lastfm'. lastfm <function> [<user>] => lastfm data for <user> on last.fm where <function> in [recenttracks, topartists, topalbums, toptracks, tags, friends, neighbors]. other topics: events, artist, album, now, set, who")
76     end
77   end
78
79   def find_events(m, params)
80     num = params[:num] || @bot.config['lastfm.default_events']
81     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
82
83     location = artist = nil
84     location = params[:location].to_s if params[:location]
85     artist = params[:who].to_s if params[:who]
86
87     uri = nil
88     if artist == nil
89       uri = URI.escape("#{APIURL}method=geo.getevents&location=#{location}")
90     else
91       uri = URI.escape("#{APIURL}method=artist.getevents&artist=#{artist}")
92     end
93     xml = @bot.httputil.get_response(uri)
94
95     doc = Document.new xml.body
96     if xml.class == Net::HTTPInternalServerError
97       if doc.root.attributes["status"] == "failed"
98         m.reply doc.root.elements["error"].text
99       else
100         m.reply _("Could not retrieve events")
101       end
102     end
103     disp_events = Array.new
104     events = Array.new
105     doc.root.elements.each("events/event"){ |e|
106       title = e.elements["title"].text
107       venue = e.elements["venue"].elements["name"].text
108       city = e.elements["venue"].elements["location"].elements["city"].text
109       country =  e.elements["venue"].elements["location"].elements["country"].text
110       loc = Bold + venue + Bold + " #{city}, #{country}"
111       date = e.elements["startDate"].text.split
112       date = Time.utc(date[3].to_i, date[2], date[1].to_i)
113       desc = e.elements["description"].text
114       url = e.elements["url"].text
115       artists = Array.new
116       e.elements.each("artists/artist"){ |a|
117         artists << a.text
118       }
119       if artists.length > 10 #more than 10 artists and it floods
120        diff = artists.length - 10
121        artists = artists[0..10]
122        artists << _(" and %{n} more...") % {:n => diff}
123       end
124       artists = artists.join(", ")
125       events << LastFmEvent.new(url, date, artists, loc, desc)
126     }
127     events[0...num].each { |event|
128       disp_events << event.to_s
129     }
130     m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
131
132   end  
133
134   def tasteometer(m, params)
135     opts = { :cache => false }
136     user1 = params[:user1].to_s
137     user2 = params[:user2].to_s
138     xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{user1}&value2=#{user2}", opts)
139     doc = Document.new xml.body
140     unless doc
141       m.reply _("last.fm parsing failed")
142       return
143     end
144     if xml.class == Net::HTTPInternalServerError
145       if doc.root.elements["error"].attributes["code"] == "7" then 
146         error = doc.root.elements["error"].text
147         error.match(/Invalid username: \[(.*)\]/);
148         if @registry.has_key? $1 and not params[:recurs]
149           if user1 == $1
150             params[:user1] = @registry[ $1 ]
151           elsif user2 == $1
152             params[:user2] = @registry[ $1 ]
153           end
154           params[:recurs] = true
155           tasteometer(m, params)
156         else
157           m.reply _("%{u} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>") % {:u => baduser}
158         end
159       else
160         m.reply _("Bad: %{e}") % {:e => doc.root.element["error"].text}
161       end
162     end
163     now = artist = track = albumtxt = date = nil
164     score = doc.root.elements["comparison/result/score"].text.to_f
165     rating = nil
166     case
167       when score >= 0.9
168         rating = _("Super")
169       when score >= 0.7
170         rating = _("Very High")
171       when score >= 0.5
172         rating = _("High")
173       when score >= 0.3
174         rating = _("Medium")
175       when score >= 0.1
176         rating = _("Low")
177       else
178         rating = _("Very Low")
179     end
180     m.reply _("%{a}'s and %{b}'s musical compatibility rating is: %{r}") % {:a => user1, :b => user2, :r => rating}
181   end
182
183   def now_playing(m, params)
184     opts = { :cache => false }
185     user = nil
186     if params[:who]
187       user = params[:who].to_s
188     elsif @registry.has_key? m.sourcenick
189       user = @registry[ m.sourcenick ]
190     else
191       user = m.sourcenick
192     end
193     xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{user}", opts)
194     doc = Document.new xml.body
195     unless doc
196       m.reply _("last.fm parsing failed")
197       return
198     end
199     if xml.class == Net::HTTPBadRequest
200       if doc.root.elements["error"].text == "Invalid user name supplied" then 
201         if @registry.has_key? user and not params[:recurs]
202           params[:who] = @registry[ user ]
203           params[:recurs] = true
204           now_playing(m, params)
205         else
206           m.reply "#{user} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>"
207         end
208       else
209         m.reply _("Error %{e}") % {:e => doc.root.element["error"].text}
210       end
211     end
212     now = artist = track = albumtxt = date = nil
213     unless doc.root.elements["recenttracks"].has_elements?
214       m.reply _("%{u} hasn't played anything recently") % {:u => user}
215     end
216     first = doc.root.elements[1].elements[1]
217     now = first.attributes["nowplaying"]
218     artist = first.elements["artist"].text
219     track = first.elements["name"].text
220     albumtxt = first.elements["album"].text
221     year = get_album(artist, albumtxt)[2]
222     album = "[#{albumtxt}, #{year}] " unless albumtxt == nil or year.length == 1
223     date = first.elements["date"].attributes["uts"]
224     past = Time.at(date.to_i)
225     if now == "true"
226        verb = _("listening")
227        if @registry.has_key? "#{m.sourcenick}_verb_present"
228          verb = @registry["#{m.sourcenick}_verb_present"]
229        end
230       m.reply _("%{u} is %{v} to \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
231     else
232       verb = _("listened")
233        if @registry.has_key? "#{m.sourcenick}_verb_past"
234          verb = @registry["#{m.sourcenick}_verb_past"]
235        end
236       ago = Utils.timeago(past)
237       m.reply _("%{u} %{v} to \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
238     end
239   end
240
241   def find_artist(m, params)
242     xml = @bot.httputil.get(URI.escape("#{APIURL}method=artist.getinfo&artist=#{params[:artist]}"))
243     unless xml
244       m.reply _("I had problems getting info for %{a}.") % {:a => params[:artist]}
245     end
246     doc = Document.new xml
247     unless doc
248       m.reply _("last.fm parsing failed")
249     end
250     first = doc.root.elements["artist"]
251     artist = first.elements["name"].text
252     playcount = first.elements["stats"].elements["plays"].text
253     listeners = first.elements["stats"].elements["listeners"].text
254     summary = first.elements["bio"].elements["summary"].text
255     m.reply _("\"%{a}\" has been played %{c} times and is being listened to by %{l} people.") % {:a => artist, :c => playcount, :l => listeners}
256     m.reply summary.strip
257   end
258
259   def get_album(artist, album)
260     xml = @bot.httputil.get(URI.escape("#{APIURL}method=album.getinfo&artist=#{artist}&album=#{album}"))
261     unless xml
262       return [_("I had problems getting album info")]
263     end
264     doc = Document.new xml
265     unless doc
266       return [_("last.fm parsing failed")]
267     end
268     album = date = playcount = artist = date = year = nil
269     first = doc.root.elements["album"]
270     artist = first.elements["artist"].text
271     playcount = first.elements["playcount"].text
272     album = first.elements["name"].text
273     date = first.elements["releasedate"].text
274     unless date.strip.length < 2 
275       year = date.strip.split[2].chop
276     end
277     result = [artist, album, year, playcount]
278     return result
279   end
280
281   def find_album(m, params)
282     album = get_album(params[:artist].to_s, params[:album].to_s)
283     if album.length == 1
284       m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
285       return
286     end
287     year = "(#{album[2]}) " unless album[2] == nil
288     m.reply _("The album \"%{a}\" by %{r} %{y}has been played %{c} times.") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
289   end
290
291   def set_user(m, params)
292     user = params[:who].to_s
293     nick = m.sourcenick
294     @registry[ nick ] = user
295     m.reply _("Ok, I'll remember that %{n} is %{u} at last.fm") % {:n => nick, :u => user}
296   end
297
298   def set_verb(m, params)
299     past = params[:past].to_s
300     present = params[:present].to_s
301     key = "#{m.sourcenick}_verb_"
302     @registry[ "#{key}past" ] = past
303     @registry[ "#{key}present" ] = present
304     m.reply _("Ok, I'll remember that %{n} prefers %{p} and %{r}.") % {:n => m.sourcenick, :p => past, :r => present}
305   end
306
307   def get_user(m, params)
308     nick = ""
309     if params[:who]
310       nick = params[:who].to_s
311     else 
312       nick = m.sourcenick
313     end
314     if @registry.has_key? nick
315       user = @registry[ nick ]
316       m.reply "#{nick} is #{user} at last.fm"
317     else
318       m.reply _("Sorry, I don't know who %{n} is at last.fm perhaps you need to: lastfm set <username>") % {:n => nick}
319     end
320   end
321
322   def lastfm(m, params)
323     action = params[:action].intern
324     action = :neighbours if action == :neighbors
325     user = nil
326     if params[:user] then
327       user = params[:user].to_s
328     elsif @registry.has_key? m.sourcenick
329       user = @registry[ m.sourcenick ]
330     else
331       # m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
332       # return
333       user = m.sourcenick
334     end
335     begin
336       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
337       m.reply "#{action} for #{user}:"
338       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
339     rescue
340       m.reply "could not find #{action} for #{user} (is #{user} a user?). perhaps you need to: lastfm set <username>"
341     end
342   end
343 end
344
345 plugin = LastFmPlugin.new
346 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
347 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
348 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
349 plugin.map 'lastfm now :who', :action => :now_playing, :thread => true
350 plugin.map 'lastfm now', :action => :now_playing, :thread => true
351 plugin.map 'np :who', :action => :now_playing, :thread => true
352 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
353 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
354 plugin.map 'lastfm set nick :who', :action => :set_user, :thread => true
355 plugin.map 'lastfm set verb :present :past', :action => :set_verb, :thread => true
356 plugin.map 'lastfm who :who', :action => :get_user, :thread => true
357 plugin.map 'lastfm who', :action => :get_user, :thread => true
358 plugin.map 'lastfm compare :user1 :user2', :action => :tasteometer, :thread => true
359 #plugin.map 'lastfm :action :user', :thread => true
360 #plugin.map 'lastfm :action', :thread => true
361 plugin.map 'np', :action => :now_playing, :thread => true
362 plugin.map 'lastfm', :action => :now_playing, :thread => true