/[webpac2]/Webpacus/lib/Webpacus/Model/WebPAC.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /Webpacus/lib/Webpacus/Model/WebPAC.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 382 - (hide annotations)
Sun Jan 22 02:52:24 2006 UTC (18 years, 3 months ago) by dpavlin
File size: 15940 byte(s)
 r432@llin:  dpavlin | 2006-01-22 03:43:55 +0100
 remove WebPAC::Search::Estraier usage and replace it with calls to Search::Estraier
 directly, simplifing code in process

1 dpavlin 92 package Webpacus::Model::WebPAC;
2    
3     use strict;
4     use warnings;
5     use lib '/data/webpac2/lib';
6 dpavlin 93 use base qw/
7     Catalyst::Model
8     /;
9 dpavlin 237 use WebPAC::Store 0.08;
10 dpavlin 382 use Search::Estraier 0.04;
11 dpavlin 135 use File::Slurp;
12 dpavlin 378 use Time::HiRes qw/time/;
13 dpavlin 348 use Encode qw/encode decode from_to/;
14 dpavlin 379 use Template;
15 dpavlin 378 use Data::Dumper;
16 dpavlin 92
17     =head1 NAME
18    
19     Webpacus::Model::WebPAC - Catalyst Model
20    
21     =head1 SYNOPSIS
22    
23     See L<Webpacus> and L<WebPAC>.
24    
25     =head1 DESCRIPTION
26    
27     Catalyst Model for access to WebPAC data.
28    
29     =head2 new
30    
31     Configuration for hyperestraier in C<config.yaml> like this:
32    
33     --- #YAML:1.0
34     # DO NOT USE TABS FOR INDENTATION OR label/value SEPARATION!!!
35    
36     # configuration for hyper estraier full text search engine
37     hyperestraier:
38 dpavlin 222 masterurl: 'http://localhost:1978/node/webpac2'
39     defaultnode: 'webpac2'
40     defaultdepth: 1
41 dpavlin 96 user: 'admin'
42     passwd: 'admin'
43 dpavlin 143 hits_on_page: 100
44 dpavlin 305 hits_for_pager: 1000
45 dpavlin 92
46 dpavlin 96 webpac:
47     db_path: '/data/webpac2/db'
48     template_path: '/data/webpac2/conf/output/tt'
49     template: 'html_ffzg_results_short.tt'
50     # encoding comming from webpac
51     webpac_encoding: 'iso-8859-2'
52    
53 dpavlin 92 =cut
54    
55     sub new {
56     my ( $self, $c, $config ) = @_;
57    
58     $self = $self->NEXT::new($c, $config);
59     $self->config($config);
60    
61     my $log = $c->log;
62 dpavlin 94 $self->{log} = $log;
63 dpavlin 92
64 dpavlin 93 my $est_cfg = $c->config->{hyperestraier};
65     $est_cfg->{'log'} = $log;
66 dpavlin 92
67 dpavlin 271 $est_cfg->{encoding} = $est_cfg->{catalyst_encoding} || $c->config->{catalyst_encoding} or $c->log->fatal("can't find catalyst_encoding");
68 dpavlin 142
69 dpavlin 93 $log->debug("using config:" . Dumper($est_cfg) );
70 dpavlin 92
71 dpavlin 222 if (! $est_cfg->{database}) {
72     my $defaultnode = $est_cfg->{defaultnode} || $log->logdie("can't find defaultnode in estraier configuration");
73     $log->info("using default node $defaultnode");
74     $est_cfg->{database} = $defaultnode;
75     }
76    
77 dpavlin 382 my $url = $est_cfg->{masterurl} . '/node/' . $est_cfg->{database};
78 dpavlin 92
79 dpavlin 382 $log->info("opening Hyper Estraier index $url as $est_cfg->{'user'}");
80    
81     $self->{est_node} = Search::Estraier::Node->new(
82     url => $url,
83     user => $est_cfg->{user},
84     passwd => $est_cfg->{passwd},
85     );
86    
87     $log->fatal("can't create Search::Estraier::Node $url") unless ($self->{est_node});
88    
89 dpavlin 167 # save config parametars in object
90 dpavlin 348 foreach my $f (qw/db_path template_path hits_on_page webpac_encoding defaultdepth/) {
91 dpavlin 167 $self->{$f} = $c->config->{hyperestraier}->{$f} ||
92     $c->config->{webpac}->{$f};
93     $log->debug("self->{$f} = " . $self->{$f});
94     }
95     my $db_path = $self->{db_path};
96     my $template_path = $self->{template_path};
97 dpavlin 95
98     $log->debug("using db path '$db_path', template path '$template_path'");
99    
100 dpavlin 222 $self->{db} = new WebPAC::Store(
101 dpavlin 95 path => $db_path,
102     read_only => 1,
103 dpavlin 224 database => $est_cfg->{database},
104 dpavlin 95 );
105    
106 dpavlin 101 # default template from config.yaml
107 dpavlin 95 $self->{template} ||= $c->config->{webpac}->{template};
108    
109 dpavlin 100 $log->debug("converting encoding from webpac_encoding '" .
110     $c->config->{webpac}->{webpac_encoding} .
111 dpavlin 99 "'"
112     );
113 dpavlin 96
114 dpavlin 382 $self->{databases} = $c->config->{databases} || $log->fatal("can't find databases in config");
115 dpavlin 155
116 dpavlin 379 # create Template toolkit instance
117     $self->{'tt'} = Template->new(
118     INCLUDE_PATH => $template_path,
119     FILTERS => {
120     dump_html => sub {
121     return unless (@_);
122     my $out;
123     my $i = 1;
124     foreach my $v (@_) {
125     $out .= qq{<div id="dump_$i">} .
126     Data::HTMLDumper->Dump([ $v ],[ "v$i" ]) .
127     qq{</div>};
128     $i++;
129     }
130     $out =~ s!<table[^>/]*>!<table class="dump">!gis if ($out);
131     return $out;
132     }
133     },
134     EVAL_PERL => 1,
135     );
136 dpavlin 378
137 dpavlin 92 return $self;
138    
139     }
140    
141 dpavlin 135
142     =head2 search
143    
144 dpavlin 150 my $m->search(
145     phrase => 'query phrase',
146 dpavlin 155 add_attr => \@add_attr
147     get_attr => [ '@uri' ],
148     max => 42,
149 dpavlin 150 template => 'result_template.tt',
150 dpavlin 222 depth => 1,
151 dpavlin 150 );
152 dpavlin 135
153 dpavlin 155 All fields are standard C<WebPAC::Search::Estraier> parametars except
154     C<template> which will (if specified) return results in HTML using
155     selected template.
156    
157 dpavlin 135 =cut
158    
159 dpavlin 93 sub search {
160 dpavlin 150 my $self = shift;
161 dpavlin 93
162 dpavlin 378 my $search_start_t = time();
163    
164 dpavlin 150 my $args = {@_};
165    
166 dpavlin 95 my $log = $self->{log};
167 dpavlin 94
168 dpavlin 351 $log->debug("search args: " . Dumper( $args ));
169 dpavlin 95
170 dpavlin 150 my $query = $args->{phrase} || $log->warn("no query phrase") && return;
171 dpavlin 95
172 dpavlin 155 $log->debug("search model query: '$query'");
173     if ($args->{add_attr}) {
174     $log->debug(" + add_attr: " .
175     join("','", @{ $args->{add_attr} })
176     );
177     }
178 dpavlin 150
179     my $template_filename = $args->{template} || $self->{template};
180    
181 dpavlin 305 $args->{max} ||= $self->{'hits_for_pager'};
182 dpavlin 155 if (! $args->{max}) {
183 dpavlin 305 $args->{max} = 100;
184     $log->warn("max not set when calling model. Using default of $args->{max}");
185 dpavlin 155 }
186 dpavlin 93
187 dpavlin 155 my $times; # store some times for benchmarking
188    
189     my $t = time();
190    
191 dpavlin 222 # transfer depth of search
192     if (! $args->{depth}) {
193     my $default = $self->{defaultdepth} || $log->logdie("can't find defaultdepth in estraier configuration");
194     $args->{depth} = $default;
195     $log->warn("using default search depth $default");
196     }
197    
198 dpavlin 382 $log->debug("searching for maximum $args->{max} results using depth $args->{depth}");
199 dpavlin 155
200 dpavlin 382 #
201     # construct condition for Hyper Estraier
202     #
203     my $cond = Search::Estraier::Condition->new();
204     if ( ref($args->{add_attr}) eq 'ARRAY' ) {
205     $log->debug("adding search attributes: " . join(", ", @{ $args->{add_attr} }) );
206     map {
207     $cond->add_attr( _convert( $_ ) );
208     $log->debug(" + $_");
209     } @{ $args->{add_attr} };
210     };
211    
212     $cond->set_phrase( $query ) if ($query);
213     $cond->set_options( $args->{options} ) if ($args->{options});
214     $cond->set_order( $args->{order} ) if ($args->{order});
215    
216     my $max = $args->{max} || 7;
217     my $page = $args->{page} || 1;
218     if ($page < 1) {
219     $log->warn("page number $page < 1");
220     $page = 1;
221     }
222    
223 dpavlin 155 $times->{est} += time() - $t;
224    
225 dpavlin 382 $cond->set_max( $page * $max );
226 dpavlin 99
227 dpavlin 382 my $result = $self->{est_node}->search($cond, ( $args->{depth} || 0 ));
228     my $hits = $result->doc_num;
229    
230 dpavlin 380 $log->debug( sprintf("search took %.6fs and returned $hits hits.", $times->{est}) );
231 dpavlin 150
232 dpavlin 155 #
233 dpavlin 382 # fetch results
234 dpavlin 155 #
235    
236 dpavlin 382 my @results;
237 dpavlin 100
238 dpavlin 382 for my $i ( (($page - 1) * $max) .. ( $hits - 1 ) ) {
239 dpavlin 95
240 dpavlin 382 $t = time();
241    
242     #$log->debug("get_doc($i)");
243     my $doc = $result->get_doc( $i );
244     if (! $doc) {
245     $log->warn("can't find result $i");
246 dpavlin 224 next;
247     }
248 dpavlin 95
249 dpavlin 382 my $hash;
250 dpavlin 95
251 dpavlin 382 foreach my $attr (@{ $args->{get_attr} }) {
252     my $val = $doc->attr( $attr );
253     #$log->debug("attr $attr = ", $val || 'undef');
254     $hash->{$attr} = $val if (defined($val));
255 dpavlin 242 }
256 dpavlin 155
257 dpavlin 382 $times->{hash} += time() - $t;
258 dpavlin 155
259 dpavlin 382 next unless ($hash);
260 dpavlin 115
261 dpavlin 382 if (! $args->{'template'}) {
262     push @results, $hash;
263     } else {
264     my ($database, $prefix, $id);
265 dpavlin 155
266 dpavlin 382 if ( $hash->{'@uri'} =~ m!/([^/]+)/([^/]+)/(\d+)$!) {
267     ($database, $prefix,$id) = ($1,$2,$3);
268     } else {
269     $log->warn("can't decode database/prefix/id from " . $hash->{'@uri'});
270     next;
271     }
272 dpavlin 100
273 dpavlin 382 #$log->debug("load_ds( id => $id, prefix => '$prefix' )");
274 dpavlin 155
275 dpavlin 382 $t = time();
276 dpavlin 155
277 dpavlin 382 my $ds = $self->{db}->load_ds( database => $database, prefix => $prefix, id => $id );
278     if (! $ds) {
279     $log->error("can't load_ds( ${database}/${prefix}/${id} )");
280     next;
281     }
282 dpavlin 100
283 dpavlin 382 $times->{db} += time() - $t;
284 dpavlin 100
285 dpavlin 382 #$log->debug( "ds = " . Dumper( \@html_results ) );
286    
287     $t = time();
288    
289     my $html = $self->apply(
290     template => $template_filename,
291     data => $ds,
292     record_uri => "${database}/${prefix}/${id}",
293     config => $self->{databases}->{$database},
294     );
295    
296     $times->{apply} += time() - $t;
297    
298     $t = time();
299    
300     $html = decode($self->{webpac_encoding}, $html);
301    
302     $times->{decode} += time() - $t;
303    
304     push @results, $html;
305     }
306    
307 dpavlin 95 }
308    
309 dpavlin 382 $log->debug( '@results = ' . Dumper( \@results ) );
310 dpavlin 115
311 dpavlin 155 $log->debug( sprintf(
312 dpavlin 382 "duration breakdown: estraier %.6fs, hash %.6fs, store %.6fs, apply %.6fs, decode %.06f, total: %.6fs",
313     $times->{est}, $times->{hash}, $times->{db}, $times->{apply}, $times->{decode}, time() - $search_start_t,
314 dpavlin 155 ) );
315    
316 dpavlin 382 return \@results;
317 dpavlin 93 }
318    
319 dpavlin 165 =head2 record
320    
321     my $html = $m->record(
322     mfn => 42,
323     template => 'foo.tt',
324     );
325    
326     This will load one record, convert it to html using C<template> and return
327     it.
328    
329     =cut
330    
331     sub record {
332     my $self = shift;
333    
334     my $args = {@_};
335     my $log = $self->{log};
336 dpavlin 351 $log->debug("record args: " . Dumper( $args ));
337 dpavlin 165
338 dpavlin 242 foreach my $f (qw/record_uri template/) {
339 dpavlin 228 $log->fatal("need $f") unless ($args->{$f});
340 dpavlin 165 }
341    
342 dpavlin 242 my ($database, $prefix, $id);
343 dpavlin 165
344 dpavlin 242 if ($args->{record_uri} =~ m#^([^/]+)/([^/]+)/([^/]+)$#) {
345     ($database, $prefix, $id) = ($1,$2,$3);
346     } else {
347     $log->error("can't parse $args->{record_uri} into prefix, database and uri");
348     return;
349     }
350 dpavlin 165
351 dpavlin 242 my $ds = $self->{db}->load_ds( id => $id, prefix => $prefix, database => $database );
352     if (! $ds) {
353     $log->error("can't load_ds( $database/$prefix/$id )");
354     return;
355     }
356    
357 dpavlin 379 my $html = $self->apply(
358 dpavlin 165 template => $args->{template},
359     data => $ds,
360 dpavlin 242 record_uri => $args->{record_uri},
361 dpavlin 305 config => $self->{databases}->{$database},
362 dpavlin 165 );
363    
364 dpavlin 348 $html = decode($self->{webpac_encoding}, $html);
365 dpavlin 165
366     return $html;
367     }
368    
369 dpavlin 305
370 dpavlin 135 =head2 save_html
371 dpavlin 93
372 dpavlin 135 $m->save_html( '/full/path/to/file', $content );
373 dpavlin 93
374 dpavlin 348 It will use C<Encode> to convert content encoding back to
375 dpavlin 135 Webpac codepage, recode JavaScript Unicode entities (%u1234),
376     strip extra newlines at beginning and end, and save to
377     C</full/path/to/file.new> and if that succeeds, just rename
378     it over original file which should be atomic on filesystem level.
379    
380     =cut
381    
382     sub save_html {
383     my ($self, $path, $content) = @_;
384    
385 dpavlin 348 # FIXME Should this be UTF-8 or someting?
386     my $js_encoding = $self->{webpac_encoding};
387     $js_encoding = 'UTF-16';
388    
389 dpavlin 135 sub _conv_js {
390 dpavlin 348 return '0x' . $_[1];
391     return encode($_[0], chr(hex($_[1])));
392 dpavlin 135 }
393 dpavlin 348 #$content =~ s/%u([a-fA-F0-9]{4})/_conv_js($js_encoding,$1)/gex;
394 dpavlin 135 $content =~ s/^[\n\r]+//s;
395     $content =~ s/[\n\r]+$/\n/s;
396 dpavlin 282 $content =~ s/\n\r/\n/gs;
397 dpavlin 135
398 dpavlin 348 my $disk_encoding = $self->{webpac_encoding} || 'utf-8';
399     $self->{log}->debug("convert encoding to $disk_encoding");
400     from_to($content, 'utf-8', $disk_encoding) || $self->{log}->warn("encoding from utf-8 to $disk_encoding failed for: $content");
401 dpavlin 179
402     write_file($path . '.new', {binmode => ':raw' }, $content) || die "can't save ${path}.new $!";
403 dpavlin 135 rename $path . '.new', $path || die "can't rename to $path: $!";
404     }
405    
406     =head2 load_html
407    
408     my $html = $m->load_html('/full/path/to/file');
409    
410     This will convert file from Webpac encoding to Catalyst and
411     convert that data to escaped HTML (for sending into
412     C<< <textarea/> >> tags in html.
413    
414     =cut
415    
416     sub load_html {
417     my ($self, $path) = @_;
418    
419     die "no path?" unless ($path);
420    
421 dpavlin 179 my $content = read_file($path, {binmode => ':raw' }) || die "can't read $path: $!";
422 dpavlin 135
423 dpavlin 348 return decode($self->{webpac_encoding}, $content);
424 dpavlin 135 }
425    
426 dpavlin 379
427     =head2 apply
428    
429     Create output from in-memory data structure using Template Toolkit template.
430    
431     my $text = $tt->apply(
432     template => 'text.tt',
433     data => $ds,
434     record_uri => 'database/prefix/mfn',
435     );
436    
437     It also has follwing template toolikit filter routies defined:
438    
439     =cut
440    
441     sub apply {
442     my $self = shift;
443    
444     my $args = {@_};
445    
446     my $log = $self->{log} || die "no log?";
447    
448     foreach my $a (qw/template data/) {
449 dpavlin 382 $log->fatal("need $a") unless ($args->{$a});
450 dpavlin 379 }
451    
452     =head3 tt_filter_type
453    
454     filter to return values of specified from $ds, usage from TT template is in form
455     C<d('FieldName','delimiter')>, where C<delimiter> is optional, like this:
456    
457     [% d('Title') %]
458     [% d('Author',', ' %]
459    
460     =cut
461    
462     sub tt_filter_type {
463     my ($data,$type) = @_;
464    
465     die "no data?" unless ($data);
466     $type ||= 'display';
467    
468     my $default_delimiter = {
469     'display' => '&#182;<br/>',
470     'index' => '\n',
471     };
472    
473     return sub {
474    
475     my ($name,$join) = @_;
476    
477     die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
478     # Hm? Should we die here?
479     return unless ($name);
480    
481     my $item = $data->{'data'}->{$name} || return;
482    
483     my $v = $item->{$type} || return;
484    
485     if (ref($v) eq 'ARRAY') {
486     if ($#{$v} == 0) {
487     $v = $v->[0];
488     } else {
489     $join = $default_delimiter->{$type} unless defined($join);
490     $v = join($join, @{$v});
491     }
492     } else {
493     warn("TT filter $type(): field $name values aren't ARRAY, ignoring");
494     }
495    
496     return $v;
497     }
498     }
499    
500     $args->{'d'} = tt_filter_type($args, 'display');
501     $args->{'display'} = tt_filter_type($args, 'display');
502    
503     =head3 tt_filter_search
504    
505     filter to return links to search, usage in TT:
506    
507     [% search('FieldToDisplay','FieldToSearch','optional delimiter', 'optional_template.tt') %]
508    
509     =cut
510    
511     sub tt_filter_search {
512    
513     my ($data) = @_;
514    
515     die "no data?" unless ($data);
516    
517     return sub {
518    
519     my ($display,$search,$delimiter,$template) = @_;
520    
521     # default delimiter
522     $delimiter ||= '&#182;<br/>',
523    
524     die "no data hash" unless ($data->{'data'} && ref($data->{'data'}) eq 'HASH');
525     # Hm? Should we die here?
526     return unless ($display);
527    
528     my $item = $data->{'data'}->{$display} || return;
529    
530     return unless($item->{'display'});
531     if (! $item->{'search'}) {
532     warn "error in TT template: field $display didn't insert anything into search, use d('$display') and not search('$display'...)";
533     return;
534     }
535    
536     my @warn;
537     foreach my $type (qw/display search/) {
538     push @warn, "field $display type $type values aren't ARRAY" unless (ref($item->{$type}) eq 'ARRAY');
539     }
540    
541     if (@warn) {
542     warn("TT filter search(): " . join(",", @warn) . ", skipping");
543     return;
544     }
545     my @html;
546    
547     my $d_el = $#{ $item->{'display'} };
548     my $s_el = $#{ $item->{'search'} };
549    
550     # easy, both fields have same number of elements or there is just
551     # one search and multiple display
552     if ( $d_el == $s_el || $s_el == 0 ) {
553    
554     foreach my $i ( 0 .. $d_el ) {
555    
556     my $s;
557     if ($s_el > 0) {
558     $s = $item->{'search'}->[$i] || die "can't find value $i for type search in field $search";
559     } else {
560     $s = $item->{'search'}->[0];
561     }
562     #$s =~ s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
563     $s = __quotemeta( $s );
564    
565     my $d = $item->{'display'}->[$i] || die "can't find value $i for type display in field $display";
566    
567     my $template_arg = '';
568     $template_arg = qq{,'$template'} if ($template);
569    
570     push @html, qq{<a href="#" onclick="return search_via_link('$search','$s'${template_arg})">$d</a>};
571     }
572    
573     return join($delimiter, @html);
574     } else {
575     my $html = qq{<div class="notice">WARNING: we should really support if there is $d_el display elements and $s_el search elements, but currently there is no nice way to do so, so we will just display values</div>};
576     my $v = $item->{'display'};
577    
578     if ($#{$v} == 0) {
579     $html .= $v->[0];
580     } else {
581     $html .= join($delimiter, @{$v});
582     }
583     return $html;
584     }
585     }
586     }
587    
588     $args->{'search'} = tt_filter_search($args);
589    
590     =head3 load_rec
591    
592     Used mostly for onClick events like this:
593    
594     <a href="#" onClick="[% load_rec( record_uri, 'template_name.tt') %]>foo</a>
595    
596     It will automatically do sanity checking and create correct JavaScript code.
597    
598     =cut
599    
600     $args->{'load_rec'} = sub {
601     my @errors;
602    
603     my $record_uri = shift or push @errors, "record_uri missing";
604     my $template = shift or push @errors, "template missing";
605    
606     if ($record_uri !~ m#^[^/]+/[^/]+/[^/]+$#) {
607     push @errors, "invalid format of record_uri: $record_uri";
608     }
609    
610     if (@errors) {
611     return "Logger.error('errors in load_rec: " . join(", ", @errors) . "'); return false;";
612     } else {
613     return "load_rec('$record_uri','$template'); return false;";
614     }
615     };
616    
617     =head3 load_template
618    
619     Used to re-submit search request and load results in different template
620    
621     <a href="#" onClick="[% load_template( 'template_name.tt' ) %]">bar</a>
622    
623     =cut
624    
625     $args->{'load_template'} = sub {
626     my $template = shift or return "Logger.error('load_template missing template name!'); return false;";
627     return "load_template($template); return false;";
628     };
629    
630     my $out;
631    
632     $self->{'tt'}->process(
633     $args->{'template'},
634     $args,
635     \$out
636     ) || $log->error( "apply can't process template: ", $self->{'tt'}->error() );
637    
638     return $out;
639     }
640    
641    
642     =head2 __quotemeta
643    
644     Helper to quote JavaScript-friendly characters
645    
646     =cut
647    
648     sub __quotemeta {
649     local $_ = shift;
650     $_ = decode('iso-8859-2', $_);
651    
652     s<([\x{0080}-\x{fffd}]+)>{sprintf '\u%0*v4X', '\u', $1}ge if ( Encode::is_utf8($_) );
653     {
654     use bytes;
655     s<((?:[^ \x21-\x7E]|(?:\\(?!u)))+)>{sprintf '\x%0*v2X', '\x', $1}ge;
656     }
657    
658     s/\\x09/\\t/g;
659     s/\\x0A/\\n/g;
660     s/\\x0D/\\r/g;
661     s/"/\\"/g;
662     s/\\x5C/\\\\/g;
663    
664     return $_;
665     }
666    
667    
668    
669 dpavlin 92 =head1 AUTHOR
670    
671 dpavlin 348 Dobrica Pavlinusic C<< <dpavlin@rot13.org> >>
672 dpavlin 92
673     =head1 LICENSE
674    
675     This library is free software, you can redistribute it and/or modify
676     it under the same terms as Perl itself.
677    
678     =cut
679    
680     1;

  ViewVC Help
Powered by ViewVC 1.1.26