Class: Scrobbler::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/scrobbler/base.rb

Direct Known Subclasses

Authentication, BaseXml, Geo, Library, Radio, Track, Venue

Constant Summary

@@cache =

By default, there is no cache

[]

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (void) add_cache(cache)

This method returns an undefined value.

Add a cache provider to the caching system

Parameters:

  • cache (CacheProvider)

    A instance of a cache provider.



28
29
30
# File 'lib/scrobbler/base.rb', line 28

def Base.add_cache(cache)
  @@cache << cache
end

+ (void) api_key=(api_key)

This method returns an undefined value.

Set the default API key.

This key will be used by all Scrobbler classes and objects.

Parameters:

  • api_key (String)

    The default API key.



38
39
40
# File 'lib/scrobbler/base.rb', line 38

def Base.api_key=(api_key)
  @@api_key = api_key
end

+ (String) fetch_http(request_method, paramlist)

Fetch a http answer for the given request

Parameters:

  • request_method (String)

    The HTTP verb for the request type

  • paramlist (Array<String>)

    The URL(-query) parameters

Returns:

  • (String)

    The plain response from the Last.fm API



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/scrobbler/base.rb', line 129

def Base.fetch_http(request_method, paramlist)
  url = URI.join(API_URL, "/2.0/?#{paramlist.join('&')}")
  case request_method.downcase
    when "get"
      req = Net::HTTP::Get.new(url.request_uri)
    when "post"
      req = Net::HTTP::Post.new(url.request_uri)
  end
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = (url.port == 443)
  xml = http.start() do |conn|
    conn.request(req)
  end
  xml.body
end

+ (Array<Scrobbler::Base>) get(api_method, parent, element, parameters = {})

Initiate a API and parse it.

Parameters:

  • api_method (String, Symbol)

    The API method to call.

  • parent (String, Symbol)

    The parent node to inspect.

  • element (Class, String, Symbol)

    The name of the node to turn into objects.

  • parameters (Hash<String,Symbol>) (defaults to: {})

    The parameters for the method call.

Returns:



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/scrobbler/base.rb', line 67

def Base.get(api_method, parent, element, parameters = {})
  scrobbler_class = element
  element = element.to_s.sub("Scrobbler::","").downcase
  doc = request(api_method, parameters)
  elements = []
  doc.root.children.each do |child|
      next unless child.name == parent.to_s
      child.children.each do |child2|
          next unless child2.name == element
          begin
            elements << scrobbler_class.new_from_libxml(child2)
          rescue
            # Sadly last.fm does not always return valid Elements
            # @todo Try to make the best out of it
          end
      end
  end unless doc.root.nil? || doc.root.children.nil?
  elements
end

+ (String) load_from_cache(parameters)

Load a request from cache if possible

Parameters:

  • parameters (Hash)

    The parameters passed as URL params.

Returns:

  • (String)


100
101
102
103
104
105
106
107
108
109
# File 'lib/scrobbler/base.rb', line 100

def Base.load_from_cache(parameters)
  found = nil
  @@cache.each do |cache|
    if cache.has?(parameters)
      found = cache.get(parameters)
      break
    end
  end
  found
end

+ (LibXML::XML::Document) post_request(api_method, parameters = {})

Execute a request to the Audioscrobbler webservice

Parameters:

  • api_method (String, Symbol)

    The method which shall be called.

  • parameter (Hash)

    The parameters passed as URL params.

Returns:

  • (LibXML::XML::Document)


92
93
94
# File 'lib/scrobbler/base.rb', line 92

def Base.post_request(api_method, parameters = {})
  Base.request(api_method, parameters, 'post')
end

+ (LibXML::XML::Document) request(api_method, parameters = {}, request_method = 'get')

Execute a request to the Audioscrobbler webservice

Parameters:

  • api_method (String, Symbol)

    The method which shall be called.

  • parameter (Hash)

    The parameters passed as URL params.

  • request_method (String) (defaults to: 'get')

    The HTTP verb to be used.

Returns:

  • (LibXML::XML::Document)

Raises:

  • (ArgumentError)


151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/scrobbler/base.rb', line 151

def Base.request(api_method, parameters = {}, request_method = 'get')
  raise ArgumentError unless [String, Symbol].member?(api_method.class)
  raise ArgumentError unless parameters.kind_of?(Hash)

  parameters = {:signed => false}.merge(parameters)
  parameters['api_key'] = @@api_key
  parameters['method'] = api_method.to_s
  check_cache = false
  paramlist = []
  # Check if we want a signed call and pop :signed
  if parameters.delete :signed
    #1: Sort alphabetically
    params = parameters.sort{|a,b| a.at(0).to_s<=>b.at(0).to_s}
    #2: concat them into one string
    str = params.join('')
    #3: Append secret
    str = str + @@secret
    #4: Make a md5 hash
    md5 = Digest::MD5.hexdigest(str)
    params << [:api_sig, md5]
    params.each do |a|
      paramlist << "#{sanitize(a.at(0))}=#{sanitize(a.at(1))}"
    end
  else
    if request_method == 'get' then
      check_cache = true
    end
    parameters.each do |key, value|
      paramlist << "#{sanitize(key)}=#{sanitize(value)}"
    end
  end

  xml = nil
  # Check if we could read from cache
  xml = load_from_cache(parameters) if check_cache
  # Fetch the http answer if cache was empty
  xml = fetch_http(request_method, paramlist) if xml.nil?
  # Process it
  doc = Nokogiri::XML(xml) { |config| config.noent.noblanks.nonet }
  # Validate it
  validate_response_document doc
  # Write to cache
  save_to_cache(xml, parameters) if check_cache

  # Return the parsed result
  doc
end

+ (String) sanitize(param)

Clean up a URL parameter.

Parameters:

  • param (String, Symbol)

    The parameter which needs cleanup.

Returns:

  • (String)


56
57
58
# File 'lib/scrobbler/base.rb', line 56

def Base.sanitize(param)
  URI.escape(param.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
end

+ (void) save_to_cache(xml, parameters)

This method returns an undefined value.

Save a request answer to all caches that would store it.

Parameters:

  • xml (String)

    The answer from the Last.fm API

  • parameters (Hash)

    The parameters passed as URL params.



116
117
118
119
120
121
122
# File 'lib/scrobbler/base.rb', line 116

def Base.save_to_cache(xml, parameters)
  @@cache.each do |cache|
    if cache.writable? then
      cache.set(xml, parameters)
    end
  end
end

+ (void) secret=(secret)

This method returns an undefined value.

Set the default API secret.

This secret will be used by all Scrobbler classes and objects.

Parameters:

  • secret (String)

    The default API secret.



48
49
50
# File 'lib/scrobbler/base.rb', line 48

def Base.secret=(secret)
  @@secret = secret
end

+ (void) validate_response_document(document)

This method returns an undefined value.

Check response status, raise ApiError if request failed.

Parameters:

  • document (Nokogiri::XML::Document)

    Response XML document.



203
204
205
206
207
208
# File 'lib/scrobbler/base.rb', line 203

def Base.validate_response_document(document)
  unless document.root and document.root['status'] == 'ok'
    error_message = (document.content if document.root.child.name == 'error') rescue "Erroneous documents received"
    raise ApiError, error_message
  end
end

Instance Method Details

- (Array) call(api_method, parent, element, params)

Call a API method

Parameters:

  • api_method (String, Symbol)

    The method which shall be called.

  • params (Hash)

    The parameters passed as URL params.

  • parent (String, Symbol)

    the parent XML node to look for.

  • element (Class, String, Symbol)

    The xml node name which shall be converted into an object.

Returns:

  • (Array)


276
277
278
# File 'lib/scrobbler/base.rb', line 276

def call(api_method, parent, element, params)
  Base.get(api_method, parent, element, params)
end

- (Array) call_pageable(method, parent, element, options = {})

Generic request method for the most Library funtions

Parameters:

  • api_method (String, Symbol)

    The method which shall be called.

  • options (Hash) (defaults to: {})

    The parameters passed as URL params.

  • parent (String, Symbol)

    the parent XML node to look for.

  • element (Class)

    The xml node name which shall be converted into an object.

Returns:

  • (Array)


237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/scrobbler/base.rb', line 237

def call_pageable(method, parent, element, options={})
  options = {:all => true}.merge options
  result = []
  if options.delete(:all)
    doc = Base.request(method, options.merge(:page => 1))
    root = nil
    doc.root.children.each do |child|
      next unless child.name == parent.to_s
      root = child
    end unless doc.nil? || doc.root.nil?
    if root.nil? then
      # Sometimes Last.fm returns an empty file if we query for sth not known
      return []
    end
    #return nil if root.nil? # Sometimes Last.fm returns an empty XML file if there were no artists
    total_pages = root['totalPages'].to_i
    root.children.each do |child|
      next unless child.name == element.to_s.sub("Scrobbler::","").downcase
      result << element.new_from_libxml(child)
    end
    (2..total_pages).each do |i|
      options[:page] = i
      result.concat call(method, parent, element, options)
    end
  else
    result = call(method, parent, element, options)
  end
  result
end

- (void) populate_data(data = {})

This method returns an undefined value.

Load information into instance variables.

Parameters:

  • data (Hash<String,Symbol>) (defaults to: {})

    Each entry will be stored as a variable.



214
215
216
217
218
# File 'lib/scrobbler/base.rb', line 214

def populate_data(data = {})
  data.each do |key, value|
    instance_variable_set("@#{key.to_s}", value)
  end
end

- (LibXML::XML::Document) request(api_method, parameters = {}, request_method = 'get')

Execute a request to the Audioscrobbler webservice

Parameters:

  • api_method (String, Symbol)

    The method which shall be called.

  • parameter (Hash)

    The parameters passed as URL params.

Returns:

  • (LibXML::XML::Document)


225
226
227
# File 'lib/scrobbler/base.rb', line 225

def request(api_method, parameters = {}, request_method = 'get')
  Base.request(api_method, parameters, request_method)
end