Class: MajesticSeo::Api::Client

Inherits:
Object
  • Object
show all
Includes:
Logger
Defined in:
lib/majestic_seo/api/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logger

#log

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



45
46
47
48
49
50
51
52
53
54
# File 'lib/majestic_seo/api/client.rb', line 45

def initialize(options = {})
	set_config

	@api_key            =   options.fetch(:api_key,     self.config.fetch("api_key", nil))
	@environment        =   options.fetch(:environment, self.config.fetch("environment", :sandbox)).to_sym
	@verbose            =   options.fetch(:verbose,     false)

	set_api_url
	set_connection
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def api_key
  @api_key
end

#api_urlObject

Returns the value of attribute api_url.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def api_url
  @api_url
end

#configObject

Returns the value of attribute config.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def config
  @config
end

#connectionObject

Returns the value of attribute connection.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def connection
  @connection
end

#environmentObject

Returns the value of attribute environment.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def environment
  @environment
end

#verboseObject

Returns the value of attribute verbose.



42
43
44
# File 'lib/majestic_seo/api/client.rb', line 42

def verbose
  @verbose
end

Instance Method Details

#execute_command(name, parameters = {}, options = {}) ⇒ Object

This method will execute the specified command as an api request. ‘name’ is the name of the command you wish to execute, e.g. GetIndexItemInfo ‘parameters’ a hash containing the command parameters. ‘timeout’ specifies the amount of time to wait before aborting the transaction. This defaults to 5 seconds.



121
122
123
124
# File 'lib/majestic_seo/api/client.rb', line 121

def execute_command(name, parameters = {}, options = {})
	request_parameters = parameters.merge({"app_api_key" => @api_key, "cmd" => name})
	self.execute_request(request_parameters, options)
end

#execute_open_app_request(command_name, access_token, parameters = {}, options = {}) ⇒ Object

This will execute the specified command as an OpenApp request. ‘command_name’ is the name of the command you wish to execute, e.g. GetIndexItemInfo ‘parameters’ a hash containing the command parameters. ‘access_token’ the token provided by the user to access their resources. ‘timeout’ specifies the amount of time to wait before aborting the transaction. This defaults to 5 seconds.



131
132
133
134
# File 'lib/majestic_seo/api/client.rb', line 131

def execute_open_app_request(command_name, access_token, parameters = {}, options = {})
	request_parameters = parameters.merge({"accesstoken" => access_token, "cmd" => command_name, "privatekey" => @api_key})
	self.execute_request(request_parameters, options)
end

#execute_request(parameters = {}, options = {}, retries = 3) ⇒ Object

‘parameters’ a hash containing the command parameters. ‘options’ a hash containing command/call options (timeout, proxy settings etc)



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/majestic_seo/api/client.rb', line 138

def execute_request(parameters = {}, options = {}, retries = 3)
   response        =   nil
   timeout         =   options.delete(:timeout)      { |opt| 60 }
   open_timeout    =   options.delete(:open_timeout) { |opt| 60 }
   
   begin
     log(:info, "[MajesticSeo::Api::Client] - Sending API Request to Majestic SEO. Parameters: #{parameters.inspect}. Options: #{options.inspect}")
     
     response      =   @connection.get do |request|
       request.params                    =   parameters  if (!parameters.empty?)
       request.options                   =   options     if (!options.empty?)
       request.options[:timeout]         =   timeout
       request.options[:open_timeout]    =   open_timeout
     end
   
   rescue StandardError => e
     log(:error, "[MajesticSeo::Api::Client] - Error occurred while trying to perform API-call with parameters: #{parameters.inspect}. Error Class: #{e.class.name}. Error Message: #{e.message}. Stacktrace: #{e.backtrace.join("\n")}")
     retries -= 1
     
     if retries > 0
       retry
     else
       raise e
     end
   end

	return response
end

#get_index_item_info(urls, parameters = {}, options = {}) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/majestic_seo/api/client.rb', line 84

def get_index_item_info(urls, parameters = {}, options = {})
  request_parameters                    =   {}
  request_parameters['datasource']      =   parameters.fetch(:data_source, "historic")
   request_parameters["items"]           =   urls.size

   urls.each_with_index do |url, index|
     request_parameters["item#{index}"]  =   url
   end

   response    =   self.execute_command("GetIndexItemInfo", request_parameters, options)
   response    =   MajesticSeo::Api::ItemInfoResponse.new(response)

   return response
end


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/majestic_seo/api/client.rb', line 99

def get_top_back_links(url, parameters = {}, options = {})
   request_parameters                                  =     {}
   request_parameters['datasource']                    =     parameters.fetch(:data_source, "historic")
   request_parameters['URL']                           =     url
   request_parameters["MaxSourceURLs"]                 =     parameters.fetch(:max_source_urls, 100)
   request_parameters["ShowDomainInfo"]                =     parameters.fetch(:show_domain_info, 0)
   request_parameters["GetUrlData"]                    =     parameters.fetch(:get_url_data, 1)
   request_parameters["GetSubDomainData"]              =     parameters.fetch(:get_sub_domain_data, 0)
   request_parameters["GetRootDomainData"]             =     parameters.fetch(:get_root_domain_data, 0)
   request_parameters["MaxSourceURLsPerRefDomain"]     =     parameters.fetch(:max_source_urls_per_ref_domain, -1)
   request_parameters["DebugForceQueue"]               =     parameters.fetch(:debug_force_queue, 0)

   response    =   self.execute_command("GetTopBackLinks", request_parameters, options)
   response    =   MajesticSeo::Api::TopBackLinksResponse.new(response)

   return response
end

#set_api_url(format = :xml) ⇒ Object

TODO: Switch to the JSON API



66
67
68
69
70
71
72
73
# File 'lib/majestic_seo/api/client.rb', line 66

def set_api_url(format = :xml)
  @api_url      =   case @environment.to_sym
    when :sandbox     then "http://developer.majestic.com/api/#{format}"
    when :production  then "http://api.majestic.com/api/#{format}"
    else
      "http://developer.majestic.com/api/#{format}"
  end
end

#set_configObject



56
57
58
59
60
61
62
63
# File 'lib/majestic_seo/api/client.rb', line 56

def set_config
  env           = (defined?(Rails) && Rails.respond_to?(:env)) ? Rails.env : (ENV["RACK_ENV"] || 'development')

  self.config   = YAML.load_file(File.join(Rails.root, "config/majestic_seo.yml"))[env] rescue nil
   self.config ||= YAML.load_file(File.join(File.dirname(__FILE__), "../../generators/templates/majestic_seo.yml"))[env] rescue nil
   self.config ||= YAML.load_file(File.join(File.dirname(__FILE__), "../../generators/templates/majestic_seo.template.yml"))[env] rescue nil
   self.config ||= {}
end

#set_connectionObject



75
76
77
78
79
80
81
82
# File 'lib/majestic_seo/api/client.rb', line 75

def set_connection
  @connection = Faraday.new(url: @api_url, ssl: {verify: false}) do |builder|
     builder.request   :url_encoded
     builder.request   :retry
     builder.response  :logger if (@verbose)
     builder.adapter   :net_http
   end
end