Class: PdfSearch::WebServer

Inherits:
Object
  • Object
show all
Defined in:
lib/web_server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(search_index, debug_mode = false) ⇒ WebServer

Returns a new instance of WebServer.



7
8
9
10
# File 'lib/web_server.rb', line 7

def initialize(search_index, debug_mode = false)
  @search_index = search_index
  @debug_mode = (ENV['DEBUG_PDF_SEARCH'] == '1') || debug_mode
end

Instance Attribute Details

#daemonObject

Returns the value of attribute daemon.



5
6
7
# File 'lib/web_server.rb', line 5

def daemon
  @daemon
end

Instance Method Details

#auth_defined?Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/web_server.rb', line 33

def auth_defined?
  [ENV['PDF_SEARCH_USERNAME'], ENV['PDF_SEARCH_PASSWORD']].all? do |env_var|
    env_var != nil && env_var != ''
  end
end

#basic_authObject



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/web_server.rb', line 12

def basic_auth
  return @basic_auth if @basic_auth != nil

  config = { :Realm => 'BanalBI Pdf-Search' }

  htpasswd = WEBrick::HTTPAuth::Htpasswd.new 'banalbi-pdf-search'
  htpasswd.set_passwd config[:Realm], ENV['PDF_SEARCH_USERNAME'] , ENV['PDF_SEARCH_PASSWORD']
  htpasswd.flush

  config[:UserDB] = htpasswd

  @basic_auth = WEBrick::HTTPAuth::BasicAuth.new config
end

#index(request, response) ⇒ Object



26
27
28
29
30
31
# File 'lib/web_server.rb', line 26

def index(request, response)
  search_view = ::PdfSearch::SearchView.new(@search_index)
  response.status = 200
  response['Content-Type'] = 'text/html'
  response.body = search_view.render
end

#response_html(es_response) ⇒ Object



67
68
69
70
71
72
# File 'lib/web_server.rb', line 67

def response_html(es_response)
  results = es_response['hits']['hits']
  results.map do |result|
    "<li>#{result["_source"]["text"]}</li>"
  end.join("\n")
end

#search(request, response) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/web_server.rb', line 39

def search(request, response)
  if auth_defined?
    basic_auth.authenticate(request, response)
  end

  query = ::PdfSearch::ElasticSearchQuery.new(JSON.parse(request.body), @search_index)
  elastic_response = ::PdfSearch::ElasticSearchClient.search index: 'pdf_pages', body: query.to_hash

  response.body = response_html(elastic_response)
end

#startObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/web_server.rb', line 50

def start
  start_server = lambda do
    server = WEBrick::HTTPServer.new(:Port => 80)

    server.mount_proc '/', &method(:index)
    server.mount_proc '/search', &method(:search)

    server.start
  end

  if @debug_mode
    start_server.call
  else
   self.daemon = Daemons.call(multiple: true, &start_server)
  end
end