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