class PatchFinder::Engine::MSU::Google

Constants

GOOGLEAPIS

Attributes

api_key[R]
search_engine_id[R]

Public Class Methods

new(opts = {}) click to toggle source

Initializes the Google API client.

@param opts [Hash] @option opts [String] :api_key Google API key. @option opts [String] :search_engine_id Google Search engine ID.

# File lib/patch_finder/engine/msu/google.rb, line 30
def initialize(opts = {})
  @api_key = opts[:api_key]
  @search_engine_id = opts[:search_engine_id]
end

Public Instance Methods

find_msb_numbers(keyword) click to toggle source

Returns the MSB (advisories) numbers for a search keyword.

@param keyword [String] @return [Array]

# File lib/patch_finder/engine/msu/google.rb, line 39
def find_msb_numbers(keyword)
  msb_numbers = []
  next_starting_index = 1
  search_opts = {
    keyword: keyword,
    starting_index: next_starting_index
  }

  begin
    while
      results = search(search_opts)
      items = results['items']
      items.each do |item|
        title = item['title']
        msb = title.scan(/Microsoft Security Bulletin (MS\d\d\-\d\d\d)/).flatten.first
        msb_numbers << msb.downcase if msb
      end

      next_starting_index = get_next_index(results)
      next_page = results['queries']['nextPage']

      # Google API Documentation:
      # https://developers.google.com/custom-search/json-api/v1/using_rest
      # "This role is not present if the current results are the last page.
      # Note: This API returns up to the first 100 results only."
      break if next_page.nil? || next_starting_index > 100
    end
  rescue GoogleClientException => e
    print_verbose_error(e.message)
    return msb_numbers.uniq
  end

  msb_numbers.uniq
end
get_next_index(j) click to toggle source

Returns startIndex

@param j [Hash] JSON response. @return [Fixnum]

# File lib/patch_finder/engine/msu/google.rb, line 134
def get_next_index(j)
  j['queries']['nextPage'] ? j['queries']['nextPage'].first['startIndex'] : 0
end
get_total_results(j) click to toggle source

Returns totalResults

@param j [Hash] JSON response. @return [Fixnum]

# File lib/patch_finder/engine/msu/google.rb, line 126
def get_total_results(j)
  j['queries']['request'].first['totalResults'].to_i
end
parse_results(res) click to toggle source

Returns the string data to JSON.

@raise [GoogleClientException] The Google Search API returns an error. @param res [Net::HTTPResponse]

# File lib/patch_finder/engine/msu/google.rb, line 110
def parse_results(res)
  j = JSON.parse(res.body)

  if j['error']
    message = j['error']['errors'].first['message']
    reason  = j['error']['errors'].first['reason']
    fail GoogleClientException, "Google Search failed. #{message} (#{reason})"
  end

  j
end