]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lastfm.rb
a9a0a582c99e946655aae50788d0989b38cb73fc
[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 = Bold + @artists[0..10].join(', ') + Bold
32       @artist_string << _(" and %{n} more...") % {:n => diff}
33     else
34       @artist_string = Bold + @artists.join(', ') + Bold
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"), @artist_string, @location, @attendance, @url]
41    end
42    return "%s %s @ %s %s" % [@date.strftime("%a, %b %d"), @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 user <user> => associate your current irc nick with a last.fm user. lastfm set verb <present>, <past> => set your preferred now playing/just played verbs. default \"is listening to\" and \"listened to\".")
86     when :who
87       _("lastfm who [<nick>] => show who <nick> is on last.fm. if <nick> is empty, show who you are on lastfm.")
88     when :compare
89       _("lastfm compare [<nick1>] <nick2> => show musical taste compatibility between nick1 (or user if omitted) and nick2")
90     else
91       _("lastfm [<user>] => show your or <user>'s now playing track on lastfm. np [<user>] => same as 'lastfm'. other topics: events, artist, album, track, now, set, who, compare")
92     end
93   end
94
95   def find_events(m, params)
96     num = params[:num] || @bot.config['lastfm.default_events']
97     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
98
99     location = artist = nil
100     location = params[:location].to_s if params[:location]
101     artist = params[:who].to_s if params[:who]
102
103     uri = nil
104     if artist == nil
105       uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location}"
106       emptymsg = _("no events found in %{location}") % {:location => location}
107     else
108       uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist}"
109       emptymsg = _("no events found by %{artist}") % {:artist => artist}
110     end
111     xml = @bot.httputil.get_response(uri)
112
113     doc = Document.new xml.body
114     if xml.class == Net::HTTPInternalServerError
115       if doc.root and doc.root.attributes["status"] == "failed"
116         m.reply doc.root.elements["error"].text
117       else
118         m.reply _("could not retrieve events")
119       end
120     end
121     disp_events = Array.new
122     events = Array.new
123     doc.root.elements.each("events/event"){ |e|
124       h = {}
125       h[:title] = e.elements["title"].text
126       venue = e.elements["venue"].elements["name"].text
127       city = e.elements["venue"].elements["location"].elements["city"].text
128       country =  e.elements["venue"].elements["location"].elements["country"].text
129       h[:location] = Underline + venue + Underline + " #{Bold + city + Bold}, #{country}"
130       date = e.elements["startDate"].text.split
131       h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
132       h[:desc] = e.elements["description"].text
133       h[:url] = e.elements["url"].text
134       e.detect {|node|
135         if node.kind_of? Element and node.attributes["name"] == "attendance" then
136           h[:attendance] = node.text
137         end
138       }
139       artists = Array.new
140       e.elements.each("artists/artist"){ |a|
141         artists << a.text
142       }
143       h[:artists] = artists
144       events << LastFmEvent.new(h)
145     }
146     if events.empty?
147       m.reply emptymsg
148       return
149     end
150     events[0...num].each { |event|
151       disp_events << event.to_s
152     }
153     m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
154
155   end
156
157   def tasteometer(m, params)
158     opts = { :cache => false }
159     user1 = resolve_username(m, params[:user1])
160     user2 = resolve_username(m, params[:user2])
161     xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
162     doc = Document.new xml.body
163     unless doc
164       m.reply _("last.fm parsing failed")
165       return
166     end
167     if xml.class == Net::HTTPBadRequest
168       if doc.root.elements["error"].attributes["code"] == "7" then
169         error = doc.root.elements["error"].text
170         error.match(/Invalid username: \[(.*)\]/);
171         baduser = $1
172
173         m.reply _("%{u} doesn't exist on last.fm") % {:u => baduser}
174         return
175       else
176         m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
177         return
178       end
179     end
180     score = doc.root.elements["comparison/result/score"].text.to_f
181     artists = doc.root.get_elements("comparison/result/artists/artist").map { |e| e.elements["name"].text}
182     case
183       when score >= 0.9
184         rating = _("Super")
185       when score >= 0.7
186         rating = _("Very High")
187       when score >= 0.5
188         rating = _("High")
189       when score >= 0.3
190         rating = _("Medium")
191       when score >= 0.1
192         rating = _("Low")
193       else
194         rating = _("Very Low")
195     end
196
197     reply = _("%{a}'s and %{b}'s musical compatibility rating is %{bold}%{r}%{bold}") % {
198       :a => user1,
199       :b => user2,
200       :r => rating.downcase,
201       :bold => Bold
202     }
203
204     reply << _(" and music they have in common includes: %{artists}") % {
205       :artists => artists.join(", ")
206     } unless artists.empty?
207
208     m.reply reply
209   end
210
211   def now_playing(m, params)
212     opts = { :cache => false }
213     user = resolve_username(m, params[:who])
214     xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
215     doc = Document.new xml.body
216     unless doc
217       m.reply _("last.fm parsing failed")
218       return
219     end
220     if xml.class == Net::HTTPBadRequest
221       if doc.root.elements["error"].text == "Invalid user name supplied" then
222         m.reply _("%{user} doesn't exist on last.fm, perhaps they need to: lastfm 2 <username>") % {
223           :user => user
224         }
225         return
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     past = nil
247     date = XPath.first(first, "//date")
248     if date != nil
249       time = date.attributes["uts"]
250       past = Time.at(time.to_i)
251     end
252     if now == "true"
253        verb = _("is listening to")
254        if @registry.has_key? "#{m.sourcenick}_verb_present"
255          verb = @registry["#{m.sourcenick}_verb_present"]
256        end
257        m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
258     else
259       verb = _("listened to")
260        if @registry.has_key? "#{m.sourcenick}_verb_past"
261          verb = @registry["#{m.sourcenick}_verb_past"]
262        end
263       ago = Utils.timeago(past)
264       m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
265     end
266   end
267
268   def find_artist(m, params)
269     xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
270     unless xml
271       m.reply _("I had problems getting info for %{a}") % {:a => params[:artist]}
272       return
273     end
274     doc = Document.new xml
275     unless doc
276       m.reply _("last.fm parsing failed")
277       return
278     end
279     first = doc.root.elements["artist"]
280     artist = first.elements["name"].text
281     playcount = first.elements["stats"].elements["playcount"].text
282     listeners = first.elements["stats"].elements["listeners"].text
283     summary = first.elements["bio"].elements["summary"].text
284     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}
285     m.reply summary.ircify_html
286   end
287
288   def find_track(m, params)
289     track = params[:track].to_s
290     xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
291     unless xml
292       m.reply _("I had problems getting info for %{a}") % {:a => track}
293       return
294     end
295     debug xml
296     doc = Document.new xml
297     unless doc
298       m.reply _("last.fm parsing failed")
299       return
300     end
301     debug doc.root
302     results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
303     if results > 0
304       begin
305         hits = []
306         doc.root.each_element("results/trackmatches/track") do |track|
307           hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
308             :t => track.elements["name"].text,
309             :a => track.elements["artist"].text,
310             :n => track.elements["listeners"].text,
311             :bold => Bold
312           }
313         end
314         m.reply hits.join(' -- '), :split_at => ' -- '
315       rescue
316         error $!
317         m.reply _("last.fm parsing failed")
318       end
319     else
320       m.reply _("track %{a} not found") % {:a => track}
321     end
322   end
323
324   def get_album(artist, album)
325     xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
326     unless xml
327       return [_("I had problems getting album info")]
328     end
329     doc = Document.new xml
330     unless doc
331       return [_("last.fm parsing failed")]
332     end
333     album = date = playcount = artist = date = year = nil
334     first = doc.root.elements["album"]
335     artist = first.elements["artist"].text
336     playcount = first.elements["playcount"].text
337     album = first.elements["name"].text
338     date = first.elements["releasedate"].text
339     unless date.strip.length < 2
340       year = date.strip.split[2].chop
341     end
342     result = [artist, album, year, playcount]
343     return result
344   end
345
346   def find_album(m, params)
347     album = get_album(params[:artist].to_s, params[:album].to_s)
348     if album.length == 1
349       m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
350       return
351     end
352     year = "(#{album[2]}) " unless album[2] == nil
353     m.reply _("the album \"%{a}\" by %{r} %{y}has been played %{c} times") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
354   end
355
356   def set_user(m, params)
357     user = params[:who].to_s
358     nick = m.sourcenick
359     @registry[ nick ] = user
360     m.reply _("okay, I'll remember that %{n} is %{u} on last.fm") % {:n => nick, :u => user}
361   end
362
363   def set_verb(m, params)
364     past = params[:past].to_s
365     present = params[:present].to_s
366     key = "#{m.sourcenick}_verb_"
367     @registry[ "#{key}past" ] = past
368     @registry[ "#{key}present" ] = present
369     m.reply _("okay, I'll remember that %{n} prefers \"%{r}\" and \"%{p}\"") % {:n => m.sourcenick, :p => past, :r => present}
370   end
371
372   def get_user(m, params)
373     nick = ""
374     if params[:who]
375       nick = params[:who].to_s
376     else
377       nick = m.sourcenick
378     end
379     if @registry.has_key? nick
380       user = @registry[ nick ]
381       m.reply _("%{nick} is %{user} on last.fm") % {
382         :nick => nick,
383         :user => user
384       }
385     else
386       m.reply _("sorry, I don't know who %{n} is on last.fm, perhaps they need to: lastfm set user <username>") % {:n => nick}
387     end
388   end
389
390   # TODO this user data retrieval should be upgraded to API 2.0 but it would need separate parsing
391   # for each dataset, or almost
392   def lastfm(m, params)
393     action = params[:action].intern
394     action = :neighbours if action == :neighbors
395     action = :recenttracks if action == :recentracks
396     action = :topalbums if action == :topalbum
397     action = :topartists if action == :topartist
398     action = :toptags if action == :toptag
399     user = resolve_username(m, params[:user])
400     begin
401       data = @bot.httputil.get("http://ws.audioscrobbler.com/1.0/user/#{user}/#{action}.txt")
402       m.reply "#{action} for #{user}:"
403       m.reply data.to_a[0..3].map{|l| l.split(',',2)[-1].chomp}.join(", ")
404     rescue
405       m.reply "could not find #{action} for #{user} (is #{user} a user?). perhaps you need to: lastfm set <username>"
406     end
407   end
408
409   def resolve_username(m, name)
410     name = m.sourcenick if name.nil?
411     @registry[name] or name
412   end
413 end
414
415 plugin = LastFmPlugin.new
416 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
417 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
418 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :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 user[name] :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 compare to :user2', :action => :tasteometer, :thread => true
426 plugin.map 'lastfm compare [:user1] [to] :user2', :action => :tasteometer, :thread => true
427 plugin.map "lastfm [user] :action [:user]", :thread => true,
428   :requirements => { :action =>
429     /^(?:events|friends|neighbou?rs|playlists|recent?tracks|top(?:album|artist|tag)s?|weekly(?:album|artist|track)chart|weeklychartlist)$/
430 }
431 plugin.map 'lastfm [now] [:who]', :action => :now_playing, :thread => true
432 plugin.map 'np [:who]', :action => :now_playing, :thread => true