]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/lib_spotify.rb
[core] unicode plugin that sets server encoding
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / lib_spotify.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: spotify library used at least in spotify and lastfm plugins
5 #
6 # Author:: Raine Virta <raine.virta@gmail.com>
7 #
8 # Copyright:: (C) 2009 Raine Virta
9 #
10 # License:: GPL v2
11
12 require 'rexml/document'
13 require 'cgi'
14
15 module ::Spotify
16   class SpotifyObject
17     def initialize(xml)
18       @spotify_id = xml.attributes["href"]
19     end
20
21     def url
22       id = @spotify_id[@spotify_id.rindex(':')+1..-1]
23       method = self.class.to_s.split('::').last.downcase
24       return "http://open.spotify.com/#{method}/#{id}"
25     end
26   end
27
28   class Album < SpotifyObject
29     attr_reader :name, :released, :artist
30
31     def initialize(xml)
32       super
33       @name = xml.elements["name"].text
34       if e = xml.elements["artist"]
35         @artist = Artist.new(xml.elements["artist"])
36       end
37       if e = xml.elements["released"]
38         @released = e.text.to_i
39       end
40     end
41   end
42
43   class Artist < SpotifyObject
44     attr_reader :name
45
46     def initialize(xml)
47       super
48       @name = xml.elements["name"].text
49     end
50   end
51
52   class Track < SpotifyObject
53     attr_reader :name, :artist, :album, :track_number
54
55     def initialize(xml)
56       super
57       @name = xml.elements["name"].text
58       @artist = Artist.new(xml.elements["artist"])
59       @album = Album.new(xml.elements["album"])
60       @track_number = xml.elements["track-number"].text.to_i
61       @length = xml.elements["length"].text.to_f
62     end
63
64     def to_s
65       str = "#{artist.name} – #{name} [#{album.name}"
66       str << ", #{album.released}" if album.released
67       str << "]"
68     end
69   end
70
71   def self.get(service, method, query, page=1)
72     query.tr!('-','')
73     url = "http://ws.spotify.com/#{service}/1/#{method}?q=#{CGI.escape(query)}&page=#{page}"
74     xml = Irc::Utils.bot.httputil.get(url)
75     raise unless xml
76     return REXML::Document.new(xml).root
77   end
78
79   def self.search(method, query, page=1)
80     doc = get(:search, method, query, page)
81     return nil if doc.elements["opensearch:totalResults"].text.to_i.zero?
82     return Spotify.const_get(method.to_s.capitalize).new(doc.elements[method.to_s])
83   end
84 end