/searchengine_query.rb
Ruby | 82 lines | 70 code | 11 blank | 1 comment | 14 complexity | b6ba821b306140c21702d1b9f82bf2ea MD5 | raw file
- require 'net/http'
- require 'net/https'
- require 'json'
- class SearchEngine
- attr_reader :searchTerm
- def initialize(strSearch, strGoogleKey)
- @searchTerm = strSearch
- @googleDevKey = strGoogleKey
- end
- def getGoogleQuery()
- return "https://www.google.it/search?&oe=utf8&num=10&q=" + getCleanText(@searchTerm)
- end
- def getGoogleFirstResult()
- return [nil, nil, nil] unless @googleDevKey
- strPage = getPage(getGoogleApiQuery())
- hResult = JSON.parse(strPage)
- strDesc, strLink, strName = nil, nil, nil
- if hResult["items"] != nil && !hResult["items"].empty? then
- strName = hResult["items"].first["title"]
- strLink = hResult["items"].first["link"]
- strDesc = hResult["items"].first["snippet"]
- end
- if strName && strLink && strDesc then
- [strName, strLink, strDesc]
- else
- [nil, nil, nil]
- end
- end
- def getDuckDuckGoQuery()
- return "https://duckduckgo.com/?q=" + getCleanText(@searchTerm)
- end
- def getDuckDuckGoOfficialPage()
- strPage = getPage(getDuckDuckGoApiQuery())
- #puts "Parsing " + getDuckDuckGoApiQuery() + "..."
- hResult = JSON.parse(strPage)
- strDesc, strLink, strName = nil, nil, nil
- if hResult["Results"] != nil && !hResult["Results"].empty? then
- strDesc = hResult["AbstractText"]
- strLink = hResult["Results"].first["FirstURL"]
- strName = hResult["Heading"]
- end
- if strName && strLink && strDesc then
- [strName, strLink, strDesc]
- else
- [nil, nil, nil]
- end
- end
- private
- def getDuckDuckGoApiQuery()
- return "https://api.duckduckgo.com/?q=#{getCleanText(@searchTerm)}&format=json&pretty=0"
- end
- def getGoogleApiQuery()
- return "https://www.googleapis.com/customsearch/v1?key=#{@googleDevKey}&q=#{getCleanText(@searchTerm)}&cx=017576662512468239146:omuauf_lfve&num=1&oe=utf8"
- end
- def getCleanText(strText)
- regSpaces = /\s{2,}/
- workString = strText.gsub(regSpaces, " ").strip
- workString.gsub!(" ", "+")
- URI.escape(workString)
- end
- def getPage(strURL)
- uri = URI.parse(strURL)
- http = Net::HTTP.new(uri.host, uri.port)
- if uri.port == 443 then
- http.use_ssl = true
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
- end
- response = http.get(uri.request_uri)
- response.body.force_encoding("UTF-8")
- end
- end