]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lastfm.rb
1efb58fd40db571993e6b6ebad1c39242a5157f1
[user/henk/code/ruby/rbot.git] / 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 require 'cgi'
18
19 class ::LastFmEvent
20   def initialize(hash)
21     @url = hash[:url]
22     @date = hash[:date]
23     @location = hash[:location]
24     @description = hash[:description]
25     @attendance = hash[:attendance]
26
27     @artists = hash[:artists]
28
29     if @artists.length > 10 #more than 10 artists and it floods
30       diff = @artists.length - 10
31       @artist_string = @artists[0..10].join(', ')
32       @artist_string << _(" and %{n} more...") % {:n => diff}
33     else
34       @artist_string = @artists.join(', ')
35     end
36   end
37
38   def compact_display
39    if @attendance
40      return "%s %s @ %s (%s attending) %s" % [@date.strftime("%a %b, %d %Y"), @artist_string, @location, @attendance, @url]
41    end
42    return "%s %s @ %s %s" % [@date.strftime("%a %b, %d %Y"), @artist_string, @location, @url]
43   end
44   alias :to_s :compact_display
45
46 end
47
48 class LastFmPlugin < Plugin
49   include REXML
50   Config.register Config::IntegerValue.new('lastfm.max_events',
51     :default => 25, :validate => Proc.new{|v| v > 1},
52     :desc => "Maximum number of events to display.")
53   Config.register Config::IntegerValue.new('lastfm.default_events',
54     :default => 3, :validate => Proc.new{|v| v > 1},
55     :desc => "Default number of events to display.")
56
57   APIKEY = "b25b959554ed76058ac220b7b2e0a026"
58   APIURL = "http://ws.audioscrobbler.com/2.0/?api_key=#{APIKEY}&"
59
60   def initialize
61     super
62     class << @registry
63       def store(val)
64         val
65       end
66       def restore(val)
67         val
68       end
69     end
70   end
71
72   def help(plugin, topic="")
73     case (topic.intern rescue nil)
74     when :event, :events
75       _("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']}
76     when :artist
77       _("lastfm artist <name> => show information on artist <name> from last.fm")
78     when :album
79       _("lastfm album <name> => show information on album <name> from last.fm [not implemented yet]")
80     when :track
81       _("lastfm track <name> => search tracks matching <name> on last.fm")
82     when :now, :np
83       _("lastfm now [<user>] => show the now playing track from last.fm.  np [<user>] does the same.")
84     when :set
85       _("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\".")
86     when :who
87       _("lastfm who [<nick>] => show who <nick> is at last.fm. if <nick> is empty, show who you are at lastfm.")
88     else
89       _("lastfm [<user>] => show your or <user>'s now playing track at lastfm. np [<user>] => same as 'lastfm'. other topics: events, artist, album, track, now, set, who")
90     end
91   end
92
93   def find_events(m, params)
94     num = params[:num] || @bot.config['lastfm.default_events']
95     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
96
97     location = artist = nil
98     location = params[:location].to_s if params[:location]
99     artist = params[:who].to_s if params[:who]
100
101     uri = nil
102     if artist == nil
103       uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location}"
104     else
105       uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist}"
106     end
107     xml = @bot.httputil.get_response(uri)
108
109     doc = Document.new xml.body
110     if xml.class == Net::HTTPInternalServerError
111       if doc.root.attributes["status"] == "failed"
112         m.reply doc.root.elements["error"].text
113       else
114         m.reply _("Could not retrieve events")
115       end
116     end
117     disp_events = Array.new
118     events = Array.new
119     doc.root.elements.each("events/event"){ |e|
120       h = {}
121       h[:title] = e.elements["title"].text
122       venue = e.elements["venue"].elements["name"].text
123       city = e.elements["venue"].elements["location"].elements["city"].text
124       country =  e.elements["venue"].elements["location"].elements["country"].text
125       h[:location] = Bold + venue + Bold + " #{city}, #{country}"
126       date = e.elements["startDate"].text.split
127       h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
128       h[:desc] = e.elements["description"].text
129       h[:url] = e.elements["url"].text
130       e.detect {|node|
131         if node.kind_of? Element and node.attributes["name"] == "attendance" then
132           h[:attendance] = node.text
133         end
134       }
135       artists = Array.new
136       e.elements.each("artists/artist"){ |a|
137         artists << a.text
138       }
139       h[:artists] = artists
140       events << LastFmEvent.new(h)
141     }
142     events[0...num].each { |event|
143       disp_events << event.to_s
144     }
145     m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
146
147   end  
148
149   def tasteometer(m, params)
150     opts = { :cache => false }
151     user1 = params[:user1].to_s
152     user2 = params[:user2].to_s
153     xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
154     doc = Document.new xml.body
155     unless doc
156       m.reply _("last.fm parsing failed")
157       return
158     end
159     if xml.class == Net::HTTPInternalServerError
160       if doc.root.elements["error"].attributes["code"] == "7" then 
161         error = doc.root.elements["error"].text
162         error.match(/Invalid username: \[(.*)\]/);
163         if @registry.has_key? $1 and not params[:recurs]
164           if user1 == $1
165             params[:user1] = @registry[ $1 ]
166           elsif user2 == $1
167             params[:user2] = @registry[ $1 ]
168           end
169           params[:recurs] = true
170           tasteometer(m, params)
171         else
172           m.reply _("%{u} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>") % {:u => baduser}
173           return
174         end
175       else
176         m.reply _("Bad: %{e}") % {:e => doc.root.element["error"].text}
177         return
178       end
179     end
180     now = artist = track = albumtxt = date = nil
181     score = doc.root.elements["comparison/result/score"].text.to_f
182     rating = nil
183     case
184       when score >= 0.9
185         rating = _("Super")
186       when score >= 0.7
187         rating = _("Very High")
188       when score >= 0.5
189         rating = _("High")
190       when score >= 0.3
191         rating = _("Medium")
192       when score >= 0.1
193         rating = _("Low")
194       else
195         rating = _("Very Low")
196     end
197     m.reply _("%{a}'s and %{b}'s musical compatibility rating is: %{r}") % {:a => user1, :b => user2, :r => rating}
198   end
199
200   def now_playing(m, params)
201     opts = { :cache => false }
202     user = nil
203     if params[:who]
204       user = params[:who].to_s
205     elsif @registry.has_key? m.sourcenick
206       user = @registry[ m.sourcenick ]
207     else
208       user = m.sourcenick
209     end
210     xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
211     doc = Document.new xml.body
212     unless doc
213       m.reply _("last.fm parsing failed")
214       return
215     end
216     if xml.class == Net::HTTPBadRequest
217       if doc.root.elements["error"].text == "Invalid user name supplied" then 
218         if @registry.has_key? user and not params[:recurs]
219           params[:who] = @registry[ user ]
220           params[:recurs] = true
221           now_playing(m, params)
222         else
223           m.reply "#{user} doesn't exist at last.fm. Perhaps you need to: lastfm set <username>"
224           return
225         end
226       else
227         m.reply _("Error %{e}") % {:e => doc.root.element["error"].text}
228         return
229       end
230     end
231     now = artist = track = albumtxt = date = nil
232     unless doc.root.elements[1].has_elements?
233      m.reply _("%{u} hasn't played anything recently") % {:u => user}
234      return
235     end
236     first = doc.root.elements[1].elements[1]
237     now = first.attributes["nowplaying"]
238     artist = first.elements["artist"].text
239     track = first.elements["name"].text
240     albumtxt = first.elements["album"].text
241     album = ""
242     if albumtxt
243       year = get_album(artist, albumtxt)[2]
244       album = "[#{albumtxt}, #{year}] " if year
245     end
246     date = first.elements["date"].attributes["uts"]
247     past = Time.at(date.to_i)
248     if now == "true"
249        verb = _("listening")
250        if @registry.has_key? "#{m.sourcenick}_verb_present"
251          verb = @registry["#{m.sourcenick}_verb_present"]
252        end
253       m.reply _("%{u} is %{v} to \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
254     else
255       verb = _("listened")
256        if @registry.has_key? "#{m.sourcenick}_verb_past"
257          verb = @registry["#{m.sourcenick}_verb_past"]
258        end
259       ago = Utils.timeago(past)
260       m.reply _("%{u} %{v} to \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
261     end
262   end
263
264   def find_artist(m, params)
265     xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
266     unless xml
267       m.reply _("I had problems getting info for %{a}.") % {:a => params[:artist]}
268       return
269     end
270     doc = Document.new xml
271     unless doc
272       m.reply _("last.fm parsing failed")
273       return
274     end
275     first = doc.root.elements["artist"]
276     artist = first.elements["name"].text
277     playcount = first.elements["stats"].elements["plays"].text
278     listeners = first.elements["stats"].elements["listeners"].text
279     summary = first.elements["bio"].elements["summary"].text
280     m.reply _("%{b}%{a}%{b} has been played %{c} times and is being listened to by %{l} people.") % {:b => Bold, :a => artist, :c => playcount, :l => listeners}
281     m.reply summary.ircify_html
282   end
283
284   def find_track(m, params)
285     track = params[:track].to_s
286     xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
287     unless xml
288       m.reply _("I had problems getting info for %{a}.") % {:a => track}
289       return
290     end
291     debug xml
292     doc = Document.new xml
293     unless doc
294       m.reply _("last.fm parsing failed")
295       return
296     end
297     debug doc.root
298     results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
299     if results > 0
300       begin
301         hits = []
302         doc.root.each_element("results/trackmatches/track") do |track|
303           hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
304             :t => track.elements["name"].text,
305             :a => track.elements["artist"].text,
306             :n => track.elements["listeners"].text,
307             :bold => Bold
308           }
309         end
310         m.reply hits.join(' -- '), :split_at => ' -- '
311       rescue
312         error $!
313         m.reply _("last.fm parsing failed")
314       end
315     else
316       m.reply _("track %{a} not found") % {:a => track}
317     end
318   end
319
320   def get_album(artist, album)
321     xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
322     unless xml
323       return [_("I had problems getting album info")]
324     end
325     doc = Document.new xml
326     unless doc
327       return [_("last.fm parsing failed")]
328     end
329     album = date = playcount = artist = date = year = nil
330     first = doc.root.elements["album"]
331     artist = first.elements["artist"].text
332     playcount = first.elements["playcount"].text
333     album = first.elements["name"].text
334     date = first.elements["releasedate"].text
335     unless date.strip.length < 2 
336       year = date.strip.split[2].chop
337     end
338     result = [artist, album, year, playcount]
339     return result
340   end
341
342   def find_album(m, params)
343     album = get_album(params[:artist].to_s, params[:album].to_s)
344     if album.length == 1
345       m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
346       return
347     end
348     year = "(#{album[2]}) " unless album[2] == nil
349     m.reply _("The album \"%{a}\" by %{r} %{y}has been played %{c} times.") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
350   end
351
352   def set_user(m, params)
353     user = params[:who].to_s
354     nick = m.sourcenick
355     @registry[ nick ] = user
356     m.reply _("Ok, I'll remember that %{n} is %{u} at last.fm") % {:n => nick, :u => user}
357   end
358
359   def set_verb(m, params)
360     past = params[:past].to_s
361     present = params[:present].to_s
362     key = "#{m.sourcenick}_verb_"
363     @registry[ "#{key}past" ] = past
364     @registry[ "#{key}present" ] = present
365     m.reply _("Ok, I'll remember that %{n} prefers %{r} and %{p}.") % {:n => m.sourcenick, :p => past, :r => present}
366   end
367
368   def get_user(m, params)
369     nick = ""
370     if params[:who]
371       nick = params[:who].to_s
372     else 
373       nick = m.sourcenick
374     end
375     if @registry.has_key? nick
376       user = @registry[ nick ]
377       m.reply "#{nick} is #{user} at last.fm"
378     else
379       m.reply _("Sorry, I don't know who %{n} is at last.fm perhaps you need to: lastfm set <username>") % {:n => nick}
380     end
381   end
382
383   # TODO this user data retrieval should be upgraded to API 2.0 but it would need separate parsing
384   # for each dataset, or almost
385   def lastfm(m, params)
386     action = params[:action].intern
387     action = :neighbours if action == :neighbors
388     action = :recenttracks if action == :recentracks
389     action = :topalbums if action == :topalbum
390     action = :topartists if action == :topartist
391     action = :toptags if action == :toptag
392     user = nil
393     if params[:user] then
394       user = params[:user].to_s
395     elsif @registry.has_key? m.sourcenick
396       user = @registry[ m.sourcenick ]
397     else
398       # m.reply "I don't know who you are on last.fm. Use 'lastfm set username' to identify yourself."
399       # return
400       user = m.sourcenick
401     end
402     begin
403       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
404       m.reply "#{action} for #{user}:"
405       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
406     rescue
407       m.reply "could not find #{action} for #{user} (is #{user} a user?). perhaps you need to: lastfm set <username>"
408     end
409   end
410 end
411
412 plugin = LastFmPlugin.new
413 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
414 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
415 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
416 plugin.map 'lastfm now :who', :action => :now_playing, :thread => true
417 plugin.map 'lastfm now', :action => :now_playing, :thread => true
418 plugin.map 'np :who', :action => :now_playing, :thread => true
419 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
420 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
421 plugin.map 'lastfm track *track', :action => :find_track, :thread => true
422 plugin.map 'lastfm set nick :who', :action => :set_user, :thread => true
423 plugin.map 'lastfm set verb :present :past', :action => :set_verb, :thread => true
424 plugin.map 'lastfm who :who', :action => :get_user, :thread => true
425 plugin.map 'lastfm who', :action => :get_user, :thread => true
426 plugin.map 'lastfm compare :user1 :user2', :action => :tasteometer, :thread => true
427 plugin.map 'np', :action => :now_playing, :thread => true
428 plugin.map 'lastfm', :action => :now_playing, :thread => true
429 plugin.map "lastfm [user] :action [:user]", :thread => true,
430   :requirements => { :action =>
431     /^(?:events|friends|neighbou?rs|playlists|recent?tracks|top(?:album|artist|tag)s?|weekly(?:album|artist|track)chart|weeklychartlist)$/
432 }