Dancer/SearchApp.pm

filter: Statementstmt 26.1% 44 / 168 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 31 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 55.0% 11 / 20 Podpod 0.0% 0 / 4 totaltotal 19.7% 55 / 279 CC 35 SCAR 51.1
CC
35
Cov
19%
__ANON__
420.0
__ANON__
56.0
reproxy
20.0
CRAP 166.1
↑ Summary Mail/Email/IMAP.pm »
1 package Dancer::SearchApp;
2 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use File::Basename 'basename';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Dancer;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use Search::Elasticsearch::Async;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use URI::Escape 'uri_unescape';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use URI::file;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 #use Search::Elasticsearch::TestServer;
9  
10 3 ▶use Dancer::SearchApp::Defaults 'get_defaults';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 3 ▶use Dancer::SearchApp::Entry;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Dancer::SearchApp::HTMLSnippet;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 3 ▶use vars qw($VERSION $es %indices);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 $VERSION = '0.06';
17  
18 =head1 NAME
19  
20 Dancer::SearchApp - A simple local search engine
21  
22 =head1 SYNOPSIS
23  
24 =head1 QUICKSTART
25  
26 Also see L<Dancer::SearchApp::Installation>.
27  
28 cpanm --look Dancer::SearchApp
29
30 # Install prerequisites
31 cpanm --installdeps .
32  
33 # Install Elasticsearch https://www.elastic.co/downloads/elasticsearch
34 # Start Elasticsearch
35 # Install Apache Tika from https://tika.apache.org/download.html into jar/
36  
37 # Launch the web frontend
38 plackup --host 127.0.0.1 -p 8080 -Ilib -a bin\app.pl
39  
40 # Edit filesystem configuration
41 cat >>fs-import.yml
42 fs:
43 directories:
44 - folder: "C:\\Users\\Corion\\Projekte\\App-StarTraders"
45 recurse: true
46 exclude:
47 - ".git"
48 - folder: "t\\documents"
49 recurse: true
50  
51 # Collect some content
52 perl -Ilib -w bin/index-filesystem.pl -f
53  
54 # Search in your browser
55  
56 =head1 CONFIGURATION
57  
58 Configuration happens through config.yml
59  
60 elastic_search:
61 home: "./elasticsearch-2.1.1/"
62 index: "dancer-searchapp"
63  
64 The Elasticsearch instance to used can also be passed in C<%ENV>
65 as C<SEARCHAPP_ES_NODES>.
66  
67 =cut
68  
69 3 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 3 $Data::Dumper::Sortkeys = 1;
71  
72 3 my $config = get_defaults(
73 env => \%ENV,
74 config => config(),
75 #defaults => \%
76 names => [
77 ['elastic_search/index' => 'elastic_search/index' => 'SEARCHAPP_ES_INDEX', 'searchapp'],
78 ['elastic_search/nodes' => 'elastic_search/nodes' => 'SEARCHAPP_ES_NODES', 'localhost:9200'],
79 ],
80 );
81  
82 # A small helper subroutine that adds some API headers that result in
83 # the API not being interpretable as pages to be displayed by a browser
84 0 ▶sub add_api_headers {
Subroutine add_api_headers: not called CC=1 SCAR=6.9
Pod undocumented
85 0 header 'Content-Disposition' => 'attachment; filename="1.txt"';
86 0 header 'X-Content-Type-Options' => 'nosniff';
87 };
88  
89 0 ▶sub search {
Subroutine search: not called CC=3 SCAR=24.8
Pod undocumented
90 0 ▶ if( ! $es ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Dancer::SearchApp::es) 0 0 0
91 0 my $nodes = $config->{elastic_search}->{nodes};
92 0 ▶ $nodes = [split /,/, $nodes] # our config system doesn't provide for lists...
Branch: 1 branch
BranchTrueFalseTotal
unless ref $nodes 0 0 0
93 unless ref $nodes;
94 0 $es = Search::Elasticsearch->new(
95 nodes => $nodes,
96 );
97 };
98
99 0 $es
100 };
101  
102 3 $Template::Stash::PRIVATE = $Template::Stash::PRIVATE = 1;
103  
104 0 ▶get '/' => sub {
Subroutine __ANON__: not called CC=20 SCAR=60.4
105 # Later, separate out the code paths between
106 # search and index page only, to serve the index
107 # page as a static file
108
109 0 my $statistics;
110 my $results;
111
112 0 ▶ my $from = params->{'from'} || 0;
Condition0%0/2
params()->{'from'} || 0
l!l
00
MC/DC0%0/1
params()->{'from'} || 0
params()->{'from'}
Truth table0%0/2
A
A= params()->{'from'}
Aresult
11
00
113 0 $from =~ s!\D!!g;
114 0 ▶ my $size = params->{'size'} || 25;
Condition0%0/2
params()->{'size'} || 25
l!l
00
MC/DC0%0/1
params()->{'size'} || 25
params()->{'size'}
Truth table0%0/2
A
A= params()->{'size'}
Aresult
11
00
115 0 $size =~ s!\D!!g;
116 0 my $search_term = params->{'q'};
117
118 0 ▶ if( defined $search_term) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $search_term) { } 0 0 0
119
120 #warning "Reading ES indices\n";
121 0 %indices = %{ search->indices->get({index => ['*']}) };
122 #warning $_ for sort keys %indices;
123  
124 0 my @restrict_type;
125 my $type;
126 0 ▶ if( $type = params->{'type'} and $type =~ m!([a-z0-9+-]+)/[a-z0-9+-]+!i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i) 0 0 0
Condition0%0/3
$type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
!ll&&!rl&&r
000
MC/DC0%0/2
$type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
$type = params()->{"type"} $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
Truth table0%0/3
A and B
A= $type = params()->{"type"}B= $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
ABresult
0X0
100
111
127 #warn "Filtering for '$type'";
128 0 @restrict_type = (filter => { term => { mime_type => $type }});
129 };
130
131 0 my $sanitized_search_term = $search_term;
132 # Escape colons, as they're special in search queries...
133 0 $sanitized_search_term =~ s!([:\\])!\\$1!g;
134
135 # Move this to an async query, later
136 0 my $index = $config->{elastic_search}->{index};
137 $results = search->search(
138 # Wir suchen in allen Sprachindices
139 0 index => [ grep { /^\Q$index\E/ } sort keys %indices ],
140 body => {
141 from => $from,
142 size => $size,
143 query => {
144 # multi_match => { ... grep for the non-autocomplete stuff, and include the boosters
145 bool => {
146 must => {
147 query_string => {
148 query => $search_term,
149 fields => ['title','folder','content', 'author'] #'creation_date']
150 },
151 },
152 @restrict_type,
153 },
154 },
155 sort => {
156 _score => { order => 'desc' },
157 },
158 "highlight" => {
159 "pre_tags" => '<b>',
160 "post_tags" => '</b>',
161 "fields" => {
162 # we want the whole content so we can strip it down
163 # ourselves:
164 "content" => {"number_of_fragments" => 0},
165 #"content" => {}
166 }
167 }
168 }
169 );
170
171 #warn Dumper $results->{hits};
172 } else {
173 # Update the statistics
174 #$statistics = search->search(
175 # search_type => 'count',
176 # index => config->{index},
177 # body => {
178 # query => {
179 # match_all => {}
180 # }
181 # }
182 #);
183 #warn Dumper $statistics;
184 };
185
186 0 ▶ if( $results ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($results) 0 0 0
187 0 for( @{ $results->{ hits }->{hits} } ) {
188 0 $_->{source} = Dancer::SearchApp::Entry->from_es( $_ );
189 0 for my $key ( qw( id index type )) {
190 0 $_->{$key} = $_->{"_$key"}; # thanks, Template::Toolkit
191 };
192
193 };
194 };
195
196 0 ▶ if( $results and exists params->{lucky}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($results and exists params()->{'lucky'}) { } 0 0 0
Condition0%0/3
$results and exists params()->{"lucky"}
!ll&&!rl&&r
000
MC/DC0%0/2
$results and exists params()->{"lucky"}
$results exists params()->{"lucky"}
Truth table0%0/3
A and B
A= $resultsB= exists params()->{"lucky"}
ABresult
0X0
100
111
197 0 my $first = $results->{ hits }->{hits}->[0];
198
199 0 ▶ if( $first ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first) 0 0 0
200 0 my( $index, $type, $id ) = @{$first}{qw(index type id)};
201 0 warn "Redirecting/reproxying first document";
202 0 ▶ if( $type eq 'http' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'http') { } 0 0 0
203 return
204 0 redirect $id
205 } else {
206 0 my $doc = $first->{source};
207 0 my $local = URI::file->new( $id )->file;
208 return
209 0 reproxy( $doc, $local, 'Inline',
210 index => $index,
211 type => $type,
212 );
213 }
214 };
215 } else {
216  
217 0 ▶ if( $results and $results->{hits} and $results->{hits}->{hits} and $results->{hits}->{hits}->[0]->{highlight}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($results and $results->{"hits"} and $results->{"hits"}{"hits"} and $results->{"hits"}{"hits"}[0]{"highlight"}) 0 0 0
Condition0%0/9
$results and $results->{"hits"} and $results->{"hits"}{"hits"} and $results->{"hits"}{"hits"}[0]{"highlight"}
!ll&&!rl&&r
000
$results and $results->{"hits"} and $results->{"hits"}{"hits"}
!ll&&!rl&&r
000
$results and $results->{"hits"}
!ll&&!rl&&r
000
MC/DC0%0/4
$results and $results->{"hits"} and $results->{"hits"}{"hits"} and $results->{"hits"}{"hits"}[0]{"highlight"}
$results $results->{"hits"} $results->{"hits"}{"hits"} $results->{"hits"}{"hits"}[0]{"highlight"}
Truth table0%0/5
A and B and C and D
A= $resultsB= $results->{"hits"}C= $results->{"hits"}{"hits"}D= $results->{"hits"}{"hits"}[0]{"highlight"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
218 # Rework the result snippets to show only the highlighted stuff, together
219 # with the appropriate page number if available
220 0 for my $document (@{ $results->{hits}->{hits} }) {
221 0 my $html = $document->{highlight}->{content}->[0];
222 0 my @show = Dancer::SearchApp::HTMLSnippet->extract_highlights(
223 html => $html,
224 max_length => 300,
225 );
226  
227 # Find the PDF page numbers from Tika
228 0 for my $s (@show) {
229 0 $s->{page} = () = (substr($html,0,$s->{start}) =~ /<div class="page"/g);
230 };
231  
232 $document->{highlight}->{content} =
233 [map {
234 0 +{ snippet => substr( $html, $_->{start}, $_->{length} ),
235 page => $_->{page},
236 }
237 0 } @show
238 ];
239 };
240 };
241
242 template 'index', {
243 0 ▶ results => ($results ? $results->{hits} : undef ),
Branch: 1 branch
BranchTrueFalseTotal
$results ? : 0 0 0
244 params => {
245 q => $search_term,
246 from => $from,
247 size => $size,
248 },
249 };
250 };
251 3 };
252  
253 # Show (cached) elements
254 0 ▶get '/cache/:index/:type/:id' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
255 0 my $index = params->{index};
256 0 my $type = params->{type};
257 0 my $id = uri_unescape( params->{id} );
258 0 my $document = retrieve($index,$type,$id);
259 #warn $document->basic_mime_type;
260
261 0 $document->{type} = $type;
262 0 $document->{index} = $index;
263
264 0 ▶ if( $document ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($document) { } 0 0 0
265 0 return template 'view_document', {
266 result => $document,
267 backlink => scalar( request->referer ),
268 # we should also save the page offset...
269 }
270 } else {
271 0 status 404;
272 return <<SORRY
273 That file does (not) exist anymore in the index.
274 SORRY
275 # We could delete that item from the index here...
276 # or schedule reindexing of the resource?
277 0 }
278 3 };
279  
280 # Reproxy elements from disk
281 0 ▶sub reproxy {
Subroutine reproxy: not called CC=4 SCAR=30.0
Pod undocumented
282 0 my( $document, $local, $disposition, %options ) = @_;
283
284 # Now, if the file exists both in the index and locally, let's reproxy the content
285 0 ▶ if( $document and -f $local) {
Branch: 1 branch
BranchTrueFalseTotal
if ($document and -f $local) { } 0 0 0
Condition0%0/3
$document and -f $local
!ll&&!rl&&r
000
MC/DC0%0/2
$document and -f $local
$document -f $local
Truth table0%0/3
A and B
A= $documentB= -f $local
ABresult
0X0
100
111
286 0 status 200;
287 0 content_type( $document->mime_type );
288 0 header( "Content-Disposition" => sprintf '%s; filename="%s"', $disposition, basename $local);
289 0 my $abs = File::Spec->rel2abs( $local, '.' );
290 0 ▶ open my $fh, '<', $local
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $local or die "Couldn't read local file '${local}': $!" 0 0 0
291 or die "Couldn't read local file '$local': $!";
292 0 binmode $fh;
293 0 local $/;
294 <$fh>
295
296 0 } else {
297 0 status 404; # sorry
298 return <<SORRY
299 That file does (not) exist anymore or is currently unreachable
300 for this webserver. We'll need to implement
301 cleaning up the index from dead items.
302 SORRY
303 # We could delete that item from the index here...
304 # Or schedule reindexing of the resource?
305 0 }
306 };
307  
308 0 ▶sub retrieve {
Subroutine retrieve: not called CC=2 SCAR=17.9
Pod undocumented
309 0 my( $index, $type, $id ) = @_;
310 0 my $document;
311 0 ▶ if( eval {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $document = search()->get('index', $index, 'type', $type, 'id', $id); 1 } }) { } 0 0 0
312 0 $document = search->get(index => $index, type => $type, id => $id);
313 0 1
314 }) {
315 0 my $res = Dancer::SearchApp::Entry->from_es($document);
316 0 return $res
317 } else {
318 0 warn "$@";
319 };
320 # Not found in the Elasticsearch index
321 return undef
322 0 }
323  
324 0 ▶get '/open/:index/:type/:id' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
325 0 my $index = params->{index};
326 0 my $type = params->{type};
327 0 my $id = uri_unescape params->{id};
328 0 my $document = retrieve($index,$type,$id);
329 0 ▶ if( $type eq 'http' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'http') { } 0 0 0
330 return
331 0 redirect $id
332 } else {
333 0 my $local = URI::file->new( $id )->file;
334 return
335 0 reproxy( $document, $local, 'Attachment',
336 index => $index,
337 type => $type,
338 );
339 }
340 3 };
341  
342 0 ▶get '/inline/:index/:type/:id' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
343 0 my $index = params->{index};
344 0 my $type = params->{type};
345 0 my $id = uri_unescape params->{id};
346 0 my $document = retrieve($index,$type,$id);
347
348 0 my $local;
349 0 ▶ if( 'http' eq $type ) {
Branch: 1 branch
BranchTrueFalseTotal
if ('http' eq $type) { } 0 0 0
350 0 $document->content
351 } else {
352 0 $local = URI::file->new( $id )->file;
353 };
354
355 0 reproxy( $document, $local, 'Inline',
356 index => $index,
357 type => $type,
358 );
359
360 3 };
361  
362 # This is likely a really bad design choice which I will regret later.
363 # Most likely, manually encoding to JSON would be the saner approach
364 # instead of globally setting a serializer for all routes.
365 3 set 'serializer' => 'JSON';
366  
367 0 ▶get '/suggest/:query.json' => sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
368 0 my( $q ) = params->{query};
369 #warn "Completing '$q'";
370
371 0 ▶ return [] unless $q and $q =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $q and $q =~ /\S/ 0 0 0
Condition0%0/3
$q and $q =~ /\S/
!ll&&!rl&&r
000
MC/DC0%0/2
$q and $q =~ /\S/
$q $q =~ /\S/
Truth table0%0/3
A and B
A= $qB= $q =~ /\S/
ABresult
0X0
100
111
372
373 # Strip leading/trailing whitespace, Justin Case
374 0 $q =~ s!^\s+!!;
375 0 $q =~ s!\s+$!!;
376  
377 # Reinitialize indices
378 # Some day, we could cache that/not refresh them all the time
379 0 %indices = %{ search->indices->get({index => ['*']}) };
380  
381 0 my @restrict_type;
382 my $type;
383 0 ▶ if( $type = params->{'type'} and $type =~ m!([a-z0-9+-]+)/[a-z0-9+-]+!i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i) 0 0 0
Condition0%0/3
$type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
!ll&&!rl&&r
000
MC/DC0%0/2
$type = params()->{"type"} and $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
$type = params()->{"type"} $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
Truth table0%0/3
A and B
A= $type = params()->{"type"}B= $type =~ m[([a-z0-9+-]+)/[a-z0-9+-]+]i
ABresult
0X0
100
111
384 #warn "Filtering for '$type'";
385 0 @restrict_type = (filter => { term => { mime_type => $type }});
386 };
387
388 # This should be centralized
389 # This is "did you mean X"
390 #my @fields = ('title','content', 'author');
391
392 # Query all suggestive fields at once:
393 #my %suggest_query = map {;
394 # "my_suggestions_$_" => {
395 # phrase => {
396 # field => "$_.autocomplete",
397 # #field => "$_",
398 # #text => $q,
399 # }
400 # }
401 #} @fields;
402
403 0 my @fields = ('title_suggest');
404
405 # Query all suggestive fields at once:
406 0 my %suggest_query = map {;
407 0 "my_completions_$_" => {
408 phrase => {
409 field => "title_suggest",
410 #field => "$_",
411 #text => $q,
412 }
413 }
414 } @fields;
415  
416 #warn Dumper \%suggest_query;
417
418 # Move this to an async query, later
419 0 my $index = $config->{elastic_search}->{index};
420 my $results = search->suggest(
421 0 index => [ grep { /^\Q$index\E/ } sort keys %indices ],
422 body => {
423 foo => {
424 text => $q,
425 completion => {
426 field => 'title_suggest',
427 "fuzzy" => { "fuzziness" => 2 }, # edit distance of 2
428 }
429 }
430 #%suggest_query
431 }
432 );
433
434 #warn Dumper $results;
435
436 0 my %suggestions;
437 my @res = map {; +{
438 tokens => [split //, $_->{text}],
439 value => $_->{text},
440 url => $_->{_source}->{url},
441 0 } }
442 0 ▶ sort { $b->{_score} <=> $a->{_score} || $b cmp $a } # sort by score+asciibetically descending
Condition0%0/3
$Dancer::SearchApp::b->{'_score'} <=> $Dancer::SearchApp::a->{'_score'} || $b cmp $a
l!l&&r!l&&!r
000
MC/DC0%0/2
$Dancer::SearchApp::b->{'_score'} <=> $Dancer::SearchApp::a->{'_score'} || $b cmp $a
$Dancer::SearchApp::b->{'_score'} <=> $Dancer::SearchApp::a->{'_score'} $b cmp $a
Truth table0%0/3
A || B
A= $Dancer::SearchApp::b->{'_score'} <=> $Dancer::SearchApp::a->{'_score'}B= $b cmp $a
ABresult
1X1
011
000
443 0 ▶ map { $_->{options} ? @{ $_->{options} } : () } # unwrap again
Branch: 1 branch
BranchTrueFalseTotal
$_->{'options'} ? : 0 0 0
444 0 map { @$_ } # unwrap
445 0 grep { ref $_ eq 'ARRAY' } values %$results
446 ;
447
448 0 add_api_headers;
449 0 return \@res;
450 3 };
451  
452 3 true;
453  
454 __END__
↑ Summary Mail/Email/IMAP.pm »