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