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