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