Class: SL::GoogleSearch

Inherits:
Object
  • Object
show all
Defined in:
lib/searchlink/searches/google.rb

Overview

Google Search

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.api_keyObject (readonly)

Returns the value of attribute api_key.



7
8
9
# File 'lib/searchlink/searches/google.rb', line 7

def api_key
  @api_key
end

Class Method Details

.api_key?Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
26
27
28
# File 'lib/searchlink/searches/google.rb', line 19

def api_key?
  return false unless SL.config.key?("google_api_key") && SL.config["google_api_key"]

  key = SL.config["google_api_key"]
  return false if key =~ /^(x{4,})?$/i

  @api_key = key

  true
end

.search(search_type, search_terms, link_text) ⇒ Object



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

.settingsObject



9
10
11
12
13
14
15
16
17
# File 'lib/searchlink/searches/google.rb', line 9

def settings
  {
    trigger: "(g(oo)?g(le?)?|img)",
    searches: [
      ["gg", "Google Search"],
      ["img", "First image from result"]
    ]
  }
end