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

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

revision 47 by dpavlin, Fri Jan 6 01:51:28 2006 UTC revision 63 by dpavlin, Sat Jan 7 16:19:31 2006 UTC
# Line 4  use 5.008; Line 4  use 5.008;
4  use strict;  use strict;
5  use warnings;  use warnings;
6    
7  our $VERSION = '0.00';  our $VERSION = '0.01';
8    
9  =head1 NAME  =head1 NAME
10    
# Line 205  Returns array with attribute names from Line 205  Returns array with attribute names from
205    
206  sub attr_names {  sub attr_names {
207          my $self = shift;          my $self = shift;
208          croak "attr_names return array, not scalar" if (! wantarray);          return unless ($self->{attrs});
209            #croak "attr_names return array, not scalar" if (! wantarray);
210          return sort keys %{ $self->{attrs} };          return sort keys %{ $self->{attrs} };
211  }  }
212    
# Line 221  Returns value of an attribute. Line 222  Returns value of an attribute.
222  sub attr {  sub attr {
223          my $self = shift;          my $self = shift;
224          my $name = shift;          my $name = shift;
225            return unless (defined($name) && $self->{attrs});
226          return $self->{'attrs'}->{ $name };          return $self->{attrs}->{ $name };
227  }  }
228    
229    
# Line 236  Returns array with text sentences. Line 237  Returns array with text sentences.
237    
238  sub texts {  sub texts {
239          my $self = shift;          my $self = shift;
240          confess "texts return array, not scalar" if (! wantarray);          #confess "texts return array, not scalar" if (! wantarray);
241          return @{ $self->{dtexts} };          return @{ $self->{dtexts} } if ($self->{dtexts});
242  }  }
243    
244    
# Line 251  Return whole text as single scalar. Line 252  Return whole text as single scalar.
252    
253  sub cat_texts {  sub cat_texts {
254          my $self = shift;          my $self = shift;
255          return join(' ',@{ $self->{dtexts} });          return join(' ',@{ $self->{dtexts} }) if ($self->{dtexts});
256  }  }
257    
258    
# Line 460  Return search result attrs. Line 461  Return search result attrs.
461  sub attrs {  sub attrs {
462          my $self = shift;          my $self = shift;
463          #croak "attrs return array, not scalar" if (! wantarray);          #croak "attrs return array, not scalar" if (! wantarray);
464          return @{ $self->{attrs} };          return @{ $self->{attrs} } if ($self->{attrs});
465  }  }
466    
467    
# Line 524  sub new { Line 525  sub new {
525          my $self = {@_};          my $self = {@_};
526          bless($self, $class);          bless($self, $class);
527    
528          foreach my $f (qw/uri attrs snippet keywords/) {          croak "missing uri for ResultDocument" unless defined($self->{uri});
                 croak "missing $f for ResultDocument" unless defined($self->{$f});  
         }  
529    
530          $self ? return $self : return undef;          $self ? return $self : return undef;
531  }  }
# Line 645  Return number of documents Line 644  Return number of documents
644    
645  sub doc_num {  sub doc_num {
646          my $self = shift;          my $self = shift;
647          return $#{$self->{docs}};          return $#{$self->{docs}} + 1;
648  }  }
649    
650    
# Line 692  use Carp qw/carp croak confess/; Line 691  use Carp qw/carp croak confess/;
691  use URI;  use URI;
692  use MIME::Base64;  use MIME::Base64;
693  use IO::Socket::INET;  use IO::Socket::INET;
694    use URI::Escape qw/uri_escape/;
695    
696  =head1 Search::Estraier::Node  =head1 Search::Estraier::Node
697    
# Line 716  sub new { Line 716  sub new {
716          };          };
717          bless($self, $class);          bless($self, $class);
718    
719          if (@_) {          my $args = {@_};
720                  $self->{debug} = shift;  
721                  warn "## Node debug on\n";          $self->{debug} = $args->{debug};
722          }          warn "## Node debug on\n" if ($self->{debug});
723    
724          $self ? return $self : return undef;          $self ? return $self : return undef;
725  }  }
# Line 866  sub out_doc_by_uri { Line 866  sub out_doc_by_uri {
866          return unless ($self->{url});          return unless ($self->{url});
867          $self->shuttle_url( $self->{url} . '/out_doc',          $self->shuttle_url( $self->{url} . '/out_doc',
868                  'application/x-www-form-urlencoded',                  'application/x-www-form-urlencoded',
869                  "uri=$uri",                  "uri=" . uri_escape($uri),
870                  undef                  undef
871          ) == 200;          ) == 200;
872  }  }
# Line 928  sub get_doc_by_uri { Line 928  sub get_doc_by_uri {
928  }  }
929    
930    
931    =head2 get_doc_attr
932    
933    Retrieve the value of an atribute from object
934    
935      my $val = $node->get_doc_attr( document_id, 'attribute_name' ) or
936            die "can't get document attribute";
937    
938    =cut
939    
940    sub get_doc_attr {
941            my $self = shift;
942            my ($id,$name) = @_;
943            return unless ($id && $name);
944            return $self->_fetch_doc( id => $id, attr => $name );
945    }
946    
947    
948    =head2 get_doc_attr_by_uri
949    
950    Retrieve the value of an atribute from object
951    
952      my $val = $node->get_doc_attr_by_uri( document_id, 'attribute_name' ) or
953            die "can't get document attribute";
954    
955    =cut
956    
957    sub get_doc_attr_by_uri {
958            my $self = shift;
959            my ($uri,$name) = @_;
960            return unless ($uri && $name);
961            return $self->_fetch_doc( uri => $uri, attr => $name );
962    }
963    
964    
965  =head2 etch_doc  =head2 etch_doc
966    
967  Exctract document keywords  Exctract document keywords
# Line 936  Exctract document keywords Line 970  Exctract document keywords
970    
971  =cut  =cut
972    
973  sub erch_doc {  sub etch_doc {
974          my $self = shift;          my $self = shift;
975          my $id = shift || return;          my $id = shift || return;
976          return $self->_fetch_doc( id => $id, etch => 1 );          return $self->_fetch_doc( id => $id, etch => 1 );
# Line 987  C<etch_doc>, C<etch_doc_by_uri>. Line 1021  C<etch_doc>, C<etch_doc_by_uri>.
1021   my $doc = $node->_fetch_doc( id => 42, etch => 1 );   my $doc = $node->_fetch_doc( id => 42, etch => 1 );
1022   my $doc = $node->_fetch_doc( uri => 'file:///document/uri/42', etch => 1 );   my $doc = $node->_fetch_doc( uri => 'file:///document/uri/42', etch => 1 );
1023    
1024     # to get document attrubute add attr
1025     my $doc = $node->_fetch_doc( id => 42, attr => '@mdate' );
1026     my $doc = $node->_fetch_doc( uri => 'file:///document/uri/42', attr => '@mdate' );
1027    
1028   # more general form which allows implementation of   # more general form which allows implementation of
1029   # uri_to_id   # uri_to_id
1030   my $id = $node->_fetch_doc(   my $id = $node->_fetch_doc(
# Line 1011  sub _fetch_doc { Line 1049  sub _fetch_doc {
1049                  croak "id must be numberm not '$a->{id}'" unless ($a->{id} =~ m/^\d+$/);                  croak "id must be numberm not '$a->{id}'" unless ($a->{id} =~ m/^\d+$/);
1050                  $arg = 'id=' . $a->{id};                  $arg = 'id=' . $a->{id};
1051          } elsif ($a->{uri}) {          } elsif ($a->{uri}) {
1052                  $arg = 'uri=' . $a->{uri};                  $arg = 'uri=' . uri_escape($a->{uri});
1053          } else {          } else {
1054                  confess "unhandled argument. Need id or uri.";                  confess "unhandled argument. Need id or uri.";
1055          }          }
1056    
1057            if ($a->{attr}) {
1058                    $path = '/get_doc_attr';
1059                    $arg .= '&attr=' . uri_escape($a->{attr});
1060                    $a->{chomp_resbody} = 1;
1061            }
1062    
1063          my $rv = $self->shuttle_url( $self->{url} . $path,          my $rv = $self->shuttle_url( $self->{url} . $path,
1064                  'application/x-www-form-urlencoded',                  'application/x-www-form-urlencoded',
1065                  $arg,                  $arg,
# Line 1042  sub _fetch_doc { Line 1086  sub _fetch_doc {
1086  }  }
1087    
1088    
1089    =head2 name
1090    
1091      my $node_name = $node->name;
1092    
1093    =cut
1094    
1095    sub name {
1096            my $self = shift;
1097            $self->_set_info unless ($self->{name});
1098            return $self->{name};
1099    }
1100    
1101    
1102    =head2 label
1103    
1104      my $node_label = $node->label;
1105    
1106    =cut
1107    
1108    sub label {
1109            my $self = shift;
1110            $self->_set_info unless ($self->{label});
1111            return $self->{label};
1112    }
1113    
1114    
1115    =head2 doc_num
1116    
1117      my $documents_in_node = $node->doc_num;
1118    
1119    =cut
1120    
1121    sub doc_num {
1122            my $self = shift;
1123            $self->_set_info if ($self->{dnum} < 0);
1124            return $self->{dnum};
1125    }
1126    
1127    
1128    =head2 word_num
1129    
1130      my $words_in_node = $node->word_num;
1131    
1132    =cut
1133    
1134    sub word_num {
1135            my $self = shift;
1136            $self->_set_info if ($self->{wnum} < 0);
1137            return $self->{wnum};
1138    }
1139    
1140    
1141    =head2 size
1142    
1143      my $node_size = $node->size;
1144    
1145    =cut
1146    
1147    sub size {
1148            my $self = shift;
1149            $self->_set_info if ($self->{size} < 0);
1150            return $self->{size};
1151    }
1152    
1153    
1154    =head2 search
1155    
1156    Search documents which match condition
1157    
1158      my $nres = $node->search( $cond, $depth );
1159    
1160    C<$cond> is C<Search::Estraier::Condition> object, while <$depth> specifies
1161    depth for meta search.
1162    
1163    Function results C<Search::Estraier::NodeResult> object.
1164    
1165    =cut
1166    
1167    sub search {
1168            my $self = shift;
1169            my ($cond, $depth) = @_;
1170            return unless ($cond && defined($depth) && $self->{url});
1171            croak "cond mush be Search::Estraier::Condition, not '$cond->isa'" unless ($cond->isa('Search::Estraier::Condition'));
1172            croak "depth needs number, not '$depth'" unless ($depth =~ m/^\d+$/);
1173    
1174            my $resbody;
1175    
1176            my $rv = $self->shuttle_url( $self->{url} . '/search',
1177                    'application/x-www-form-urlencoded',
1178                    $self->cond_to_query( $cond, $depth ),
1179                    \$resbody,
1180            );
1181            return if ($rv != 200);
1182    
1183            my (@docs, $hints);
1184    
1185            my @lines = split(/\n/, $resbody);
1186            return unless (@lines);
1187    
1188            my $border = $lines[0];
1189            my $isend = 0;
1190            my $lnum = 1;
1191    
1192            while ( $lnum <= $#lines ) {
1193                    my $line = $lines[$lnum];
1194                    $lnum++;
1195    
1196                    #warn "## $line\n";
1197                    if ($line && $line =~ m/^\Q$border\E(:END)*$/) {
1198                            $isend = $1;
1199                            last;
1200                    }
1201    
1202                    if ($line =~ /\t/) {
1203                            my ($k,$v) = split(/\t/, $line, 2);
1204                            $hints->{$k} = $v;
1205                    }
1206            }
1207    
1208            my $snum = $lnum;
1209    
1210            while( ! $isend && $lnum <= $#lines ) {
1211                    my $line = $lines[$lnum];
1212                    #warn "# $lnum: $line\n";
1213                    $lnum++;
1214    
1215                    if ($line && $line =~ m/^\Q$border\E/) {
1216                            if ($lnum > $snum) {
1217                                    my $rdattrs;
1218                                    my $rdvector;
1219                                    my $rdsnippet;
1220                                    
1221                                    my $rlnum = $snum;
1222                                    while ($rlnum < $lnum - 1 ) {
1223                                            #my $rdline = $self->_s($lines[$rlnum]);
1224                                            my $rdline = $lines[$rlnum];
1225                                            $rlnum++;
1226                                            last unless ($rdline);
1227                                            if ($rdline =~ /^%/) {
1228                                                    $rdvector = $1 if ($rdline =~ /^%VECTOR\t(.+)$/);
1229                                            } elsif($rdline =~ /=/) {
1230                                                    $rdattrs->{$1} = $2 if ($rdline =~ /^(.+)=(.+)$/);
1231                                            } else {
1232                                                    confess "invalid format of response";
1233                                            }
1234                                    }
1235                                    while($rlnum < $lnum - 1) {
1236                                            my $rdline = $lines[$rlnum];
1237                                            $rlnum++;
1238                                            $rdsnippet .= "$rdline\n";
1239                                    }
1240                                    #warn Dumper($rdvector, $rdattrs, $rdsnippet);
1241                                    if (my $rduri = $rdattrs->{'@uri'}) {
1242                                            push @docs, new Search::Estraier::ResultDocument(
1243                                                    uri => $rduri,
1244                                                    attrs => $rdattrs,
1245                                                    snippet => $rdsnippet,
1246                                                    keywords => $rdvector,
1247                                            );
1248                                    }
1249                            }
1250                            $snum = $lnum;
1251                            #warn "### $line\n";
1252                            $isend = 1 if ($line =~ /:END$/);
1253                    }
1254    
1255            }
1256    
1257            if (! $isend) {
1258                    warn "received result doesn't have :END\n$resbody";
1259                    return;
1260            }
1261    
1262            #warn Dumper(\@docs, $hints);
1263    
1264            return new Search::Estraier::NodeResult( docs => \@docs, hints => $hints );
1265    }
1266    
1267    
1268    =head2 cond_to_query
1269    
1270    Return URI encoded string generated from Search::Estraier::Condition
1271    
1272      my $args = $node->cond_to_query( $cond, $depth );
1273    
1274    =cut
1275    
1276    sub cond_to_query {
1277            my $self = shift;
1278    
1279            my $cond = shift || return;
1280            croak "condition must be Search::Estraier::Condition, not '$cond->isa'" unless ($cond->isa('Search::Estraier::Condition'));
1281            my $depth = shift;
1282    
1283            my @args;
1284    
1285            if (my $phrase = $cond->phrase) {
1286                    push @args, 'phrase=' . uri_escape($phrase);
1287            }
1288    
1289            if (my @attrs = $cond->attrs) {
1290                    for my $i ( 0 .. $#attrs ) {
1291                            push @args,'attr' . ($i+1) . '=' . uri_escape( $attrs[$i] ) if ($attrs[$i]);
1292                    }
1293            }
1294    
1295            if (my $order = $cond->order) {
1296                    push @args, 'order=' . uri_escape($order);
1297            }
1298                    
1299            if (my $max = $cond->max) {
1300                    push @args, 'max=' . $max;
1301            } else {
1302                    push @args, 'max=' . (1 << 30);
1303            }
1304    
1305            if (my $options = $cond->options) {
1306                    push @args, 'options=' . $options;
1307            }
1308    
1309            push @args, 'depth=' . $depth if ($depth);
1310            push @args, 'wwidth=' . $self->{wwidth};
1311            push @args, 'hwidth=' . $self->{hwidth};
1312            push @args, 'awidth=' . $self->{awidth};
1313    
1314            return join('&', @args);
1315    }
1316    
1317    
1318  =head2 shuttle_url  =head2 shuttle_url
# Line 1049  sub _fetch_doc { Line 1320  sub _fetch_doc {
1320  This is method which uses C<IO::Socket::INET> to communicate with Hyper Estraier node  This is method which uses C<IO::Socket::INET> to communicate with Hyper Estraier node
1321  master.  master.
1322    
1323    my $rv = shuttle_url( $url, $content_type, \$req_body, \$resbody );    my $rv = shuttle_url( $url, $content_type, $req_body, \$resbody );
1324    
1325  C<$resheads> and C<$resbody> booleans controll if response headers and/or response  C<$resheads> and C<$resbody> booleans controll if response headers and/or response
1326  body will be saved within object.  body will be saved within object.
1327    
1328  =cut  =cut
1329    
1330    use LWP::UserAgent;
1331    
1332  sub shuttle_url {  sub shuttle_url {
1333          my $self = shift;          my $self = shift;
1334    
# Line 1074  sub shuttle_url { Line 1347  sub shuttle_url {
1347                  return -1;                  return -1;
1348          }          }
1349    
1350          my ($host,$port,$query) = ($url->host, $url->port, $url->path);          my $ua = LWP::UserAgent->new;
1351            $ua->agent( "Search-Estraier/$Search::Estraier::VERSION" );
         if ($self->{pxhost}) {  
                 ($host,$port) = ($self->{pxhost}, $self->{pxport});  
                 $query = "http://$host:$port/$query";  
         }  
   
         $query .= '?' . $url->query if ($url->query && ! $reqbody);  
   
         my $headers;  
1352    
1353            my $req;
1354          if ($reqbody) {          if ($reqbody) {
1355                  $headers .= "POST $query HTTP/1.0\r\n";                  $req = HTTP::Request->new(POST => $url);
1356          } else {          } else {
1357                  $headers .= "GET $query HTTP/1.0\r\n";                  $req = HTTP::Request->new(GET => $url);
1358          }          }
1359    
1360          $headers .= "Host: " . $url->host . ":" . $url->port . "\r\n";          $req->headers->header( 'Host' => $url->host . ":" . $url->port );
1361          $headers .= "Connection: close\r\n";          $req->headers->header( 'Connection', 'close' );
1362          $headers .= "User-Agent: Search-Estraier/$Search::Estraier::VERSION\r\n";          $req->headers->header( 'Authorization', 'Basic ' . $self->{auth} );
1363          $headers .= "Content-Type: $content_type\r\n";          $req->content_type( $content_type );
         $headers .= "Authorization: Basic $self->{auth}\r\n";  
         my $len = 0;  
         {  
                 use bytes;  
                 $len = length($reqbody) if ($reqbody);  
         }  
         $headers .= "Content-Length: $len\r\n";  
         $headers .= "\r\n";  
1364    
1365          my $sock = IO::Socket::INET->new(          warn $req->headers->as_string,"\n" if ($self->{debug});
                 PeerAddr        => $host,  
                 PeerPort        => $port,  
                 Proto           => 'tcp',  
                 Timeout         => $self->{timeout} || 90,  
         );  
1366    
1367          if (! $sock) {          if ($reqbody) {
1368                  carp "can't open socket to $host:$port";                  warn "$reqbody\n" if ($self->{debug});
1369                  return -1;                  $req->content( $reqbody );
1370          }          }
1371    
1372          warn $headers if ($self->{debug});          my $res = $ua->request($req) || croak "can't make request to $url: $!";
1373    
1374          print $sock $headers or          warn "## response status: ",$res->status_line,"\n" if ($self->{debug});
                 carp "can't send headers to network:\n$headers\n" and return -1;  
1375    
1376          if ($reqbody) {          return -1 if (! $res->is_success);
                 warn "$reqbody\n" if ($self->{debug});  
                 print $sock $reqbody or  
                         carp "can't send request body to network:\n$$reqbody\n" and return -1;  
         }  
1377    
1378          my $line = <$sock>;          ($self->{status}, $self->{status_message}) = split(/\s+/, $res->status_line, 2);
         chomp($line);  
         my ($schema, $res_status, undef) = split(/  */, $line, 3);  
         return if ($schema !~ /^HTTP/ || ! $res_status);  
   
         $self->{status} = $res_status;  
         warn "## response status: $res_status\n" if ($self->{debug});  
   
         # skip rest of headers  
         $line = <$sock>;  
         while ($line) {  
                 $line = <$sock>;  
                 $line =~ s/[\r\n]+$//;  
                 warn "## ", $line || 'NULL', " ##\n" if ($self->{debug});  
         };  
1379    
1380          # read body          $$resbody .= $res->content;
         $len = 0;  
         do {  
                 $len = read($sock, my $buf, 8192);  
                 $$resbody .= $buf if ($resbody);  
         } while ($len);  
1381    
1382          warn "## response body:\n$$resbody\n" if ($resbody && $self->{debug});          warn "## response body:\n$$resbody\n" if ($resbody && $self->{debug});
1383    
1384          return $self->{status};          return $self->{status};
1385  }  }
1386    
1387    
1388    =head2 set_snippet_width
1389    
1390    Set width of snippets in results
1391    
1392      $node->set_snippet_width( $wwidth, $hwidth, $awidth );
1393    
1394    C<$wwidth> specifies whole width of snippet. It's C<480> by default. If it's C<0> snippet
1395    is not sent with results. If it is negative, whole document text is sent instead of snippet.
1396    
1397    C<$hwidth> specified width of strings from beginning of string. Default
1398    value is C<96>. Negative or zero value keep previous value.
1399    
1400    C<$awidth> specifies width of strings around each highlighted word. It's C<96> by default.
1401    If negative of zero value is provided previous value is kept unchanged.
1402    
1403    =cut
1404    
1405    sub set_snippet_width {
1406            my $self = shift;
1407    
1408            my ($wwidth, $hwidth, $awidth) = @_;
1409            $self->{wwidth} = $wwidth;
1410            $self->{hwidth} = $hwidth if ($hwidth >= 0);
1411            $self->{awidth} = $awidth if ($awidth >= 0);
1412    }
1413    
1414    
1415    =head2 set_user
1416    
1417    Manage users of node
1418    
1419      $node->set_user( 'name', $mode );
1420    
1421    C<$mode> can be one of:
1422    
1423    =over 4
1424    
1425    =item 0
1426    
1427    delete account
1428    
1429    =item 1
1430    
1431    set administrative right for user
1432    
1433    =item 2
1434    
1435    set user account as guest
1436    
1437    =back
1438    
1439    Return true on success, otherwise false.
1440    
1441    =cut
1442    
1443    sub set_user {
1444            my $self = shift;
1445            my ($name, $mode) = @_;
1446    
1447            return unless ($self->{url});
1448            croak "mode must be number, not '$mode'" unless ($mode =~ m/^\d+$/);
1449    
1450            $self->shuttle_url( $self->{url} . '/_set_user',
1451                    'text/plain',
1452                    'name=' . uri_escape($name) . '&mode=' . $mode,
1453                    undef
1454            ) == 200;
1455    }
1456    
1457    
1458    =head2 set_link
1459    
1460    Manage node links
1461    
1462      $node->set_link('http://localhost:1978/node/another', 'another node label', $credit);
1463    
1464    If C<$credit> is negative, link is removed.
1465    
1466    =cut
1467    
1468    sub set_link {
1469            my $self = shift;
1470            my ($url, $label, $credit) = @_;
1471    
1472            return unless ($self->{url});
1473            croak "mode credit be number, not '$credit'" unless ($credit =~ m/^\d+$/);
1474    
1475            my $reqbody = 'url=' . uri_escape($url) . '&label=' . uri_escape($label);
1476            $reqbody .= '&credit=' . $credit if ($credit > 0);
1477    
1478            $self->shuttle_url( $self->{url} . '/_set_link',
1479                    'text/plain',
1480                    $reqbody,
1481                    undef
1482            ) == 200;
1483    }
1484    
1485    
1486    =head1 PRIVATE METHODS
1487    
1488    You could call those directly, but you don't have to. I hope.
1489    
1490    =head2 _set_info
1491    
1492    Set information for node
1493    
1494      $node->_set_info;
1495    
1496    =cut
1497    
1498    sub _set_info {
1499            my $self = shift;
1500    
1501            $self->{status} = -1;
1502            return unless ($self->{url});
1503    
1504            my $resbody;
1505            my $rv = $self->shuttle_url( $self->{url} . '/inform',
1506                    'text/plain',
1507                    undef,
1508                    \$resbody,
1509            );
1510    
1511            return if ($rv != 200 || !$resbody);
1512    
1513            # it seems that response can have multiple line endings
1514            $resbody =~ s/[\r\n]+$//;
1515    
1516            ( $self->{name}, $self->{label}, $self->{dnum}, $self->{wnum}, $self->{size} ) =
1517                    split(/\t/, $resbody, 5);
1518    
1519    }
1520    
1521  ###  ###
1522    
1523  =head1 EXPORT  =head1 EXPORT

Legend:
Removed from v.47  
changed lines
  Added in v.63

  ViewVC Help
Powered by ViewVC 1.1.26