Dezi-App

 view release on metacpan or  search on metacpan

lib/Dezi/Aggregator/Spider.pm  view on Meta::CPAN

package Dezi::Aggregator::Spider;
use Moose;
extends 'Dezi::Aggregator';
use Carp;
use Scalar::Util qw( blessed );
use URI;
use HTTP::Cookies;
use Types::Standard qw( InstanceOf Maybe Int CodeRef Str Bool ArrayRef );
use Dezi::Types qw( DeziFileRules DeziEpoch );
use Dezi::Utils;
use Dezi::Queue;
use Dezi::Cache;
use Dezi::Aggregator::Spider::UA;
use Search::Tools::UTF8;
use XML::Feed;
use WWW::Sitemap::XML;
use File::Rules;
use Class::Load;

#
# TODO tests for cookies, non-text urls needing filters
#
#

has 'agent' => (
    is      => 'rw',
    isa     => Str,
    default => sub {'dezi-spider http://dezi.org/'},
);
has 'authn_callback'     => ( is => 'rw', isa => CodeRef );
has 'credential_timeout' => ( is => 'rw', isa => Int, default => sub {30} );
has 'credentials'        => ( is => 'rw', isa => Str );
has 'delay'              => ( is => 'rw', isa => Int, default => sub {5} );
has 'email' => (
    is      => 'rw',
    isa     => Str,
    default => sub {'dezi@user.failed.to.set.email.invalid'},
);
has 'file_rules' => ( is => 'rw', isa => DeziFileRules, coerce => 1, );
has 'follow_redirects' => ( is => 'rw', isa => Bool, default => sub {1} );
has 'keep_alive' => ( is => 'rw', isa => Bool, default => sub {0} );

# whitelist which HTML tags we consider "links"
# should be subset of what HTML::LinkExtor considers links
has 'link_tags' => (
    is      => 'rw',
    isa     => ArrayRef,
    default => sub { [ 'a', 'frame', 'iframe' ] }
);

has 'max_depth' => ( is => 'rw', isa => Maybe [Int] );
has 'max_files' => ( is => 'rw', isa => Int, default => sub {0} );
has 'max_size'  => ( is => 'rw', isa => Int, default => sub {5_000_000} );
has 'max_time' => ( is => 'rw', isa => Int, );    # TODO
has 'md5_cache' => (
    is      => 'rw',
    isa     => InstanceOf ['Dezi::Cache'],
    default => sub { Dezi::Cache->new }
);
has 'modified_since' => ( is => 'rw', isa => DeziEpoch, coerce => 1, );
has 'queue' => (
    is      => 'rw',
    isa     => InstanceOf ['Dezi::Queue'],
    default => sub { Dezi::Queue->new }
);
has 'remove_leading_dots' => ( is => 'rw', isa => Bool, default => sub {1} );
has 'same_hosts' => ( is => 'rw', isa => ArrayRef, default => sub { [] } );
has 'timeout'    => ( is => 'rw', isa => Int,      default => sub {30} );
has 'ua' => ( is => 'rw', isa => InstanceOf ['LWP::UserAgent'] );
has 'uri_cache' => (
    is      => 'rw',
    isa     => InstanceOf ['Dezi::Cache'],
    default => sub { Dezi::Cache->new },
);
has 'use_md5'     => ( is => 'rw', isa => Bool, default => sub {0} );
has 'use_cookies' => ( is => 'rw', isa => Bool, default => sub {1} );

#use LWP::Debug qw(+);

our $VERSION = '0.016';

# shortcut
my $UTILS = 'Dezi::Utils';

=pod

=head1 NAME

Dezi::Aggregator::Spider - web aggregator

=head1 SYNOPSIS

lib/Dezi/Aggregator/Spider.pm  view on Meta::CPAN

Default is unlimited depth.

=item max_time I<n>

This optional key will set the max minutes to spider.   Spidering
for this host will stop after C<max_time> seconds, and move on to the
next server, if any.  The default is to not limit by time.

=item max_files I<n>

This optional key sets the max number of files to spider before aborting.
The default is to not limit by number of files.  This is the number of requests
made to the remote server, not the total number of files to index (see C<max_indexed>).
This count is displayed at the end of indexing as C<Unique URLs>.

This feature can (and perhaps should) be use when spidering a web site where dynamic
content may generate unique URLs to prevent run-away spidering.

=item max_size I<n>

This optional key sets the max size of a file read from the web server.
This B<defaults> to 5,000,000 bytes.  If the size is exceeded the resource is
truncated per LWP::UserAgent.

Set max_size to zero for unlimited size.

=item modified_since I<date>

This optional parameter will skip any URIs that do not report having
been modified since I<date>. The C<Last-Modified> HTTP header is used to
determine modification time.

=item keep_alive I<1|0>

This optional parameter will enable keep alive requests.  This can dramatically speed
up spidering and reduce the load on server being spidered.  The default is to not use
keep alives, although enabling it will probably be the right thing to do.

To get the most out of keep alives, you may want to set up your web server to
allow a lot of requests per single connection (i.e MaxKeepAliveRequests on Apache).
Apache's default is 100, which should be good.

When a connection is not closed the spider does not wait the "delay"
time when making the next request.  In other words, there is no delay in
requesting documents while the connection is open.

Note: you must have at least libwww-perl-5.53_90 installed to use this feature.

=item delay I<n>

Get/set the number of seconds to wait between making requests. Default is
5 seconds (a very friendly delay).

=item timeout I<n>

Get/set the number of seconds to wait before considering the remote
server unresponsive. The default is 10.

=item authn_callback I<code_ref>

CODE reference to fetch username/password credentials when necessary. See also
C<credentials>.

=item credential_timeout I<n>

Number of seconds to wait before skipping manual prompt for username/password.

=item credentials I<user:pass>

String with C<username>:C<password> pair to be used when prompted by
the server.

=item follow_redirects I<1|0>

By default, 3xx responses from the server will be followed when
they are on the same hostname. Set to false (0) to not follow
redirects.

=item link_tags

TODO

=item remove_leading_dots I<1|0>

Microsoft server hack.

=item same_hosts I<array_ref>

ARRAY ref of hostnames to be treated as identical to the original
host being spidered. By default the spider will not follow
links to different hosts.

=back

=head2 BUILD

Initializes a new spider object. Called by new().

=cut

sub BUILD {
    my $self = shift;

    $self->{_auth_cache} = Dezi::Cache->new;    # ALWAYS inmemory cache

    $self->{ua}
        ||= Dezi::Aggregator::Spider::UA->new( $self->agent, $self->email, );

    $self->{ua}
        ->set_link_tags( { map { lc($_) => 1 } @{ $self->{link_tags} } } );

    # we handle our own delay
    $self->{ua}->delay(0);

    $self->{ua}->timeout( $self->timeout );

    # TODO we test this using HEAD request. Set here too?
    #$self->{ua}->max_size( $self->{max_size} ) if $self->{max_size};

    if ( $self->use_cookies ) {
        $self->{ua}->cookie_jar( HTTP::Cookies->new() );
    }
    if ( $self->keep_alive ) {
        if ( $self->{ua}->can('conn_cache') ) {
            $self->{ua}
                ->conn_cache( { total_capacity => $self->keep_alive } );
        }
        else {

lib/Dezi/Aggregator/Spider.pm  view on Meta::CPAN


# ported from spider.pl
# Do we need to authorize?  If so, ask for password and request again.
# First we try using any cached value
# Then we try using the get_password callback
# Then we ask.

sub _authorize {
    my ( $self, $uri, $response ) = @_;

    delete $self->{last_auth};    # since we know that doesn't work

    if (   $response->header('WWW-Authenticate')
        && $response->header('WWW-Authenticate') =~ /realm="([^"]+)"/i )
    {
        my $realm = $1;
        my $user_pass;

        # Do we have a cached user/pass for this realm?
        # only each URI only once
        unless ( $self->{_request}->{auth}->{$uri}++ ) {
            my $key = $uri->canonical->host_port . ':' . $realm;

            if ( $user_pass = $self->{_auth_cache}->get($key) ) {

                # If we didn't just try it, try again
                unless ( $uri->userinfo && $user_pass eq $uri->userinfo ) {

                    # add the user/pass to the URI
                    $uri->userinfo($user_pass);

                   #warn " >> set userinfo via _auth_cache\n" if $self->debug;
                    return 1;
                }
                else {
                    # we've tried this before
                    #warn "tried $user_pass before";
                    return 0;
                }
            }
        }

        # now check for a callback password (if $user_pass not set)
        unless ( $user_pass || $self->{_request}->{auth}->{callback}++ ) {

            # Check for a callback function
            if ( $self->{authn_callback}
                and ref $self->{authn_callback} eq 'CODE' )
            {
                $user_pass = $self->{authn_callback}
                    ->( $self, $uri, $response, $realm );
                $uri->userinfo($user_pass);

                #warn " >> set userinfo via authn_callback\n" if $self->debug;
                return 1;
            }
        }

        # otherwise, prompt (over and over)
        if ( !$user_pass ) {
            $user_pass = $self->_get_basic_credentials( $uri, $realm );
        }

        if ($user_pass) {
            $uri->userinfo($user_pass);
            $self->{cur_realm} = $realm;  # save so we can cache if it's valid
            return 1;
        }
    }

    return 0;

}

# From spider.pl
sub _get_basic_credentials {
    my ( $self, $uri, $realm ) = @_;

    # Exists but undefined means don't ask.
    return
        if exists $self->{credential_timeout}
        && !defined $self->{credential_timeout};

    my $netloc = $uri->canonical->host_port;

    my ( $user, $password );

    eval {
        local $SIG{ALRM} = sub { die "timed out\n" };

        # a zero timeout means don't time out
        alarm( $self->{credential_timeout} ) unless $^O =~ /Win32/i;

        if ( $uri->userinfo ) {
            print STDERR "\nSorry: invalid username/password\n";
            $uri->userinfo(undef);
        }

        print STDERR
            "Need Authentication for $uri at realm '$realm'\n(<Enter> skips)\nUsername: ";
        $user = <STDIN>;
        chomp($user) if $user;
        die "No Username specified\n" unless length $user;

        alarm( $self->{credential_timeout} ) unless $^O =~ /Win32/i;

        print STDERR "Password: ";
        system("stty -echo");
        $password = <STDIN>;
        system("stty echo");
        print STDERR "\n";    # because we disabled echo
        chomp($password);
        alarm(0) unless $^O =~ /Win32/i;
    };

    alarm(0) unless $^O =~ /Win32/i;

    return if $@;

    return join ':', $user, $password;

}

=head2 add_to_queue( I<uri> )

Add I<uri> to the queue.

=cut

sub add_to_queue {
    my $self = shift;
    my $uri = shift or croak "uri required";
    return $self->queue->put($uri);
}

=head2 next_from_queue

lib/Dezi/Aggregator/Spider.pm  view on Meta::CPAN

sub left_in_queue {
    return shift->queue->size();
}

=head2 remove_from_queue( I<uri> )

Calls queue()->remove(I<uri>).

=cut

sub remove_from_queue {
    my $self = shift;
    my $uri = shift or croak "uri required";
    return $self->queue->remove($uri);
}

=head2 get_doc

Returns the next URI from the queue() as a Dezi::Indexer::Doc object,
or the error message if there was one.

Returns undef if the queue is empty or max_depth() has been reached.

=cut

sub get_doc {
    my $self = shift;

    # return unless we have something in the queue
    return unless $self->left_in_queue();

    # pop the queue and make it a URI
    my $uri   = $self->next_from_queue();
    my $depth = $self->uri_cache->get("$uri");

    $self->debug
        and $self->write_log(
        uri => $uri,
        msg => sprintf(
            "depth:%d max_depth:%s",
            $depth, ( $self->max_depth || 'undef' )
        ),
        );

    return if defined $self->max_depth && $depth > $self->max_depth;

    $self->{_cur_depth} = $depth;

    my $doc = $self->_make_request($uri);

    if ($doc) {
        $self->remove_from_queue($uri);
    }

    return $doc;
}

=head2 get_authorized_doc( I<uri>, I<response> )

Called internally when the server returns a 401 or 403 response.
Will attempt to determine the correct credentials for I<uri>
based on the previous attempt in I<response> and what you
have configured in B<credentials>, B<authn_callback> or when
manually prompted.

=cut

sub get_authorized_doc {
    my $self     = shift;
    my $uri      = shift or croak "uri required";
    my $response = shift or croak "response required";

    # set up credentials
    $self->_authorize( $uri, $response->http_response ) or return;

    return $self->_make_request($uri);
}

sub _make_request {
    my ( $self, $uri ) = @_;

    # get our useragent
    my $ua    = $self->ua;
    my $delay = 0;
    if ( $self->{keep_alive} ) {
        $delay = 0;
    }
    elsif ( !$self->{delay} or !$self->{_last_response_time} ) {
        $delay = 0;
    }
    else {
        my $elapsed = time() - $self->{_last_response_time};
        $delay = $self->{delay} - $elapsed;
        $delay = 0 if $delay < 0;
        $self->debug
            and $self->write_log(
            uri => $uri,
            msg => "elapsed:$elapsed delay:$delay",
            );
    }

    $self->write_log(
        uri => $uri,
        msg => "GET delay:$delay",
    ) if $self->verbose;

    my %get_args = (
        uri     => $uri,
        delay   => $delay,
        debug   => $self->debug,
        verbose => $self->verbose,
    );

    if ( my ( $user, $pass ) = $self->_get_user_pass($uri) ) {
        $get_args{user} = $user;
        $get_args{pass} = $pass;
    }

    # fetch the uri. $ua handles delay internally.
    my $response      = $ua->get(%get_args);
    my $http_response = $response->http_response;

    # flag current time for next delay calc.
    $self->{_last_response_time} = time();

    # redirect? follow, conditionally.
    if ( $response->is_redirect ) {
        my $location = $response->header('location');
        if ( !$location ) {
            $self->write_log(
                uri => $uri,
                msg => "skipping, redirect without a Location header",
            );

lib/Dezi/Aggregator/Spider.pm  view on Meta::CPAN

    }
    else {
        $self->_add_links( $uri, $response->links );
    }

    # return $uri as a Doc object
    my $use_uri = $response->success ? $ua->uri : $uri;
    my $meta = {
        org_uri => $uri,
        ret_uri => ( $use_uri || $uri ),
        depth   => delete $self->{_cur_depth},
        status  => $response->status,
        success => $response->success,
        is_html => $response->is_html,
        title   => (
            $response->success
            ? ( $response->is_html
                ? ( $response->title || "No title: $use_uri" )
                : $use_uri
                )
            : "Failed: $use_uri"
        ),
        ct => ( $response->success ? $response->ct : "Unknown" ),
    };

    my $headers = $http_response->headers;
    my $buf     = $response->content;

    if ( $self->{use_md5} ) {
        my $fingerprint = $response->header('Content-MD5')
            || Digest::MD5::md5_base64($buf);
        if ( $self->md5_cache->has($fingerprint) ) {
            return "duplicate content for "
                . $self->md5_cache->get($fingerprint);
        }
        $self->md5_cache->add( $fingerprint => $uri );
    }

    if ( $response->success ) {

        my $content_type = $meta->{ct};
        my $swish3 = $self->indexer ? $self->indexer->swish3 : undef;
        if ( !$UTILS->get_parser_for_mime( $content_type, $swish3 ) ) {
            $self->write_log(
                uri => $uri,
                msg => "no parser for $content_type",
            );
        }
        my $charset = $headers->content_type;
        $charset =~ s/;?$meta->{ct};?//;
        my $encoding = $headers->content_encoding || $charset;
        my %doc = (
            url     => $meta->{org_uri},
            modtime => ( $headers->last_modified || $headers->date ),
            type    => $meta->{ct},
            content => ( $encoding =~ m/utf-8/i ? to_utf8($buf) : $buf ),
            size => $headers->content_length || length( pack 'C0a*', $buf ),
            charset => $encoding,
        );

        # cache whatever credentials were used so we can re-use
        if ( $self->{cur_realm} and $uri->userinfo ) {
            my $key = $uri->canonical->host_port . ':' . $self->{cur_realm};
            $self->{_auth_cache}->add( $key => $uri->userinfo );

            # not too sure of the best logic here
            my $path = $uri->path;
            $path =~ s!/[^/]*$!!;
            $self->{last_auth} = {
                path => $path,
                auth => $uri->userinfo,
            };
        }

        # return doc
        return $self->doc_class->new(%doc);

    }
    elsif ( $response->status == 401 ) {

        # authorize and try again
        $self->write_log(
            uri => $uri,
            msg => sprintf( "authn denied, retrying, %s",
                $response->status_line ),
        );
        return $self->get_authorized_doc( $uri, $response )
            || $response->status;
    }
    elsif ($response->status == 403
        && $http_response->status_line =~ m/robots.txt/ )
    {

        # ignore
        $self->write_log(
            uri => $uri,
            msg => sprintf( "skipped, %s", $http_response->status_line ),
        );
        return $self->get_authorized_doc( $uri, $response )
            || $response->status;
    }
    elsif ( $response->status == 403 ) {

        # authorize and try again
        $self->write_log(
            uri => $uri,
            msg => sprintf( "retrying, %s", $http_response->status_line ),
        );
        return $self->get_authorized_doc( $uri, $response );
    }
    else {

        $self->write_log(
            uri => $uri,
            msg => $http_response->status_line,
        );
        return $response->status;
    }

    return;    # never get here.
}

sub _get_user_pass {
    my $self = shift;
    my $uri  = shift;

    # Set basic auth if defined - use URI specific first, then credentials.
    # this doesn't track what should have authorization
    my $last_auth;
    if ( $self->{last_auth} ) {
        my $path = $uri->path;
        $path =~ s!/[^/]*$!!;
        $last_auth = $self->{last_auth}->{auth}
            if $self->{last_auth}->{path} eq $path;
    }

    my ( $user, $pass ) = split /:/,
        ( $last_auth || $uri->userinfo || $self->credentials || '' );

    return ( $user, $pass );
}

=head2 looks_like_feed( I<http_response> )

Called internally to perform naive heuristics on I<http_response>
to determine whether it looks like an XML feed of some kind,
rather than a HTML page.

=cut

sub looks_like_feed {
    my $self     = shift;
    my $response = shift or croak "response required";
    my $headers  = $response->headers;
    my $ct       = $headers->content_type;
    if ( $ct eq 'text/html' or $ct eq 'application/xhtml+xml' ) {
        return 0;
    }
    if (   $ct eq 'text/xml'
        or $ct eq 'application/rss+xml'
        or $ct eq 'application/rdf+xml'
        or $ct eq 'application/atom+xml' )
    {
        my $xml = $response->decoded_content;    # TODO or content()
        return XML::Feed->parse( \$xml );
    }

    return 0;
}

=head2 looks_like_sitemap( I<http_response> )

Called internally to perform naive heuristics on I<http_response>
to determine whether it looks like a XML sitemap feed,
rather than a HTML page.

=cut

sub looks_like_sitemap {
    my $self     = shift;
    my $response = shift or croak "response required";
    my $headers  = $response->headers;
    my $ct       = $headers->content_type;
    if ( $ct eq 'text/html' or $ct eq 'application/xhtml+xml' ) {
        return 0;
    }
    if (   $ct eq 'text/xml'
        or $ct eq 'application/xml' )
    {
        my $xml     = $response->decoded_content;    # TODO or content()
        my $sitemap = WWW::Sitemap::XML->new();
        eval { $sitemap->load( string => $xml ); };
        if ($@) {
            return 0;
        }
        return $sitemap;
    }



( run in 0.903 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )