1
0
Fork 0

Merge pull request #7 from blakink/master

Allow custom user_agent
This commit is contained in:
Gregory Eremin 2012-10-05 02:03:33 -07:00
commit 3bf68d152e
3 changed files with 64 additions and 14 deletions

View File

@ -19,6 +19,7 @@ require "musicbrainz/release_group"
require "musicbrainz/release"
require "musicbrainz/track"
require "tools/configuration"
require "tools/cache"
require "tools/proxy"

View File

@ -0,0 +1,54 @@
# -*- encoding: utf-8 -*-
module MusicBrainz
def self.configure
yield @config ||= MusicBrainz::Tools::Configuration.new
end
def self.config
@config
end
module Tools
class Configuration
def self.add_config name, value=nil
self.instance_variable_set "@#{name}", value
class_eval <<-RUBY
def #{name}=(value)
@#{name} = value
end
def #{name}
@#{name} || self.class.instance_variable_get('@#{name}')
end
RUBY
end
DEFAULT_USER_AGENT = "gem musicbrainz (https://github.com/magnolia-fan/musicbrainz) @ " + Socket.gethostname
add_config :application
add_config :version
add_config :contact
add_config :query_interval, 1.5
add_config :tries_limit, 5
add_config :web_service_url, "http://musicbrainz.org/ws/2/"
def user_agent
return @user_agent if @user_agent
if application
@user_agent = application
@user_agent << "/#{version}" if version
@user_agent << " (#{contact})" if contact
@user_agent << ' via '
end
@user_agent = "#{@user_agent}#{DEFAULT_USER_AGENT}"
end
end
end
end

View File

@ -5,26 +5,21 @@ module MusicBrainz
class Proxy
class << self
@@last_query_time = 0
@@query_interval = 1.5 # Min: 1.0 Safe: 1.5
@@tries_limit = 5
WEB_SERVICE_URL = 'http://musicbrainz.org/ws/2/'
USER_AGENT = "gem musicbrainz (https://github.com/magnolia-fan/musicbrainz) @ " + Socket.gethostname
def query_interval=(sec)
@@query_interval = sec.to_f
def config
MusicBrainz.config
end
def query_interval
@@query_interval
def query_interval=(sec)
config.query_interval = sec.to_f
end
def tries_limit=(num)
@@tries_limit = num.to_i
config.tries_limit = num.to_i
end
def query(params = {})
url = WEB_SERVICE_URL + params[:resource].to_s.gsub('_', '-') + '/' + (params[:id].to_s || '')
url = config.web_service_url + params[:resource].to_s.gsub('_', '-') + '/' + (params[:id].to_s || '')
params.delete(:resource)
params.delete(:id) unless params[:id].nil?
url << '?' + params.map{ |k, v|
@ -40,12 +35,12 @@ module MusicBrainz
def get_contents(url)
response = nil
@@tries_limit.times {
config.tries_limit.times {
time_passed = Time.now.to_f - @@last_query_time
sleep(@@query_interval - time_passed) if time_passed < @@query_interval
sleep(config.query_interval - time_passed) if time_passed < config.query_interval
begin
response = open(url, "User-Agent" => USER_AGENT)
response = open(url, "User-Agent" => config.user_agent)
@@last_query_time = Time.now.to_f
rescue => e
response = nil if e.io.status[0].to_i == 404