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
63
64
|
# File 'lib/searchlink/searches/google.rb', line 30
def search(search_type, search_terms, link_text)
image = search_type =~ /img$/ ? true : false
unless api_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
|