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