1
0
Fork 0
robbie/lib/robbie/parsers/base_parser.rb

78 lines
2.5 KiB
Ruby
Raw Normal View History

2012-08-26 04:09:00 +00:00
module Robbie
module Parsers
class BaseParser
include HTTParty
base_uri "api.rovicorp.com"
format :json
2012-09-18 22:42:20 +00:00
@@meta_calls = []
@@autocomplete_calls = []
2012-08-26 04:09:00 +00:00
class << self
2012-09-18 22:42:20 +00:00
def sig(type = :meta)
case type
when :meta
Digest::MD5.hexdigest("#{META_API_KEY}#{META_API_SECRET}#{Time.now.to_i}")
when :autocomplete
Digest::MD5.hexdigest("#{AUTOCOMPLETE_API_KEY}#{AUTOCOMPLETE_API_SECRET}#{Time.now.to_i}")
end
2012-08-26 04:09:00 +00:00
end
def query(path, params)
2012-09-18 22:42:20 +00:00
type = (path.match(/^\/search\/v2\/music\/autocomplete/) ? :autocomplete : :meta)
if type == :meta
unless Robbie.const_defined?(:META_API_KEY) and Robbie.const_defined?(:META_API_SECRET)
raise Exception.new("No meta API credentials given")
end
elsif type == :autocomplete
unless Robbie.const_defined?(:AUTOCOMPLETE_API_KEY) and Robbie.const_defined?(:AUTOCOMPLETE_API_SECRET)
raise Exception.new("No autocomplete API credentials given")
end
2012-08-26 04:09:00 +00:00
end
params_str = params
2012-09-18 22:42:20 +00:00
.merge({ apikey: (type == :meta ? META_API_KEY : AUTOCOMPLETE_API_KEY), sig: sig(type), format: "json" })
2012-08-26 04:09:00 +00:00
.map{ |key, val| "#{key}=#{val}" }.join("&")
if Robbie.cache_enabled?
cache_key = "#{path}?#{params.inspect}".scan(/\w/).join
cache_file = File.expand_path("../../../../tmp/cache/#{cache_key}", __FILE__)
if File.exist?(cache_file)
MultiJson.load(File.open(cache_file).read)
else
2012-08-26 14:07:37 +00:00
data = load("#{path}?#{params_str}")
2012-08-26 04:09:00 +00:00
File.open(cache_file, "w") do |file|
file.write(MultiJson.dump(data)) unless data.nil? or data.empty?
end
data
end
else
2012-08-26 14:07:37 +00:00
load("#{path}?#{params_str}")
2012-08-26 04:09:00 +00:00
end
end
2012-08-26 14:07:37 +00:00
2012-09-18 22:42:20 +00:00
def load(type = :meta, uri)
if type == :meta
calls = @@meta_calls
limit = 5
elsif type == :autocomplete
calls = @@autocomplete_calls
limit = 10
end
2012-08-26 14:07:37 +00:00
if Robbie.free_limits?
2012-09-18 22:42:20 +00:00
calls = calls.length > limit ? calls.slice(-limit, limit) : calls
if calls.length > limit && Time.now.to_f - calls.first <= 1.0
sleep(1.05 - (Time.now.to_f - calls.first))
2012-08-26 14:07:37 +00:00
end
2012-09-18 22:42:20 +00:00
calls << Time.now.to_f
2012-08-26 14:07:37 +00:00
end
get(uri)
end
2012-08-26 04:09:00 +00:00
end
end
end
end