]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lastfm.rb
d2e43fa0f90e0bf3706d5fea189cd0ed46c16c0e
[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    unless @attendance.zero?
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 = params[:location]
100     artist = params[:who]
101     user = resolve_username(m, params[:user])
102
103     if location
104       uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location.to_s}"
105       emptymsg = _("no events found in %{location}") % {:location => location.to_s}
106     elsif artist
107       uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist.to_s}"
108       emptymsg = _("no events found by %{artist}") % {:artist => artist.to_s}
109     elsif user
110       uri = "#{APIURL}method=user.getevents&user=#{CGI.escape user}"
111       emptymsg = _("%{user} is not attending any events") % {:user => user}
112     end
113     xml = @bot.httputil.get_response(uri)
114
115     doc = Document.new xml.body
116     if xml.class == Net::HTTPInternalServerError
117       if doc.root and doc.root.attributes["status"] == "failed"
118         m.reply doc.root.elements["error"].text
119       else
120         m.reply _("could not retrieve events")
121       end
122     end
123     disp_events = Array.new
124     events = Array.new
125     doc.root.elements.each("events/event"){ |e|
126       h = {}
127       h[:title] = e.elements["title"].text
128       venue = e.elements["venue"].elements["name"].text
129       city = e.elements["venue"].elements["location"].elements["city"].text
130       country =  e.elements["venue"].elements["location"].elements["country"].text
131       h[:location] = Underline + venue + Underline + " #{Bold + city + Bold}, #{country}"
132       date = e.elements["startDate"].text.split
133       h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
134       h[:desc] = e.elements["description"].text
135       h[:url] = e.elements["url"].text
136       h[:attendance] = e.elements["attendance"].text.to_i
137       artists = Array.new
138       e.elements.each("artists/artist"){ |a|
139         artists << a.text
140       }
141       h[:artists] = artists
142       events << LastFmEvent.new(h)
143     }
144     if events.empty?
145       m.reply emptymsg
146       return
147     end
148     events[0...num].each { |event|
149       disp_events << event.to_s
150     }
151     m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
152
153   end
154
155   def tasteometer(m, params)
156     opts = { :cache => false }
157     user1 = resolve_username(m, params[:user1])
158     user2 = resolve_username(m, params[:user2])
159     xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
160     doc = Document.new xml.body
161     unless doc
162       m.reply _("last.fm parsing failed")
163       return
164     end
165     if xml.class == Net::HTTPBadRequest
166       if doc.root.elements["error"].attributes["code"] == "7" then
167         error = doc.root.elements["error"].text
168         error.match(/Invalid username: \[(.*)\]/);
169         baduser = $1
170
171         m.reply _("%{u} doesn't exist on last.fm") % {:u => baduser}
172         return
173       else
174         m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
175         return
176       end
177     end
178     score = doc.root.elements["comparison/result/score"].text.to_f
179     artists = doc.root.get_elements("comparison/result/artists/artist").map { |e| e.elements["name"].text}
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
195     reply = _("%{a}'s and %{b}'s musical compatibility rating is %{bold}%{r}%{bold}") % {
196       :a => user1,
197       :b => user2,
198       :r => rating.downcase,
199       :bold => Bold
200     }
201
202     reply << _(" and music they have in common includes: %{artists}") % {
203       :artists => artists.join(", ")
204     } unless artists.empty?
205
206     m.reply reply
207   end
208
209   def now_playing(m, params)
210     opts = { :cache => false }
211     user = resolve_username(m, params[:who])
212     xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
213     doc = Document.new xml.body
214     unless doc
215       m.reply _("last.fm parsing failed")
216       return
217     end
218     if xml.class == Net::HTTPBadRequest
219       if doc.root.elements["error"].text == "Invalid user name supplied" then
220         m.reply _("%{user} doesn't exist on last.fm, perhaps they need to: lastfm user <username>") % {
221           :user => user
222         }
223         return
224       else
225         m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
226         return
227       end
228     end
229     now = artist = track = albumtxt = date = nil
230     unless doc.root.elements[1].has_elements?
231      m.reply _("%{u} hasn't played anything recently") % {:u => user}
232      return
233     end
234     first = doc.root.elements[1].elements[1]
235     now = first.attributes["nowplaying"]
236     artist = first.elements["artist"].text
237     track = first.elements["name"].text
238     albumtxt = first.elements["album"].text
239     album = ""
240     if albumtxt
241       year = get_album(artist, albumtxt)[2]
242       album = "[#{albumtxt}, #{year}] " if year
243     end
244     past = nil
245     date = XPath.first(first, "//date")
246     if date != nil
247       time = date.attributes["uts"]
248       past = Time.at(time.to_i)
249     end
250     if now == "true"
251        verb = _("is listening to")
252        if @registry.has_key? "#{m.sourcenick}_verb_present"
253          verb = @registry["#{m.sourcenick}_verb_present"]
254        end
255        m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
256     else
257       verb = _("listened to")
258        if @registry.has_key? "#{m.sourcenick}_verb_past"
259          verb = @registry["#{m.sourcenick}_verb_past"]
260        end
261       ago = Utils.timeago(past)
262       m.reply _("%{u} %{v} \"%{t}\" by %{a} %{b}%{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
263     end
264   end
265
266   def find_artist(m, params)
267     xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
268     unless xml
269       m.reply _("I had problems getting info for %{a}") % {:a => params[:artist]}
270       return
271     end
272     doc = Document.new xml
273     unless doc
274       m.reply _("last.fm parsing failed")
275       return
276     end
277     first = doc.root.elements["artist"]
278     artist = first.elements["name"].text
279     playcount = first.elements["stats"].elements["playcount"].text
280     listeners = first.elements["stats"].elements["listeners"].text
281     summary = first.elements["bio"].elements["summary"].text
282     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}
283     m.reply summary.ircify_html
284   end
285
286   def find_track(m, params)
287     track = params[:track].to_s
288     xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
289     unless xml
290       m.reply _("I had problems getting info for %{a}") % {:a => track}
291       return
292     end
293     debug xml
294     doc = Document.new xml
295     unless doc
296       m.reply _("last.fm parsing failed")
297       return
298     end
299     debug doc.root
300     results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
301     if results > 0
302       begin
303         hits = []
304         doc.root.each_element("results/trackmatches/track") do |track|
305           hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
306             :t => track.elements["name"].text,
307             :a => track.elements["artist"].text,
308             :n => track.elements["listeners"].text,
309             :bold => Bold
310           }
311         end
312         m.reply hits.join(' -- '), :split_at => ' -- '
313       rescue
314         error $!
315         m.reply _("last.fm parsing failed")
316       end
317     else
318       m.reply _("track %{a} not found") % {:a => track}
319     end
320   end
321
322   def get_album(artist, album)
323     xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
324     unless xml
325       return [_("I had problems getting album info")]
326     end
327     doc = Document.new xml
328     unless doc
329       return [_("last.fm parsing failed")]
330     end
331     album = date = playcount = artist = date = year = nil
332     first = doc.root.elements["album"]
333     artist = first.elements["artist"].text
334     playcount = first.elements["playcount"].text
335     album = first.elements["name"].text
336     date = first.elements["releasedate"].text
337     unless date.strip.length < 2
338       year = date.strip.split[2].chop
339     end
340     result = [artist, album, year, playcount]
341     return result
342   end
343
344   def find_album(m, params)
345     album = get_album(params[:artist].to_s, params[:album].to_s)
346     if album.length == 1
347       m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
348       return
349     end
350     year = "(#{album[2]}) " unless album[2] == nil
351     m.reply _("the album \"%{a}\" by %{r} %{y}has been played %{c} times") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
352   end
353
354   def set_user(m, params)
355     user = params[:who].to_s
356     nick = m.sourcenick
357     @registry[ nick ] = user
358     m.reply _("okay, I'll remember that %{n} is %{u} on last.fm") % {:n => nick, :u => user}
359   end
360
361   def set_verb(m, params)
362     past = params[:past].to_s
363     present = params[:present].to_s
364     key = "#{m.sourcenick}_verb_"
365     @registry[ "#{key}past" ] = past
366     @registry[ "#{key}present" ] = present
367     m.reply _("okay, I'll remember that %{n} prefers \"%{r}\" and \"%{p}\"") % {:n => m.sourcenick, :p => past, :r => present}
368   end
369
370   def get_user(m, params)
371     nick = ""
372     if params[:who]
373       nick = params[:who].to_s
374     else
375       nick = m.sourcenick
376     end
377     if @registry.has_key? nick
378       user = @registry[ nick ]
379       m.reply _("%{nick} is %{user} on last.fm") % {
380         :nick => nick,
381         :user => user
382       }
383     else
384       m.reply _("sorry, I don't know who %{n} is on last.fm, perhaps they need to: lastfm set user <username>") % {:n => nick}
385     end
386   end
387
388   def lastfm(m, params)
389     action = case params[:action]
390     when "neighbors"   then "neighbours"
391     when "recentracks" then "recenttracks"
392     when /^weekly(track|album|artist)s$/
393       "weekly#{$1}chart"
394     when "events"
395       find_events(m, params)
396       return
397     else
398       params[:action]
399     end.to_sym
400
401     user = resolve_username(m, params[:user])
402     uri = "#{APIURL}method=user.get#{action}&user=#{CGI.escape user}"
403
404     if period = params[:period]
405       period_uri = (period.last == "year" ? "12month" : period.first + "month")
406       uri << "&period=#{period_uri}"
407     end
408
409     res = @bot.httputil.get_response(uri)
410     unless res.body
411       m.reply _("I had problems accessing last.fm")
412       return
413     end
414     doc = Document.new(res.body)
415     unless doc
416       m.reply _("last.fm parsing failed")
417       return
418     end
419
420     case res
421     when Net::HTTPBadRequest
422       if doc.root and doc.root.attributes["status"] == "failed"
423         m.reply "error: " << doc.root.elements["error"].text.downcase
424       end
425       return
426     end
427
428     case action
429     when :friends
430       friends = doc.root.get_elements("friends/user").map do |u|
431         u.elements["name"].text
432       end
433
434       unless friends.empty?
435         m.reply _("%{user} has %{total} friends; %{friends}") %
436           { :user => user, :total => friends.size, :friends => friends.join(", ") }
437       else
438         m.reply _("%{user} has no friends :(") % { :user => user }
439       end
440     when :lovedtracks
441       loved = doc.root.get_elements("lovedtracks/track").map do |track|
442         [track.elements["artist/name"].text, track.elements["name"].text].join(" - ")
443       end
444       loved_prep = loved.shuffle[0..4].to_enum(:each_with_index).collect { |e,i| (i % 2).zero? ? Underline+e+Underline : e }
445
446       unless loved.empty?
447         m.reply _("%{user} has loved %{total} tracks, including %{tracks} %{uri}") % {
448           :user => user,
449           :total => loved.size,
450           :tracks => loved_prep.join(", "),
451           :uri => "http://www.last.fm/user/#{CGI.escape user}/library/loved"
452         }
453       else
454         m.reply _("%{user} has not loved any tracks") % { :user => user }
455       end
456     when :neighbours
457       nbrs = doc.root.get_elements("neighbours/user").map do |u|
458         u.elements["name"].text
459       end
460
461       unless nbrs.empty?
462         m.reply _("%{user}'s musical neighbors include %{nbrs} %{uri}") % {
463           :user  => user,
464           :nbrs  => nbrs.shuffle[0..9].join(", "),
465           :uri   => "http://www.last.fm/user/#{CGI.escape user}/neighbours"
466         }
467       else
468         m.reply _("no one seems to share %{user}'s musical taste") % { :user => user }
469       end
470     when :recenttracks
471       tracks = doc.root.get_elements("recenttracks/track").map do |track|
472         [track.elements["artist"].text, track.elements["name"].text].join(" - ")
473       end
474       tracks_prep = tracks.to_enum(:each_with_index).collect { |e,i| (i % 2).zero? ? Underline+e+Underline : e }
475
476       unless tracks.empty?
477         m.reply _("%{user} has recently played %{tracks}") %
478           { :user => user, :tracks => tracks_prep.join(", ") }
479       else
480         m.reply _("%{user} hasn't played anything recently") % { :user => user }
481       end
482     when :shouts
483       shouts = doc.root.get_elements("shouts/shout")
484       unless shouts.empty?
485         shouts[0..4].each do |shout|
486           m.reply _("<%{author}> %{body}") % {
487             :body   => shout.elements["body"].text,
488             :author => shout.elements["author"].text,
489           }
490         end
491       else
492         m.reply _("there are no shouts for %{user}") % { :user => user }
493       end
494     when :toptracks, :topalbums, :topartists, :weeklytrackchart, :weeklyalbumchart, :weeklyartistchart
495       type  = action.to_s.scan(/track|album|artist/).to_s
496       items = doc.root.get_elements("#{action}/#{type}").map do |item|
497         case action
498         when :weeklytrackchart, :weeklyalbumchart
499           format = "%{artist} - %{title} (%{bold}%{plays}%{bold})"
500           artist = item.elements["artist"].text
501         when :weeklyartistchart, :topartists
502           format = "%{artist} (%{bold}%{plays}%{bold})"
503           artist = item.elements["name"].text
504         when :toptracks, :topalbums
505           format = "%{artist} - (%{title} %{bold}%{plays}%{bold})"
506           artist = item.elements["artist/name"].text
507         end
508
509         _(format) % {
510           :artist => artist,
511           :title  => item.elements["name"].text,
512           :plays  => item.elements["playcount"].text,
513           :bold   => Bold
514         }
515       end
516       m.reply items[0..9].join(", ")
517     end
518   end
519
520   def resolve_username(m, name)
521     name = m.sourcenick if name.nil?
522     @registry[name] or name
523   end
524 end
525
526 plugin = LastFmPlugin.new
527 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
528 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
529 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
530 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
531 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
532 plugin.map 'lastfm track *track', :action => :find_track, :thread => true
533 plugin.map 'lastfm set user[name] :who', :action => :set_user, :thread => true
534 plugin.map 'lastfm set verb *present, *past', :action => :set_verb, :thread => true
535 plugin.map 'lastfm who [:who]', :action => :get_user, :thread => true
536 plugin.map 'lastfm compare to :user2', :action => :tasteometer, :thread => true
537 plugin.map 'lastfm compare [:user1] [to] :user2', :action => :tasteometer, :thread => true
538 plugin.map "lastfm [user] :action [:user]", :thread => true,
539   :requirements => { :action =>
540     /^(?:events|shouts|friends|neighbou?rs|(?:loved|recent?)tracks|top(?:album|artist|track)s?|weekly(?:albums?|artists?|tracks?)(?:chart)?)$/
541 }
542 plugin.map 'lastfm [user] :action [:user] over [*period]', :thread => true,
543   :requirements => {
544     :action => /^(?:top(?:album|artist|track)s?)$/,
545     :period => /^(?:(?:3|6|12) months)|(?:a\s|1\s)?year$/
546 }
547 plugin.map 'lastfm [now] [:who]', :action => :now_playing, :thread => true
548 plugin.map 'np [:who]', :action => :now_playing, :thread => true