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