Method: SL::GoogleSearch.search

Defined in:
lib/searchlink/searches/google.rb

.search(search_type, search_terms, link_text) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/searchlink/searches/google.rb', line 28

def search(search_type, search_terms, link_text)
  image = search_type =~ /img$/ ? true : false

  unless test_for_key
    SL.add_error('api key', 'Missing Google API Key')
    return false
  end

  url = "https://customsearch.googleapis.com/customsearch/v1?cx=338419ee5ac894523&q=#{ERB::Util.url_encode(search_terms)}&num=1&key=#{@api_key}"
  json = Curl::Json.new(url).json

  if json['error'] && json['error']['code'].to_i == 429
    SL.notify('api limit', 'Google API limit reached, defaulting to DuckDuckGo')
    return SL.ddg(terms, link_text, google: false, image: image)
  end

  unless json['queries']['request'][0]['totalResults'].to_i.positive?
    SL.notify('no results', 'Google returned no results, defaulting to DuckDuckGo')
    return SL.ddg(terms, link_text, google: false, image: image)
  end

  result = json['items'][0]
  return false if result.nil?

  output_url = result['link']
  output_title = result['title']
  output_title.remove_seo!(output_url) if SL.config['remove_seo']

  output_url = SL.first_image if search_type =~ /img$/

  [output_url, output_title, link_text]
rescue StandardError
  SL.notify('Google error', 'Error fetching Google results, switching to DuckDuckGo')
  SL.ddg(search_terms, link_text, google: false, image: image)
end