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