]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lastfm.rb
58f0c249d85603479d5ca01f8ce8bda5d3536c4e
[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 # Author:: Raine Virta <rane@kapsi.fi>
10 #
11 # Copyright:: (C) 2005 Jeremy Voorhis
12 # Copyright:: (C) 2007 Giuseppe Bilotta
13 # Copyright:: (C) 2008 Casey Link
14 # Copyright:: (C) 2009 Raine Virta
15 #
16 # License:: GPL v2
17
18 require 'rexml/document'
19 require 'cgi'
20
21 class ::LastFmEvent
22   def initialize(hash)
23     @url = hash[:url]
24     @date = hash[:date]
25     @location = hash[:location]
26     @description = hash[:description]
27     @attendance = hash[:attendance]
28
29     @artists = hash[:artists]
30
31     if @artists.length > 10 #more than 10 artists and it floods
32       diff = @artists.length - 10
33       @artist_string = Bold + @artists[0..10].join(', ') + Bold
34       @artist_string << _(" and %{n} more...") % {:n => diff}
35     else
36       @artist_string = Bold + @artists.join(', ') + Bold
37     end
38   end
39
40   def compact_display
41    unless @attendance.zero?
42      return "%s %s @ %s (%s attending) %s" % [@date.strftime("%a, %b %d"), @artist_string, @location, @attendance, @url]
43    end
44    return "%s %s @ %s %s" % [@date.strftime("%a, %b %d"), @artist_string, @location, @url]
45   end
46   alias :to_s :compact_display
47
48 end
49
50 define_structure :LastFmVenue, :id, :city, :street, :postal, :country, :name, :url, :lat, :long
51
52 class LastFmPlugin < Plugin
53   include REXML
54   Config.register Config::IntegerValue.new('lastfm.max_events',
55     :default => 25, :validate => Proc.new{|v| v > 1},
56     :desc => "Maximum number of events to display.")
57   Config.register Config::IntegerValue.new('lastfm.default_events',
58     :default => 3, :validate => Proc.new{|v| v > 1},
59     :desc => "Default number of events to display.")
60   Config.register Config::IntegerValue.new('lastfm.max_shouts',
61     :default => 5, :validate => Proc.new{|v| v > 1},
62     :desc => "Maximum number of user shouts to display.")
63   Config.register Config::IntegerValue.new('lastfm.default_shouts',
64     :default => 3, :validate => Proc.new{|v| v > 1},
65     :desc => "Default number of user shouts to display.")
66   Config.register Config::IntegerValue.new('lastfm.max_user_data',
67     :default => 25, :validate => Proc.new{|v| v > 1},
68     :desc => "Maximum number of user data entries (except events and shouts) to display.")
69   Config.register Config::IntegerValue.new('lastfm.default_user_data',
70     :default => 10, :validate => Proc.new{|v| v > 1},
71     :desc => "Default number of user data entries (except events and shouts) to display.")
72
73   APIKEY = "b25b959554ed76058ac220b7b2e0a026"
74   APIURL = "http://ws.audioscrobbler.com/2.0/?api_key=#{APIKEY}&"
75
76   def initialize
77     super
78     class << @registry
79       def store(val)
80         val
81       end
82       def restore(val)
83         val
84       end
85     end
86   end
87
88   def help(plugin, topic="")
89     period = _(", where <period> can be one of: 3|6|12 months, a year")
90     case (topic.intern rescue nil)
91     when :event, :events
92       _("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']}
93     when :artist
94       _("lastfm artist <name> => show information on artist <name> from last.fm")
95     when :album
96       _("lastfm album <name> => show information on album <name> from last.fm [not implemented yet]")
97     when :track
98       _("lastfm track <name> => search tracks matching <name> on last.fm")
99     when :now, :np
100       _("lastfm now [<nick>] => show the now playing track from last.fm. np [<nick>] does the same.")
101     when :set
102       _("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\".")
103     when :who
104       _("lastfm who [<nick>] => show who <nick> is on last.fm. if <nick> is empty, show who you are on lastfm.")
105     when :compare
106       _("lastfm compare [<nick1>] <nick2> => show musical taste compatibility between nick1 (or user if omitted) and nick2")
107     when :shouts
108       _("lastfm shouts [<nick>] => show shouts to <nick>")
109     when :friends
110       _("lastfm friends [<nick>] => show <nick>'s friends")
111     when :neighbors, :neighbours
112       _("lastfm neighbors [<nick>] => show people who share similar musical taste as <nick>")
113     when :lovedtracks
114       _("lastfm loved[tracks] [<nick>] => show tracks that <nick> has loved")
115     when :recenttracks, :recentracks
116       _("lastfm recent[tracks] [<nick>] => show tracks that <nick> has recently played")
117     when :topalbums
118       _("lastfm topalbums [<nick>] [over <period>] => show <nick>'s top albums%{p}") % { :p => period }
119     when :topartists
120       _("lastfm topartists [<nick>] [over <period>] => show <nick>'s top artists%{p}") % { :p => period }
121     when :toptracks
122       _("lastfm toptracks [<nick>] [over <period>] => show <nick>'s top tracks%{p}") % { :p => period }
123     when :weeklyalbumchart
124       _("lastfm weeklyalbumchart [<nick>] => show <nick>'s weekly album chart")
125     when :weeklyartistchart
126       _("lastfm weeklyartistchart [<nick>] => show <nick>'s weekly artist chart")
127     when :weeklytrackchart
128       _("lastfm weeklyartistchart [<nick>] => show <nick>'s weekly track chart")
129     else
130       _("last.fm plugin - topics: events, artist, album, track, now, set, who, compare, shouts, friends, neighbors, (loved|recent)tracks, top(albums|tracks|artists), weekly(album|artist|track)chart")
131     end
132   end
133
134   # TODO allow searching by country etc.
135   #
136   # Options: name, limit
137   def search_venue_by(options)
138     params = {}
139     params[:venue] = CGI.escape(options[:name])
140     options.delete(:name)
141     params.merge!(options)
142
143     uri = "#{APIURL}method=venue.search&"
144     uri << params.to_a.map {|e| e.join("=")}.join("&")
145
146     xml = @bot.httputil.get_response(uri)
147     doc = Document.new xml.body
148     results = []
149
150     doc.root.elements.each("results/venuematches/venue") do |v|
151       venue = LastFmVenue.new
152       venue.id      = v.elements["id"].text.to_i
153       venue.url     = v.elements["url"].text
154       venue.lat     = v.elements["location/geo:point/geo:lat"].text.to_f
155       venue.long    = v.elements["location/geo:point/geo:long"].text.to_f
156       venue.name    = v.elements["name"].text
157       venue.city    = v.elements["location/city"].text
158       venue.street  = v.elements["location/street"].text
159       venue.postal  = v.elements["location/postalcode"].text
160       venue.country = v.elements["location/country"].text
161
162       results << venue
163     end
164     results
165   end
166
167   def find_events(m, params)
168     num = params[:num] || @bot.config['lastfm.default_events']
169     num = num.to_i.clip(1, @bot.config['lastfm.max_events'])
170
171     location = params[:location]
172     artist = params[:who]
173     venue = params[:venue]
174     user = resolve_username(m, params[:user])
175
176     if location
177       uri = "#{APIURL}method=geo.getevents&location=#{CGI.escape location.to_s}"
178       emptymsg = _("no events found in %{location}") % {:location => location.to_s}
179     elsif venue
180       venues = search_venue_by(:name => venue.to_s, :limit => 1)
181       venue  = venues.first
182       uri = "#{APIURL}method=venue.getevents&venue=#{venue.id}"
183     elsif artist
184       uri = "#{APIURL}method=artist.getevents&artist=#{CGI.escape artist.to_s}"
185       emptymsg = _("no events found by %{artist}") % {:artist => artist.to_s}
186     elsif user
187       uri = "#{APIURL}method=user.getevents&user=#{CGI.escape user}"
188       emptymsg = _("%{user} is not attending any events") % {:user => user}
189     end
190     xml = @bot.httputil.get_response(uri)
191
192     doc = Document.new xml.body
193     if xml.class == Net::HTTPInternalServerError
194       if doc.root and doc.root.attributes["status"] == "failed"
195         m.reply doc.root.elements["error"].text
196       else
197         m.reply _("could not retrieve events")
198       end
199     end
200     disp_events = Array.new
201     events = Array.new
202     doc.root.elements.each("events/event"){ |e|
203       h = {}
204       h[:title] = e.elements["title"].text
205       venue = e.elements["venue"].elements["name"].text
206       city = e.elements["venue"].elements["location"].elements["city"].text
207       country =  e.elements["venue"].elements["location"].elements["country"].text
208       h[:location] = Underline + venue + Underline + " #{Bold + city + Bold}, #{country}"
209       date = e.elements["startDate"].text.split
210       h[:date] = Time.utc(date[3].to_i, date[2], date[1].to_i)
211       h[:desc] = e.elements["description"].text
212       h[:url] = e.elements["url"].text
213       h[:attendance] = e.elements["attendance"].text.to_i
214       artists = Array.new
215       e.elements.each("artists/artist"){ |a|
216         artists << a.text
217       }
218       h[:artists] = artists
219       events << LastFmEvent.new(h)
220     }
221     if events.empty?
222       m.reply emptymsg
223       return
224     end
225     events[0...num].each { |event|
226       disp_events << event.to_s
227     }
228     m.reply disp_events.join(' | '), :split_at => /\s+\|\s+/
229
230   end
231
232   def tasteometer(m, params)
233     opts = { :cache => false }
234     user1 = resolve_username(m, params[:user1])
235     user2 = resolve_username(m, params[:user2])
236     xml = @bot.httputil.get_response("#{APIURL}method=tasteometer.compare&type1=user&type2=user&value1=#{CGI.escape user1}&value2=#{CGI.escape user2}", opts)
237     doc = Document.new xml.body
238     unless doc
239       m.reply _("last.fm parsing failed")
240       return
241     end
242     if xml.class == Net::HTTPBadRequest
243       if doc.root.elements["error"].attributes["code"] == "7" then
244         error = doc.root.elements["error"].text
245         error.match(/Invalid username: \[(.*)\]/);
246         baduser = $1
247
248         m.reply _("%{u} doesn't exist on last.fm") % {:u => baduser}
249         return
250       else
251         m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
252         return
253       end
254     end
255     score = doc.root.elements["comparison/result/score"].text.to_f
256     artists = doc.root.get_elements("comparison/result/artists/artist").map { |e| e.elements["name"].text}
257     case
258       when score >= 0.9
259         rating = _("Super")
260       when score >= 0.7
261         rating = _("Very High")
262       when score >= 0.5
263         rating = _("High")
264       when score >= 0.3
265         rating = _("Medium")
266       when score >= 0.1
267         rating = _("Low")
268       else
269         rating = _("Very Low")
270     end
271
272     common_artists = unless artists.empty?
273       _(" and music they have in common includes: %{artists}") % {
274         :artists => artists.join(", ") }
275     else
276       nil
277     end
278
279     m.reply _("%{a}'s and %{b}'s musical compatibility rating is %{bold}%{r}%{bold}%{common}") % {
280       :a => user1,
281       :b => user2,
282       :r => rating.downcase,
283       :bold => Bold,
284       :common => common_artists
285     }
286   end
287
288   def now_playing(m, params)
289     opts = { :cache => false }
290     user = resolve_username(m, params[:who])
291     xml = @bot.httputil.get_response("#{APIURL}method=user.getrecenttracks&user=#{CGI.escape user}", opts)
292     doc = Document.new xml.body
293     unless doc
294       m.reply _("last.fm parsing failed")
295       return
296     end
297     if xml.class == Net::HTTPBadRequest
298       if doc.root.elements["error"].text == "Invalid user name supplied" then
299         m.reply _("%{user} doesn't exist on last.fm, perhaps they need to: lastfm user <username>") % {
300           :user => user
301         }
302         return
303       else
304         m.reply _("error: %{e}") % {:e => doc.root.element["error"].text}
305         return
306       end
307     end
308     now = artist = track = albumtxt = date = nil
309     unless doc.root.elements[1].has_elements?
310      m.reply _("%{u} hasn't played anything recently") % {:u => user}
311      return
312     end
313     first = doc.root.elements[1].elements[1]
314     now = first.attributes["nowplaying"]
315     artist = first.elements["artist"].text
316     track = first.elements["name"].text
317     albumtxt = first.elements["album"].text
318     album = ""
319     if albumtxt
320       year = get_album(artist, albumtxt)[2]
321       album = "[#{albumtxt}, #{year}]" if year
322     end
323     past = nil
324     date = XPath.first(first, "//date")
325     if date != nil
326       time = date.attributes["uts"]
327       past = Time.at(time.to_i)
328     end
329     if now == "true"
330        verb = _("is listening to")
331        if @registry.has_key? "#{m.sourcenick}_verb_present"
332          verb = @registry["#{m.sourcenick}_verb_present"]
333        end
334        reply = _("%{u} %{v} \"%{t}\" by %{a} %{b}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album}
335     else
336       verb = _("listened to")
337        if @registry.has_key? "#{m.sourcenick}_verb_past"
338          verb = @registry["#{m.sourcenick}_verb_past"]
339        end
340       ago = Utils.timeago(past)
341       reply = _("%{u} %{v} \"%{t}\" by %{a} %{b} %{p}") % {:u => user, :v => verb, :t => track, :a => artist, :b => album, :p => ago}
342     end
343
344     reply << _("; see %{uri} for more") % { :uri => "http://www.last.fm/user/#{CGI.escape user}"}
345     m.reply reply
346   end
347
348   def find_artist(m, params)
349     info_xml = @bot.httputil.get("#{APIURL}method=artist.getinfo&artist=#{CGI.escape params[:artist].to_s}")
350     unless info_xml
351       m.reply _("I had problems getting info for %{a}") % {:a => params[:artist]}
352       return
353     end
354     info_doc = Document.new info_xml
355     unless info_doc
356       m.reply _("last.fm parsing failed")
357       return
358     end
359     tags_xml = @bot.httputil.get("#{APIURL}method=artist.gettoptags&artist=#{CGI.escape params[:artist].to_s}")
360     tags_doc = Document.new tags_xml
361
362     first = info_doc.root.elements["artist"]
363     artist = first.elements["name"].text
364     url = first.elements["url"].text
365     stats = {}
366     %w(playcount listeners).each do |e|
367       t = first.elements["stats/#{e}"].text
368       stats[e.to_sym] = t.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
369     end
370     summary = first.elements["bio"].elements["summary"].text
371     similar = first.get_elements("similar/artist").map { |a|
372       _("%{b}%{a}%{b}") % { :a => a.elements["name"].text, :b => Bold } }
373     tags = tags_doc.root.get_elements("toptags/tag")[0..4].map { |t|
374       _("%{u}%{t}%{u}") % { :t => t.elements["name"].text, :u => Underline } }
375     reply = _("%{b}%{a}%{b} <%{u}> has been played %{b}%{c}%{b} times and is being listened to by %{b}%{l}%{b} people") % {
376       :b => Bold, :a => artist, :u => url, :c => stats[:playcount], :l => stats[:listeners] }
377     reply << _(". Tagged as: %{t}") % {
378       :t => tags.join(", "), :b => Bold } unless tags.empty?
379     reply << _(". Similar artists: %{s}") % {
380       :s => similar.join(", "), :b => Bold } unless similar.empty?
381     m.reply reply
382     m.reply summary.ircify_html
383   end
384
385   def find_track(m, params)
386     track = params[:track].to_s
387     xml = @bot.httputil.get("#{APIURL}method=track.search&track=#{CGI.escape track}")
388     unless xml
389       m.reply _("I had problems getting info for %{a}") % {:a => track}
390       return
391     end
392     debug xml
393     doc = Document.new xml
394     unless doc
395       m.reply _("last.fm parsing failed")
396       return
397     end
398     debug doc.root
399     results = doc.root.elements["results/opensearch:totalResults"].text.to_i rescue 0
400     if results > 0
401       begin
402         hits = []
403         doc.root.each_element("results/trackmatches/track") do |track|
404           hits << _("%{bold}%{t}%{bold} by %{bold}%{a}%{bold} (%{n} listeners)") % {
405             :t => track.elements["name"].text,
406             :a => track.elements["artist"].text,
407             :n => track.elements["listeners"].text,
408             :bold => Bold
409           }
410         end
411         m.reply hits.join(' -- '), :split_at => ' -- '
412       rescue
413         error $!
414         m.reply _("last.fm parsing failed")
415       end
416     else
417       m.reply _("track %{a} not found") % {:a => track}
418     end
419   end
420
421   def find_venue(m, params)
422     venue  = params[:venue].to_s
423     venues = search_venue_by(:name => venue, :limit => 1)
424     venue  = venues.last
425
426     if venues.empty?
427       m.reply "sorry, can't find such venue"
428       return
429     end
430
431     reply = _("%{b}%{name}%{b}, %{street}, %{u}%{city}%{u}, %{country}, see %{url} for more info") % {
432       :u => Underline, :b => Bold, :name => venue.name, :city => venue.city, :street => venue.street,
433       :country => venue.country, :url => venue.url
434     }
435
436     if venue.street && venue.city
437       maps_uri = "http://maps.google.com/maps?q=#{venue.street},+#{venue.city}"
438       maps_uri << ",+#{venue.postal}" if venue.postal
439     elsif venue.lat && venue.long
440       maps_uri = "http://maps.google.com/maps?q=#{venue.lat},+#{venue.long}"
441     else
442       m.reply reply
443       return
444     end
445
446     maps_uri << "+(#{venue.name.gsub(" ", "%A0")})"
447
448     begin
449       require "shorturl"
450       maps_uri = ShortURL.shorten(CGI.escape(maps_uri))
451     rescue LoadError => e
452       error e
453     end
454
455     reply << _(" and %{maps} for maps") % { :maps => maps_uri, :b => Bold }
456     m.reply reply
457   end
458
459   def get_album(artist, album)
460     xml = @bot.httputil.get("#{APIURL}method=album.getinfo&artist=#{CGI.escape artist}&album=#{CGI.escape album}")
461     unless xml
462       return [_("I had problems getting album info")]
463     end
464     doc = Document.new xml
465     unless doc
466       return [_("last.fm parsing failed")]
467     end
468     album = date = playcount = artist = date = year = nil
469     first = doc.root.elements["album"]
470     artist = first.elements["artist"].text
471     playcount = first.elements["playcount"].text
472     album = first.elements["name"].text
473     date = first.elements["releasedate"].text
474     unless date.strip.length < 2
475       year = date.strip.split[2].chop
476     end
477     result = [artist, album, year, playcount]
478     return result
479   end
480
481   def find_album(m, params)
482     album = get_album(params[:artist].to_s, params[:album].to_s)
483     if album.length == 1
484       m.reply _("I couldn't locate: \"%{a}\" by %{r}") % {:a => params[:album], :r => params[:artist]}
485       return
486     end
487     year = "(#{album[2]}) " unless album[2] == nil
488     m.reply _("the album \"%{a}\" by %{r} %{y}has been played %{c} times") % {:a => album[1], :r => album[0], :y => year, :c => album[3]}
489   end
490
491   def set_user(m, params)
492     user = params[:who].to_s
493     nick = m.sourcenick
494     @registry[ nick ] = user
495     m.reply _("okay, I'll remember that %{n} is %{u} on last.fm") % {:n => nick, :u => user}
496   end
497
498   def set_verb(m, params)
499     past = params[:past].to_s
500     present = params[:present].to_s
501     key = "#{m.sourcenick}_verb_"
502     @registry[ "#{key}past" ] = past
503     @registry[ "#{key}present" ] = present
504     m.reply _("okay, I'll remember that %{n} prefers \"%{r}\" and \"%{p}\"") % {:n => m.sourcenick, :p => past, :r => present}
505   end
506
507   def get_user(m, params)
508     nick = ""
509     if params[:who]
510       nick = params[:who].to_s
511     else
512       nick = m.sourcenick
513     end
514     if @registry.has_key? nick
515       user = @registry[ nick ]
516       m.reply _("%{nick} is %{user} on last.fm") % {
517         :nick => nick,
518         :user => user
519       }
520     else
521       m.reply _("sorry, I don't know who %{n} is on last.fm, perhaps they need to: lastfm set user <username>") % {:n => nick}
522     end
523   end
524
525   def lastfm(m, params)
526     action = case params[:action]
527     when "neighbors" then "neighbours"
528     when "recentracks", "recent" then "recenttracks"
529     when "loved" then "lovedtracks"
530     when /^weekly(track|album|artist)s$/
531       "weekly#{$1}chart"
532     when "events"
533       find_events(m, params)
534       return
535     else
536       params[:action]
537     end.to_sym
538
539     if action == :shouts
540       num = params[:num] || @bot.config['lastfm.default_shouts']
541       num = num.to_i.clip(1, @bot.config['lastfm.max_shouts'])
542     else
543       num = params[:num] || @bot.config['lastfm.default_user_data']
544       num = num.to_i.clip(1, @bot.config['lastfm.max_user_data'])
545     end
546
547     user = resolve_username(m, params[:user])
548     uri = "#{APIURL}method=user.get#{action}&user=#{CGI.escape user}"
549
550     if period = params[:period]
551       period_uri = (period.last == "year" ? "12month" : period.first + "month")
552       uri << "&period=#{period_uri}"
553     end
554
555     begin
556       res = @bot.httputil.get_response(uri)
557       raise _("no response body") unless res.body
558     rescue Exception => e
559         m.reply _("I had problems accessing last.fm: %{e}") % {:e => e.message}
560         return
561     end
562     doc = Document.new(res.body)
563     unless doc
564       m.reply _("last.fm parsing failed")
565       return
566     end
567
568     case res
569     when Net::HTTPBadRequest
570       if doc.root and doc.root.attributes["status"] == "failed"
571         m.reply "error: " << doc.root.elements["error"].text.downcase
572       end
573       return
574     end
575
576     seemore =  _("; see %{uri} for more")
577     case action
578     when :friends
579       friends = doc.root.get_elements("friends/user").map do |u|
580         u.elements["name"].text
581       end
582
583       if friends.empty?
584         reply = _("%{user} has no friends :(")
585       elsif friends.length <= num
586         reply = _("%{user} has %{total} friends: %{friends}")
587       else
588         reply = _("%{user} has %{total} friends, including %{friends}%{seemore}")
589       end
590       m.reply reply % {
591         :user => user,
592         :total => friends.size,
593         :friends => friends.shuffle[0, num].join(", "),
594         :uri => "http://www.last.fm/user/#{CGI.escape user}/friends",
595         :seemore => seemore
596       }
597     when :lovedtracks
598       loved = doc.root.get_elements("lovedtracks/track").map do |track|
599         [track.elements["artist/name"].text, track.elements["name"].text].join(" - ")
600       end
601       loved_prep = loved.shuffle[0, num].to_enum(:each_with_index).collect { |e,i| (i % 2).zero? ? Underline+e+Underline : e }
602
603       if loved.empty?
604         reply = _("%{user} has not loved any tracks")
605       elsif loved.length <= num
606         reply = _("%{user} has loved %{total} tracks: %{tracks}")
607       else
608         reply = _("%{user} has loved %{total} tracks, including %{tracks}%{seemore}")
609       end
610       m.reply reply % {
611           :user => user,
612           :total => loved.size,
613           :tracks => loved_prep.join(", "),
614           :uri => "http://www.last.fm/user/#{CGI.escape user}/library/loved",
615           :seemore => seemore
616         }
617     when :neighbours
618       nbrs = doc.root.get_elements("neighbours/user").map do |u|
619         u.elements["name"].text
620       end
621
622       if nbrs.empty?
623         reply = _("no one seems to share %{user}'s musical taste")
624       elsif nbrs.length <= num
625         reply = _("%{user}'s musical neighbours are %{nbrs}")
626       else
627         reply = _("%{user}'s musical neighbours include %{nbrs}%{seemore}")
628       end
629       m.reply reply % {
630           :user    => user,
631           :nbrs    => nbrs.shuffle[0, num].join(", "),
632           :uri     => "http://www.last.fm/user/#{CGI.escape user}/neighbours",
633           :seemore => seemore
634       }
635     when :recenttracks
636       tracks = doc.root.get_elements("recenttracks/track").map do |track|
637         [track.elements["artist"].text, track.elements["name"].text].join(" - ")
638       end
639
640       counts = []
641       tracks.each do |track|
642         if t = counts.assoc(track)
643           counts[counts.rindex(t)] = [track, t[-1] += 1]
644         else
645           counts << [track, 1]
646         end
647       end
648
649       tracks_prep = counts[0, num].to_enum(:each_with_index).map do |e,i|
650         str = (i % 2).zero? ? Underline+e[0]+Underline : e[0]
651         str << " (%{i} times%{m})" % {
652           :i => e.last,
653           :m => counts.size == 1 ? _(" or more") : nil
654         } if e.last > 1
655         str
656       end
657
658       if tracks.empty?
659         m.reply _("%{user} hasn't played anything recently") % { :user => user }
660       else
661         m.reply _("%{user} has recently played %{tracks}") %
662           { :user => user, :tracks => tracks_prep.join(", ") }
663       end
664     when :shouts
665       shouts = doc.root.get_elements("shouts/shout")
666       if shouts.empty?
667         m.reply _("there are no shouts for %{user}") % { :user => user }
668       else
669         shouts[0, num].each do |shout|
670           m.reply _("<%{author}> %{body}") % {
671             :body   => shout.elements["body"].text,
672             :author => shout.elements["author"].text,
673           }
674         end
675       end
676     when :toptracks, :topalbums, :topartists, :weeklytrackchart, :weeklyalbumchart, :weeklyartistchart
677       type  = action.to_s.scan(/track|album|artist/).to_s
678       items = doc.root.get_elements("#{action}/#{type}").map do |item|
679         case action
680         when :weeklytrackchart, :weeklyalbumchart
681           format = "%{artist} - %{title} (%{bold}%{plays}%{bold})"
682           artist = item.elements["artist"].text
683         when :weeklyartistchart, :topartists
684           format = "%{artist} (%{bold}%{plays}%{bold})"
685           artist = item.elements["name"].text
686         when :toptracks, :topalbums
687           format = "%{artist} - %{title} (%{bold}%{plays}%{bold})"
688           artist = item.elements["artist/name"].text
689         end
690
691         _(format) % {
692           :artist => artist,
693           :title  => item.elements["name"].text,
694           :plays  => item.elements["playcount"].text,
695           :bold   => Bold
696         }
697       end
698       if items.empty?
699         m.reply _("%{user} hasn't played anything in this period of time") % { :user => user }
700       else
701         m.reply items[0, num].join(", ")
702       end
703     end
704   end
705
706   def resolve_username(m, name)
707     name = m.sourcenick if name.nil?
708     @registry[name] or name
709   end
710 end
711
712 plugin = LastFmPlugin.new
713 plugin.map 'lastfm [:num] event[s] in *location', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
714 plugin.map 'lastfm [:num] event[s] by *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
715 plugin.map 'lastfm [:num] event[s] at *venue', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
716 plugin.map 'lastfm [:num] event[s] [for] *who', :action => :find_events, :requirements => { :num => /\d+/ }, :thread => true
717 plugin.map 'lastfm artist *artist', :action => :find_artist, :thread => true
718 plugin.map 'lastfm album *album [by *artist]', :action => :find_album
719 plugin.map 'lastfm track *track', :action => :find_track, :thread => true
720 plugin.map 'lastfm venue *venue', :action => :find_venue, :thread => true
721 plugin.map 'lastfm set user[name] :who', :action => :set_user, :thread => true
722 plugin.map 'lastfm set verb *present, *past', :action => :set_verb, :thread => true
723 plugin.map 'lastfm who [:who]', :action => :get_user, :thread => true
724 plugin.map 'lastfm compare to :user2', :action => :tasteometer, :thread => true
725 plugin.map 'lastfm compare [:user1] [to] :user2', :action => :tasteometer, :thread => true
726 plugin.map "lastfm [user] [:num] :action [:user]", :thread => true,
727   :requirements => {
728     :action => /^(?:events|shouts|friends|neighbou?rs|loved(?:tracks)?|recent(?:t?racks)?|top(?:album|artist|track)s?|weekly(?:albums?|artists?|tracks?)(?:chart)?)$/,
729     :num => /^\d+$/
730 }
731 plugin.map 'lastfm [user] [:num] :action [:user] over [*period]', :thread => true,
732   :requirements => {
733     :action => /^(?:top(?:album|artist|track)s?)$/,
734     :period => /^(?:(?:3|6|12) months)|(?:a\s|1\s)?year$/,
735     :num => /^\d+$/
736 }
737 plugin.map 'lastfm [now] [:who]', :action => :now_playing, :thread => true
738 plugin.map 'np [:who]', :action => :now_playing, :thread => true