2012-07-04 13:10:47 +00:00
|
|
|
# -*- encoding: utf-8 -*-
|
2012-07-08 22:37:46 +00:00
|
|
|
|
2012-07-04 13:10:47 +00:00
|
|
|
module MusicBrainz
|
|
|
|
module Tools
|
|
|
|
class Proxy
|
2012-07-08 22:37:46 +00:00
|
|
|
class << self
|
|
|
|
@@last_query_time = 0
|
|
|
|
|
2012-09-23 11:25:52 +00:00
|
|
|
def config
|
|
|
|
MusicBrainz.config
|
2012-07-08 22:37:46 +00:00
|
|
|
end
|
|
|
|
|
2012-09-23 11:25:52 +00:00
|
|
|
def query_interval=(sec)
|
|
|
|
config.query_interval = sec.to_f
|
2012-07-08 22:37:46 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def tries_limit=(num)
|
2012-09-23 11:25:52 +00:00
|
|
|
config.tries_limit = num.to_i
|
2012-07-08 22:37:46 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def query(params = {})
|
2012-09-23 11:25:52 +00:00
|
|
|
url = config.web_service_url + params[:resource].to_s.gsub('_', '-') + '/' + (params[:id].to_s || '')
|
2012-07-08 22:37:46 +00:00
|
|
|
params.delete(:resource)
|
|
|
|
params.delete(:id) unless params[:id].nil?
|
|
|
|
url << '?' + params.map{ |k, v|
|
|
|
|
k = k.to_s.gsub('_', '-')
|
|
|
|
v = (v.is_a?(Array) ? v.map{ |_| _.to_s.gsub('_', '-') }.join('+') : v.to_s)
|
|
|
|
k + '=' + v
|
|
|
|
}.join('&') unless params.empty?
|
|
|
|
MusicBrainz::Tools::Cache.cache_contents(url) {
|
|
|
|
get_contents url
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_contents(url)
|
|
|
|
response = nil
|
|
|
|
|
2012-09-23 11:25:52 +00:00
|
|
|
config.tries_limit.times {
|
2012-07-08 22:37:46 +00:00
|
|
|
time_passed = Time.now.to_f - @@last_query_time
|
2012-09-23 11:25:52 +00:00
|
|
|
sleep(config.query_interval - time_passed) if time_passed < config.query_interval
|
2012-07-08 22:37:46 +00:00
|
|
|
|
|
|
|
begin
|
2012-09-23 11:25:52 +00:00
|
|
|
response = open(url, "User-Agent" => config.user_agent)
|
2012-07-08 22:37:46 +00:00
|
|
|
@@last_query_time = Time.now.to_f
|
|
|
|
rescue => e
|
|
|
|
response = nil if e.io.status[0].to_i == 404
|
|
|
|
end
|
|
|
|
|
|
|
|
break unless response.nil?
|
|
|
|
}
|
|
|
|
|
|
|
|
response
|
|
|
|
end
|
2012-07-04 13:10:47 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|