Class: DuckSearch::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/duck_search/client.rb

Constant Summary collapse

BASE_URL =
"https://html.duckduckgo.com"
SEARCH_PATH =
"/html"
DEFAULT_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
RESULT_CAP =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(proxy: nil, timeout: 15, open_timeout: 10, user_agent: DEFAULT_USER_AGENT) ⇒ Client

Returns a new instance of Client.



14
15
16
17
18
19
# File 'lib/duck_search/client.rb', line 14

def initialize(proxy: nil, timeout: 15, open_timeout: 10, user_agent: DEFAULT_USER_AGENT)
  @proxy = proxy
  @timeout = timeout
  @open_timeout = open_timeout
  @user_agent = user_agent
end

Instance Attribute Details

#open_timeoutObject (readonly)

Returns the value of attribute open_timeout.



12
13
14
# File 'lib/duck_search/client.rb', line 12

def open_timeout
  @open_timeout
end

#proxyObject (readonly)

Returns the value of attribute proxy.



12
13
14
# File 'lib/duck_search/client.rb', line 12

def proxy
  @proxy
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



12
13
14
# File 'lib/duck_search/client.rb', line 12

def timeout
  @timeout
end

#user_agentObject (readonly)

Returns the value of attribute user_agent.



12
13
14
# File 'lib/duck_search/client.rb', line 12

def user_agent
  @user_agent
end

Instance Method Details

#search(query) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/duck_search/client.rb', line 21

def search(query)
  response = connection.post(SEARCH_PATH) do |req|
    req.headers["User-Agent"] = user_agent
    req.headers["DNT"] = "1"
    req.headers["Content-Type"] = "application/x-www-form-urlencoded"
    req.body = URI.encode_www_form(
      q: query,
      b: "",
      kf: "-1",
      kh: "1",
      kp: "1",
      k1: "-1"
    )
  end

  raise HttpError.new("DuckDuckGo returned HTTP #{response.status}",
                       status: response.status,
                       url: "#{BASE_URL}#{SEARCH_PATH}") unless response.success?

  parse_html(response.body)
rescue Faraday::Error => e
  raise HttpError.new("DuckDuckGo connection failed: #{e.message}",
                       url: "#{BASE_URL}#{SEARCH_PATH}")
end