/[Search-Estraier]/trunk/Estraier.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

Diff of /trunk/Estraier.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 12 by dpavlin, Wed Jan 4 19:28:30 2006 UTC revision 40 by dpavlin, Thu Jan 5 23:00:22 2006 UTC
# Line 4  use 5.008; Line 4  use 5.008;
4  use strict;  use strict;
5  use warnings;  use warnings;
6    
 require Exporter;  
   
 our @ISA = qw(Exporter);  
   
 our %EXPORT_TAGS = ( 'all' => [ qw(  
 ) ] );  
   
 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );  
   
 our @EXPORT = qw(  
 );  
   
7  our $VERSION = '0.00';  our $VERSION = '0.00';
8    
 use Carp;  
   
9  =head1 NAME  =head1 NAME
10    
11  Search::Estraier - pure perl module to use Hyper Estraier search engine  Search::Estraier - pure perl module to use Hyper Estraier search engine
# Line 41  implementation. It also includes methods Line 27  implementation. It also includes methods
27    
28  =cut  =cut
29    
30    =head2 _s
31    
32    Remove multiple whitespaces from string, as well as whitespaces at beginning or end
33    
34     my $text = $self->_s(" this  is a text  ");
35     $text = 'this is a text';
36    
37    =cut
38    
39    sub _s {
40            my $text = $_[1] || return;
41            $text =~ s/\s\s+/ /gs;
42            $text =~ s/^\s+//;
43            $text =~ s/\s+$//;
44            return $text;
45    }
46    
47  package Search::Estraier::Document;  package Search::Estraier::Document;
48    
49  use Carp qw/croak confess/;  use Carp qw/croak confess/;
50    
51    use Search::Estraier;
52    our @ISA = qw/Search::Estraier/;
53    
54  =head1 Search::Estraier::Document  =head1 Search::Estraier::Document
55    
56  Document for HyperEstraier  This class implements Document which is collection of attributes
57    (key=value), vectors (also key value) display text and hidden text.
58    
59  =head2 new  =head2 new
60    
61    Create new document, empty or from draft.
62    
63    my $doc = new Search::HyperEstraier::Document;    my $doc = new Search::HyperEstraier::Document;
64      my $doc2 = new Search::HyperEstraier::Document( $draft );
65    
66  =cut  =cut
67    
68  sub new {  sub new {
69          my $class = shift;          my $class = shift;
70          my $self = {@_};          my $self = {};
71          bless($self, $class);          bless($self, $class);
72    
73          $self->{id} = -1;          $self->{id} = -1;
74    
75            my $draft = shift;
76    
77            if ($draft) {
78                    my $in_text = 0;
79                    foreach my $line (split(/\n/, $draft)) {
80    
81                            if ($in_text) {
82                                    if ($line =~ /^\t/) {
83                                            push @{ $self->{htexts} }, substr($line, 1);
84                                    } else {
85                                            push @{ $self->{dtexts} }, $line;
86                                    }
87                                    next;
88                            }
89    
90                            if ($line =~ m/^%VECTOR\t(.+)$/) {
91                                    my @fields = split(/\t/, $1);
92                                    for my $i ( 0 .. ($#fields - 1) ) {
93                                            $self->{kwords}->{ $fields[ $i ] } = $fields[ $i + 1 ];
94                                            $i++;
95                                    }
96                                    next;
97                            } elsif ($line =~ m/^%/) {
98                                    # What is this? comment?
99                                    #warn "$line\n";
100                                    next;
101                            } elsif ($line =~ m/^$/) {
102                                    $in_text = 1;
103                                    next;
104                            } elsif ($line =~ m/^(.+)=(.+)$/) {
105                                    $self->{attrs}->{ $1 } = $2;
106                                    next;
107                            }
108    
109                            warn "draft ignored: $line\n";
110                    }
111            }
112    
113          $self ? return $self : return undef;          $self ? return $self : return undef;
114  }  }
115    
# Line 84  sub add_attr { Line 132  sub add_attr {
132    
133          while (my ($name, $value) = each %{ $attrs }) {          while (my ($name, $value) = each %{ $attrs }) {
134                  if (! defined($value)) {                  if (! defined($value)) {
135                          delete( $self->{attrs}->{_s($name)} );                          delete( $self->{attrs}->{ $self->_s($name) } );
136                  } else {                  } else {
137                          $self->{attrs}->{_s($name)} = _s($value);                          $self->{attrs}->{ $self->_s($name) } = $self->_s($value);
138                  }                  }
139          }          }
140    
# Line 107  sub add_text { Line 155  sub add_text {
155          my $text = shift;          my $text = shift;
156          return unless defined($text);          return unless defined($text);
157    
158          push @{ $self->{dtexts} }, _s($text);          push @{ $self->{dtexts} }, $self->_s($text);
159  }  }
160    
161    
# Line 124  sub add_hidden_text { Line 172  sub add_hidden_text {
172          my $text = shift;          my $text = shift;
173          return unless defined($text);          return unless defined($text);
174    
175          push @{ $self->{htexts} }, _s($text);          push @{ $self->{htexts} }, $self->_s($text);
176  }  }
177    
178  =head2 id  =head2 id
# Line 200  sub cat_texts { Line 248  sub cat_texts {
248    
249  =head2 dump_draft  =head2 dump_draft
250    
251    Dump draft data from document object.
252    
253    print $doc->dump_draft;    print $doc->dump_draft;
254    
255  =cut  =cut
256    
257  sub dump_draft {  sub dump_draft {
258          return 'FIXME';          my $self = shift;
259            my $draft;
260    
261            foreach my $attr_name (sort keys %{ $self->{attrs} }) {
262                    $draft .= $attr_name . '=' . $self->{attrs}->{$attr_name} . "\n";
263            }
264    
265            if ($self->{kwords}) {
266                    $draft .= '%%VECTOR';
267                    while (my ($key, $value) = each %{ $self->{kwords} }) {
268                            $draft .= "\t$key\t$value";
269                    }
270                    $draft .= "\n";
271            }
272    
273            $draft .= "\n";
274    
275            $draft .= join("\n", @{ $self->{dtexts} }) . "\n" if ($self->{dtexts});
276            $draft .= "\t" . join("\n\t", @{ $self->{htexts} }) . "\n" if ($self->{htexts});
277    
278            return $draft;
279  }  }
280    
281  =head2 delete  =head2 delete
# Line 214  Empty document object Line 284  Empty document object
284    
285    $doc->delete;    $doc->delete;
286    
287    This function is addition to original Ruby API, and since it was included in C wrappers it's here as a
288    convinience. Document objects which go out of scope will be destroyed
289    automatically.
290    
291  =cut  =cut
292    
293  sub delete {  sub delete {
294          my $self = shift;          my $self = shift;
295    
296          foreach my $data (qw/attrs dtexts stexts/) {          foreach my $data (qw/attrs dtexts stexts kwords/) {
297                  delete($self->{$data});                  delete($self->{$data});
298          }          }
299    
# Line 229  sub delete { Line 303  sub delete {
303  }  }
304    
305    
 =head2 _s  
306    
307  Remove multiple whitespaces from string, as well as whitespaces at beginning or end  package Search::Estraier::Condition;
308    
309   my $text = _s(" this  is a text  ");  use Carp qw/confess croak/;
310   $text = 'this is a text';  
311    use Search::Estraier;
312    our @ISA = qw/Search::Estraier/;
313    
314    =head1 Search::Estraier::Condition
315    
316    =head2 new
317    
318      my $cond = new Search::HyperEstraier::Condition;
319    
320  =cut  =cut
321    
322  sub _s {  sub new {
323          my $text = shift || return;          my $class = shift;
324          $text =~ s/\s\s+/ /gs;          my $self = {};
325          $text =~ s/^\s+//;          bless($self, $class);
326          $text =~ s/\s+$//;  
327          return $text;          $self->{max} = -1;
328            $self->{options} = 0;
329    
330            $self ? return $self : return undef;
331    }
332    
333    =head2 set_phrase
334    
335      $cond->set_phrase('search phrase');
336    
337    =cut
338    
339    sub set_phrase {
340            my $self = shift;
341            $self->{phrase} = $self->_s( shift );
342  }  }
343    
344    =head2 add_attr
345    
346      $cond->add_attr('@URI STRINC /~dpavlin/');
347    
348  package Search::Estraier::Master;  =cut
349    
350  use Carp;  sub add_attr {
351            my $self = shift;
352            my $attr = shift || return;
353            push @{ $self->{attrs} }, $self->_s( $attr );
354    }
355    
356  =head1 Search::Estraier::Master  =head2 set_order
357    
358  Controll node master. This requires user with administration priviledges.    $cond->set_order('@mdate NUMD');
359    
360  =cut  =cut
361    
362  {  sub set_order {
363          package RequestAgent;          my $self = shift;
364          @ISA = qw(LWP::UserAgent);          $self->{order} = shift;
365    }
366    
367          sub new {  =head2 set_max
                 my $self = LWP::UserAgent::new(@_);  
                 $self->agent("Search-Estraier/$Search::Estraer::VERSION");  
                 $self;  
         }  
368    
369          sub get_basic_credentials {    $cond->set_max(42);
370                  my($self, $realm, $uri) = @_;  
371  #               return ($user, $password);  =cut
372          }  
373    sub set_max {
374            my $self = shift;
375            my $max = shift;
376            croak "set_max needs number" unless ($max =~ m/^\d+$/);
377            $self->{max} = $max;
378  }  }
379    
380    =head2 set_options
381    
382      $cond->set_options( SURE => 1 );
383    
384    =cut
385    
386    my $options = {
387            # check N-gram keys skipping by three
388            SURE => 1 << 0,
389            # check N-gram keys skipping by two
390            USUAL => 1 << 1,
391            # without TF-IDF tuning
392            FAST => 1 << 2,
393            # with the simplified phrase
394            AGITO => 1 << 3,
395            # check every N-gram key
396            NOIDF => 1 << 4,
397            # check N-gram keys skipping by one
398            SIMPLE => 1 << 10,
399    };
400    
401    sub set_options {
402            my $self = shift;
403            my $option = shift;
404            confess "unknown option" unless ($options->{$option});
405            $self->{options} ||= $options->{$option};
406    }
407    
408    =head2 phrase
409    
410    Return search phrase.
411    
412      print $cond->phrase;
413    
414    =cut
415    
416    sub phrase {
417            my $self = shift;
418            return $self->{phrase};
419    }
420    
421    =head2 order
422    
423    Return search result order.
424    
425      print $cond->order;
426    
427    =cut
428    
429    sub order {
430            my $self = shift;
431            return $self->{order};
432    }
433    
434    =head2 attrs
435    
436    Return search result attrs.
437    
438      my @cond_attrs = $cond->attrs;
439    
440    =cut
441    
442    sub attrs {
443            my $self = shift;
444            #croak "attrs return array, not scalar" if (! wantarray);
445            return @{ $self->{attrs} };
446    }
447    
448    =head2 max
449    
450    Return maximum number of results.
451    
452      print $cond->max;
453    
454    C<-1> is returned for unitialized value, C<0> is unlimited.
455    
456    =cut
457    
458    sub max {
459            my $self = shift;
460            return $self->{max};
461    }
462    
463    =head2 options
464    
465    Return options for this condition.
466    
467      print $cond->options;
468    
469    Options are returned in numerical form.
470    
471    =cut
472    
473    sub options {
474            my $self = shift;
475            return $self->{options};
476    }
477    
478    
479    package Search::Estraier::ResultDocument;
480    
481    use Carp qw/croak/;
482    
483    #use Search::Estraier;
484    #our @ISA = qw/Search::Estraier/;
485    
486    =head1 Search::Estraier::ResultDocument
487    
488  =head2 new  =head2 new
489    
490  Create new connection to node master.    my $rdoc = new Search::HyperEstraier::ResultDocument(
491            uri => 'http://localhost/document/uri/42',
492            attrs => {
493                    foo => 1,
494                    bar => 2,
495            },
496            snippet => 'this is a text of snippet'
497            keywords => 'this\tare\tkeywords'
498      );
499    
500    =cut
501    
502    sub new {
503            my $class = shift;
504            my $self = {@_};
505            bless($self, $class);
506    
507            foreach my $f (qw/uri attrs snippet keywords/) {
508                    croak "missing $f for ResultDocument" unless defined($self->{$f});
509            }
510    
511            $self ? return $self : return undef;
512    }
513    
514    =head2 uri
515    
516    Return URI of result document
517    
518      print $rdoc->uri;
519    
520    =cut
521    
522    sub uri {
523            my $self = shift;
524            return $self->{uri};
525    }
526    
527    
528    =head2 attr_names
529    
530    Returns array with attribute names from result document object.
531    
532      my @attrs = $rdoc->attr_names;
533    
534    =cut
535    
536    sub attr_names {
537            my $self = shift;
538            croak "attr_names return array, not scalar" if (! wantarray);
539            return sort keys %{ $self->{attrs} };
540    }
541    
542    =head2 attr
543    
544    Returns value of an attribute.
545    
546      my $value = $rdoc->attr( 'attribute' );
547    
548    =cut
549    
550    sub attr {
551            my $self = shift;
552            my $name = shift || return;
553            return $self->{attrs}->{ $name };
554    }
555    
556    =head2 snippet
557    
558    Return snippet from result document
559    
560      print $rdoc->snippet;
561    
562    =cut
563    
564    my $master = new Search::Estraier::Master(  sub snippet {
565          url => 'http://localhost:1978',          my $self = shift;
566          user => 'admin',          return $self->{snippet};
567          passwd => 'admin',  }
568    
569    =head2 keywords
570    
571    Return keywords from result document
572    
573      print $rdoc->keywords;
574    
575    =cut
576    
577    sub keywords {
578            my $self = shift;
579            return $self->{keywords};
580    }
581    
582    
583    package Search::Estraier::NodeResult;
584    
585    use Carp qw/croak/;
586    
587    #use Search::Estraier;
588    #our @ISA = qw/Search::Estraier/;
589    
590    =head1 Search::Estraier::NodeResult
591    
592    =head2 new
593    
594      my $res = new Search::HyperEstraier::NodeResult(
595            docs => @array_of_rdocs,
596            hits => %hash_with_hints,
597    );    );
598    
599  =cut  =cut
# Line 293  sub new { Line 603  sub new {
603          my $self = {@_};          my $self = {@_};
604          bless($self, $class);          bless($self, $class);
605    
606          foreach my $p (qw/url user passwd/) {          foreach my $f (qw/docs hints/) {
607                  croak "need $p" unless ($self->{$p});                  croak "missing $f for ResultDocument" unless defined($self->{$f});
608          }          }
609    
610          $self ? return $self : return undef;          $self ? return $self : return undef;
611  }  }
612    
613    =head2 doc_num
614    
615    Return number of documents
616    
617      print $res->doc_num;
618    
619    =cut
620    
621    sub doc_num {
622            my $self = shift;
623            return $#{$self->{docs}};
624    }
625    
626    =head2 get_doc
627    
628    Return single document
629    
630      my $doc = $res->get_doc( 42 );
631    
632    Returns undef if document doesn't exist.
633    
634    =cut
635    
636    sub get_doc {
637            my $self = shift;
638            my $num = shift;
639            croak "expect number as argument" unless ($num =~ m/^\d+$/);
640            return undef if ($num < 0 || $num > $self->{docs});
641            return $self->{docs}->[$num];
642    }
643    
644    =head2 hint
645    
646    Return specific hint from results.
647    
648      print $rec->hint( 'VERSION' );
649    
650    Possible hints are: C<VERSION>, C<NODE>, C<HIT>, C<HINT#n>, C<DOCNUM>, C<WORDNUM>,
651    C<TIME>, C<LINK#n>, C<VIEW>.
652    
653    =cut
654    
655    sub hint {
656            my $self = shift;
657            my $key = shift || return;
658            return $self->{hints}->{$key};
659    }
660    
661    
662    package Search::Estraier::Node;
663    
664    use Carp qw/carp croak/;
665    use URI;
666    use MIME::Base64;
667    use IO::Socket::INET;
668    
669    =head1 Search::Estraier::Node
670    
671    =head2 new
672    
673      my $node = new Search::HyperEstraier::Node;
674    
675    =cut
676    
677    sub new {
678            my $class = shift;
679            my $self = {
680                    pxport => -1,
681                    timeout => 0,   # this used to be -1
682                    dnum => -1,
683                    wnum => -1,
684                    size => -1.0,
685                    wwidth => 480,
686                    hwidth => 96,
687                    awidth => 96,
688                    status => -1,
689            };
690            bless($self, $class);
691    
692            if (@_) {
693                    $self->{debug} = 1;
694                    warn "## Node debug on\n";
695            }
696    
697            $self ? return $self : return undef;
698    }
699    
700    =head2 set_url
701    
702    Specify URL to node server
703    
704      $node->set_url('http://localhost:1978');
705    
706    =cut
707    
708    sub set_url {
709            my $self = shift;
710            $self->{url} = shift;
711    }
712    
713    =head2 set_proxy
714    
715    Specify proxy server to connect to node server
716    
717      $node->set_proxy('proxy.example.com', 8080);
718    
719    =cut
720    
721    sub set_proxy {
722            my $self = shift;
723            my ($host,$port) = @_;
724            croak "proxy port must be number" unless ($port =~ m/^\d+$/);
725            $self->{pxhost} = $host;
726            $self->{pxport} = $port;
727    }
728    
729    =head2 set_timeout
730    
731    Specify timeout of connection in seconds
732    
733      $node->set_timeout( 15 );
734    
735    =cut
736    
737    sub set_timeout {
738            my $self = shift;
739            my $sec = shift;
740            croak "timeout must be number" unless ($sec =~ m/^\d+$/);
741            $self->{timeout} = $sec;
742    }
743    
744    =head2 set_auth
745    
746    Specify name and password for authentication to node server.
747    
748      $node->set_auth('clint','eastwood');
749    
750    =cut
751    
752    sub set_auth {
753            my $self = shift;
754            my ($login,$passwd) = @_;
755            my $basic_auth = encode_base64( "$login:$passwd" );
756            chomp($basic_auth);
757            $self->{auth} = $basic_auth;
758    }
759    
760    =head2 status
761    
762    Return status code of last request.
763    
764      print $node->status;
765    
766    C<-1> means connection failure.
767    
768    =cut
769    
770    sub status {
771            my $self = shift;
772            return $self->{status};
773    }
774    
775    =head2 put_doc
776    
777      $node->put_doc( $document_draft );
778    
779    =cut
780    
781    sub put_doc {
782            my $self = shift;
783            my $doc = shift || return;
784            $self->shuttle_url( $self->{url} . '/put_doc', 'text/x-estraier-draft', $doc->dump_draft, undef);
785    }
786    
787    =head2 shuttle_url
788    
789    This is method which uses C<IO::Socket::INET> to communicate with Hyper Estraier node
790    master.
791    
792      my $rv = shuttle_url( $url, $content_type, \$req_body, \$resbody );
793    
794    C<$resheads> and C<$resbody> booleans controll if response headers and/or response
795    body will be saved within object.
796    
797    =cut
798    
799    sub shuttle_url {
800            my $self = shift;
801    
802            my ($url, $content_type, $reqbody, $resbody) = @_;
803    
804            $self->{status} = -1;
805    
806            warn "## $url\n";
807    
808            $url = new URI($url);
809            if (
810                            !$url || !$url->scheme || !$url->scheme eq 'http' ||
811                            !$url->host || !$url->port || $url->port < 1
812                    ) {
813                    carp "can't parse $url\n";
814                    return -1;
815            }
816    
817            my ($host,$port,$query) = ($url->host, $url->port, $url->path);
818    
819            if ($self->{pxhost}) {
820                    ($host,$port) = ($self->{pxhost}, $self->{pxport});
821                    $query = "http://$host:$port/$query";
822            }
823    
824            $query .= '?' . $url->query if ($url->query && ! $reqbody);
825    
826            my $headers;
827    
828            if ($reqbody) {
829                    $headers .= "POST $query HTTP/1.0\r\n";
830            } else {
831                    $headers .= "GET $query HTTP/1.0\r\n";
832            }
833    
834            $headers .= "Host: " . $url->host . ":" . $url->port . "\r\n";
835            $headers .= "Connection: close\r\n";
836            $headers .= "User-Agent: Search-Estraier/$Search::Estraier::VERSION\r\n";
837            $headers .= "Content-Type: $content_type\r\n";
838            $headers .= "Authorization: Basic $self->{auth}\r\n";
839            my $len = 0;
840            {
841                    use bytes;
842                    $len = length($reqbody) if ($reqbody);
843            }
844            $headers .= "Content-Length: $len\r\n";
845            $headers .= "\r\n";
846    
847            my $sock = IO::Socket::INET->new(
848                    PeerAddr        => $host,
849                    PeerPort        => $port,
850                    Proto           => 'tcp',
851                    Timeout         => $self->{timeout} || 90,
852            );
853    
854            if (! $sock) {
855                    carp "can't open socket to $host:$port";
856                    return -1;
857            }
858    
859            warn $headers if ($self->{debug});
860    
861            print $sock $headers or
862                    carp "can't send headers to network:\n$headers\n" and return -1;
863    
864            if ($reqbody) {
865                    warn $reqbody if ($self->{debug});
866                    print $sock $reqbody or
867                            carp "can't send request body to network:\n$$reqbody\n" and return -1;
868            }
869    
870            my $line = <$sock>;
871            chomp($line);
872            my ($schema, $res_status, undef) = split(/  */, $line, 3);
873            return if ($schema !~ /^HTTP/ || ! $res_status);
874    
875            $self->{status} = $res_status;
876            warn "## response status: $res_status\n" if ($self->{debug});
877    
878            # skip rest of headers
879            $line = <$sock>;
880            while ($line) {
881                    $line = <$sock>;
882                    $line =~ s/[\r\n]+$//;
883                    warn "## ", $line || 'NULL', " ##\n" if ($self->{debug});
884            };
885    
886            # read body
887            $len = 0;
888            do {
889                    $len = read($sock, my $buf, 8192);
890                    $$resbody .= $buf if ($resbody);
891            } while ($len);
892    
893            warn "## response body:\n$$resbody\n" if ($resbody && $self->{debug});
894    
895            return $self->{status};
896    }
897    
898  ###  ###
899    
# Line 321  Dobrica Pavlinusic, E<lt>dpavlin@rot13.o Line 914  Dobrica Pavlinusic, E<lt>dpavlin@rot13.o
914    
915  =head1 COPYRIGHT AND LICENSE  =head1 COPYRIGHT AND LICENSE
916    
917  Copyright (C) 2005 by Dobrica Pavlinusic  Copyright (C) 2005-2006 by Dobrica Pavlinusic
918    
919  This library is free software; you can redistribute it and/or modify  This library is free software; you can redistribute it and/or modify
920  it under the GPL v2 or later.  it under the GPL v2 or later.

Legend:
Removed from v.12  
changed lines
  Added in v.40

  ViewVC Help
Powered by ViewVC 1.1.26