PageRenderTime 40ms CodeModel.GetById 31ms app.highlight 8ms RepoModel.GetById 0ms app.codeStats 0ms

/searchengine_query.rb

https://bitbucket.org/King_DuckZ/assobiotech
Ruby | 82 lines | 70 code | 11 blank | 1 comment | 14 complexity | b6ba821b306140c21702d1b9f82bf2ea MD5 | raw file
 1require 'net/http'
 2require 'net/https'
 3require 'json'
 4
 5class SearchEngine
 6	attr_reader :searchTerm
 7	def initialize(strSearch, strGoogleKey)
 8		@searchTerm = strSearch
 9		@googleDevKey = strGoogleKey
10	end
11
12	def getGoogleQuery()
13		return "https://www.google.it/search?&oe=utf8&num=10&q=" + getCleanText(@searchTerm)
14	end
15
16	def getGoogleFirstResult()
17		return [nil, nil, nil] unless @googleDevKey
18
19		strPage = getPage(getGoogleApiQuery())
20		hResult = JSON.parse(strPage)
21
22		strDesc, strLink, strName = nil, nil, nil
23		if hResult["items"] != nil && !hResult["items"].empty? then
24			strName = hResult["items"].first["title"]
25			strLink = hResult["items"].first["link"]
26			strDesc = hResult["items"].first["snippet"]
27		end
28		if strName && strLink && strDesc then
29			[strName, strLink, strDesc]
30		else
31			[nil, nil, nil]
32		end
33	end
34
35	def getDuckDuckGoQuery()
36		return "https://duckduckgo.com/?q=" + getCleanText(@searchTerm)
37	end
38
39	def getDuckDuckGoOfficialPage()
40		strPage = getPage(getDuckDuckGoApiQuery())
41		#puts "Parsing " + getDuckDuckGoApiQuery() + "..."
42		hResult = JSON.parse(strPage)
43		strDesc, strLink, strName = nil, nil, nil
44		if hResult["Results"] != nil && !hResult["Results"].empty? then
45			strDesc = hResult["AbstractText"]
46			strLink = hResult["Results"].first["FirstURL"]
47			strName = hResult["Heading"]
48		end
49		if strName && strLink && strDesc then
50			[strName, strLink, strDesc]
51		else
52			[nil, nil, nil]
53		end
54	end
55
56private
57	def getDuckDuckGoApiQuery()
58		return "https://api.duckduckgo.com/?q=#{getCleanText(@searchTerm)}&format=json&pretty=0"
59	end
60
61	def getGoogleApiQuery()
62		return "https://www.googleapis.com/customsearch/v1?key=#{@googleDevKey}&q=#{getCleanText(@searchTerm)}&cx=017576662512468239146:omuauf_lfve&num=1&oe=utf8"
63	end
64
65	def getCleanText(strText)
66		regSpaces = /\s{2,}/
67		workString = strText.gsub(regSpaces, " ").strip
68		workString.gsub!(" ", "+")
69		URI.escape(workString)
70	end
71
72	def getPage(strURL)
73		uri = URI.parse(strURL)
74		http = Net::HTTP.new(uri.host, uri.port)
75		if uri.port == 443 then
76			http.use_ssl = true
77			http.verify_mode = OpenSSL::SSL::VERIFY_NONE
78		end
79		response = http.get(uri.request_uri)
80		response.body.force_encoding("UTF-8")
81	end
82end