lib/WWW/Crawler/Mojo.pm

filter: Statementstmt 55.8% 125 / 224 Branchbran 47.5% 39 / 82 Conditioncond 42.6% 29 / 68 MC/DCmcdc 23.0% 9 / 39 Subroutinesub 46.3% 25 / 54 Podpod 100% 12 / 12 totaltotal 49.9% 239 / 479 CC 69 SCAR 25.2
CC
69
Cov
52%
discover
55.1
__ANON__
20.0
__ANON__
20.0
CRAP 12.4
« blib/lib/WWW/Crawler/Mojo.pm ↑ Summary blib/lib/WWW/Crawler/Mojo/UserAgent.pm »
1 package WWW::Crawler::Mojo;
2 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use WWW::Crawler::Mojo::Job;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use WWW::Crawler::Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Mojo::Message::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Mojo::Util qw{md5_sum xml_escape dumper};
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use List::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 our $VERSION = '0.05';
12  
13 7 has active_conn => 0;
14 7 has 'crawler_loop_id';
15 7 has depth => 10;
16 1 ▶has fix => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
17 1 ▶has active_conns_per_host => sub { {} };
Subroutine __ANON__: called CC=1 SCAR=0.0
18 7 has max_conn => 1;
19 7 has max_conn_per_host => 1;
20 7 has 'peeping';
21 7 has 'peeping_port';
22 7 has peeping_max_length => 30000;
23 0 ▶has queue => sub { [] };
Subroutine __ANON__: not called CC=1 SCAR=1.2
24 1 ▶has 'ua' => sub { WWW::Crawler::Mojo::UserAgent->new };
Subroutine __ANON__: called CC=1 SCAR=0.0
25 7 has 'ua_name' =>
26 "www-crawler-mojo/$VERSION (+https://github.com/jamadam/www-crawler-mojo)";
27 7 has 'shuffle';
28  
29 sub crawl {
30 0 ▶ my ($self) = @_;
Subroutine crawl: not called CC=3 SCAR=24.8
Pod documented
31
32 0 $self->init;
33
34 0 ▶ die 'No job is given' if (! scalar @{$self->queue});
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$self->queue;} 0 0 0
35
36 0 $self->emit('start');
37
38 0 ▶ Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless "Mojo::IOLoop"->is_running 0 0 0
39 }
40  
41 sub init {
42 1 ▶ my ($self) = @_;
Subroutine init: called CC=8 SCAR=29.5
Pod documented
43
44 0 ▶ $self->on('empty', sub { say "Queue is drained out." })
Subroutine __ANON__: not called CC=1 SCAR=6.9
45 1 ▶ unless $self->has_subscribers('empty');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("empty") 1 0 1
46 0 ▶ $self->on('error', sub { say $_[1] })
Subroutine __ANON__: not called CC=1 SCAR=6.9
47 1 ▶ unless $self->has_subscribers('error');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("error") 1 0 1
48 0 ▶ $self->on('res', sub { $_[1]->() })
Subroutine __ANON__: not called CC=1 SCAR=6.9
49 1 ▶ unless $self->has_subscribers('res');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("res") 1 0 1
50 0 ▶ $self->on('refer', sub { $_[1]->() })
Subroutine __ANON__: not called CC=1 SCAR=6.9
51 1 ▶ unless $self->has_subscribers('refer');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_subscribers("refer") 1 0 1
52
53 1 $self->ua->transactor->name($self->ua_name);
54 1 $self->ua->max_redirects(5);
55
56 my $loop_id = Mojo::IOLoop->recurring(0.25 => sub {
57 0 ▶ $self->process_job(@_);
Subroutine __ANON__: not called CC=1 SCAR=6.9
58 1 });
59
60 1 $self->crawler_loop_id($loop_id);
61
62 # notify queue is drained out
63 Mojo::IOLoop->recurring(5 => sub {
64 0 ▶ $self->emit('empty') if (! scalar @{$self->{queue}});
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if not scalar @{$self->{"queue"};} 0 0 0
65 1 });
66
67 1 ▶ if ($self->peeping || $self->peeping_port) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->peeping or $self->peeping_port) 0 1 1
Condition33%1/3
$self->peeping or $self->peeping_port
l!l&&r!l&&!r
001
MC/DC0%0/2
$self->peeping or $self->peeping_port
$self->peeping $self->peeping_port
Truth table33%1/3
A or B
A= $self->peepingB= $self->peeping_port
ABresult
1X1
011
000
68 # peeping API server
69 my $id = Mojo::IOLoop->server({port => $self->peeping_port}, sub {
70 0 ▶ $self->peeping_handler(@_);
Subroutine __ANON__: not called CC=1 SCAR=6.9
71 0 });
72 0 $self->peeping_port(Mojo::IOLoop->acceptor($id)->handle->sockport);
73 }
74
75 1 ▶ if ($self->shuffle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->shuffle) 0 1 1
76 Mojo::IOLoop->recurring($self->shuffle => sub {
77 0 ▶ @{$self->{queue}} = List::Util::shuffle @{$self->{queue}};
Subroutine __ANON__: not called CC=1 SCAR=6.9
78 0 });
79 }
80 }
81  
82 sub process_job {
83 0 ▶ my $self = shift;
Subroutine process_job: not called CC=3 SCAR=24.8
Pod documented
84
85 return unless ($self->{queue}->[0] &&
86 0 ▶ $self->_mod_busyness($self->{queue}->[0]->resolved_uri, 1));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"queue"}[0] and $self->_mod_busyness($self->{"queue"}[0]->resolved_uri, 1) 0 0 0
Condition0%0/3
$self->{"queue"}[0] and $self->_mod_busyness($self->{"queue"}[0]->resolved_uri, 1)
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"queue"}[0] and $self->_mod_busyness($self->{"queue"}[0]->resolved_uri, 1)
$self->{"queue"}[0] $self->_mod_busyness($self->{"queue"}[0]->resolved_uri, 1)
Truth table0%0/3
A and B
A= $self->{"queue"}[0]B= $self->_mod_busyness($self->{"queue"}[0]->resolved_uri, 1)
ABresult
0X0
100
111
87
88 0 my $job = shift @{$self->{queue}};
89 0 my $uri = $job->resolved_uri;
90 0 my $ua = $self->ua;
91 0 my $tx = $ua->build_tx($job->method => $uri => $job->tx_params);
92
93 $ua->start($tx, sub {
94 0 ▶ $self->_mod_busyness($uri, -1);
Subroutine __ANON__: not called CC=3 SCAR=24.8
95
96 0 my ($ua, $tx) = @_;
97
98 0 $job->redirect(_urls_redirect($tx));
99
100 0 my $res = $tx->res;
101
102 0 ▶ if (!$res->code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->code) 0 0 0
103 0 ▶ my $msg = ($res->error) ? $res->error->{message} : 'Unknown error';
Branch: 1 branch
BranchTrueFalseTotal
$res->error ? : 0 0 0
104 0 my $url = $job->resolved_uri;
105 0 $self->emit('error',
106 "An error occured during crawling $url: $msg", $job);
107 0 return;
108 }
109
110 0 ▶ $self->emit('res', sub { $self->discover($res, $job) }, $job, $res);
Subroutine __ANON__: not called CC=1 SCAR=6.9
111 0 });
112 }
113  
114 sub say_start {
115 0 ▶ my $self = shift;
Subroutine say_start: not called CC=2 SCAR=17.9
Pod documented
116
117 0 print <<"EOF";
118 ----------------------------------------
119 0 Crawling is starting with @{[ $self->queue->[0]->resolved_uri ]}
120 0 Max Connection : @{[ $self->max_conn ]}
121 0 Depth : @{[ $self->depth ]}
122 0 User Agent : @{[ $self->ua_name ]}
123 EOF
124  
125 0 ▶ print <<"EOF" if ($self->peeping_port);
Branch: 1 branch
BranchTrueFalseTotal
if $self->peeping_port 0 0 0
126 Peeping API is available at following URL
127 0 http://127.0.0.1:@{[ $self->peeping_port ]}/
128 EOF
129
130 0 print <<"EOF";
131 ----------------------------------------
132 EOF
133 }
134  
135 sub peeping_handler {
136 0 ▶ my ($self, $loop, $stream) = @_;
Subroutine peeping_handler: not called CC=1 SCAR=6.9
Pod documented
137 $stream->on(read => sub {
138 0 ▶ my ($stream, $bytes) = @_;
Subroutine __ANON__: not called CC=4 SCAR=30.0
139
140 0 my $path = Mojo::Message::Request->new->parse($bytes)->url->path;
141
142 0 ▶ if ($path =~ qr{^/queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ qr"^/queue"u) 0 0 0
143 0 my $res = sprintf('%s jobs are left.', scalar @{$self->queue});
144 0 $stream->write("HTTP/1.1 200 OK\n\n");
145 0 ▶ $stream->write($res, sub {shift->close});
Subroutine __ANON__: not called CC=1 SCAR=6.9
146 0 return;
147 }
148
149 0 ▶ if ($path =~ qr{^/dumper/(\w+)} && defined $self->{$1}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ qr"^/dumper/(\w+)"u and defined $self->{$1}) 0 0 0
Condition0%0/3
$path =~ qr"^/dumper/(\w+)"u and defined $self->{$1}
!ll&&!rl&&r
000
MC/DC0%0/2
$path =~ qr"^/dumper/(\w+)"u and defined $self->{$1}
$path =~ qr"^/dumper/(\w+)"u defined $self->{$1}
Truth table0%0/3
A and B
A= $path =~ qr"^/dumper/(\w+)"uB= defined $self->{$1}
ABresult
0X0
100
111
150 0 my $res = substr(dumper($self->{$1}), 0, $self->peeping_max_length);
151 0 $stream->write("HTTP/1.1 200 OK\n\n");
152 0 ▶ $stream->write($res, sub {shift->close});
Subroutine __ANON__: not called CC=1 SCAR=6.9
153 0 return;
154 }
155
156 $stream->write(
157 0 ▶ "HTTP/1.1 404 NOT FOUND\n\nNOT FOUND", sub {shift->close});
Subroutine __ANON__: not called CC=1 SCAR=6.9
158 0 });
159 }
160  
161 sub discover {
162 1 ▶ my ($self, $res, $job) = @_;
Subroutine discover: called CC=13 SCAR=40.1
Pod documented
163
164 1 ▶ return if ($res->code != 200);
Branch: 1 branch
BranchTrueFalseTotal
if $res->code != 200 0 1 1
165 1 ▶ return if ($self->depth && $job->depth >= $self->depth);
Branch: 1 branch
BranchTrueFalseTotal
if $self->depth and $job->depth >= $self->depth 0 1 1
Condition33%1/3
$self->depth and $job->depth >= $self->depth
!ll&&!rl&&r
010
MC/DC0%0/2
$self->depth and $job->depth >= $self->depth
$self->depth $job->depth >= $self->depth
Truth table33%1/3
A and B
A= $self->depthB= $job->depth >= $self->depth
ABresult
0X0
100
111
166
167 1 my $base = $job->resolved_uri;
168 1 my $type = $res->headers->content_type;
169
170 1 ▶ if ($type && $type =~ qr{text/(html|xml)} &&
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type =~ qr"text/(html|xml)"u and my $base_tag = $res->dom->at("base")) 0 1 1
Condition33%2/6
$type and $type =~ qr"text/(html|xml)"u and my $base_tag = $res->dom->at("base")
!ll&&!rl&&r
010
$type and $type =~ qr"text/(html|xml)"u
!ll&&!rl&&r
001
MC/DC0%0/3
$type and $type =~ qr"text/(html|xml)"u and my $base_tag = $res->dom->at("base")
$type $type =~ qr"text/(html|xml)"u my $base_tag = $res->dom->at("base")
Truth table25%1/4
A and B and C
A= $typeB= $type =~ qr"text/(html|xml)"uC= my $base_tag = $res->dom->at("base")
ABCresult
0XX0
10X0
1100
1111
171 (my $base_tag = $res->dom->at('base'))) {
172 0 $base = resolve_href($base, $base_tag->attr('href'));
173 }
174
175 my $cb = sub {
176 0 ▶ my ($url, $dom) = @_;
Subroutine __ANON__: not called CC=4 SCAR=30.0
177
178 0 $url = Mojo::URL->new($url);
179
180 return unless
181 0 ▶ (!$url->scheme || $url->scheme =~ qr{http|https|ftp|ws|wss});
Branch: 1 branch
BranchTrueFalseTotal
unless not $url->scheme or $url->scheme =~ qr/http|https|ftp|ws|wss/u 0 0 0
Condition0%0/3
not $url->scheme or $url->scheme =~ qr/http|https|ftp|ws|wss/u
l!l&&r!l&&!r
000
MC/DC0%0/2
not $url->scheme or $url->scheme =~ qr/http|https|ftp|ws|wss/u
not $url->scheme $url->scheme =~ qr/http|https|ftp|ws|wss/u
Truth table0%0/3
not(A) or B
A= not $url->schemeB= $url->scheme =~ qr/http|https|ftp|ws|wss/u
ABresult
1X1
011
000
182
183 0 my $child = $job->child(
184 resolved_uri => resolve_href($base, $url), literal_uri => $url);
185
186 $self->emit('refer', sub {
187 0 ▶ $self->enqueue($_[0] || $child);
Subroutine __ANON__: not called CC=2 SCAR=17.9
Condition0%0/3
$_[0] || $child
l!l&&r!l&&!r
000
MC/DC0%0/2
$_[0] || $child
$_[0] $child
Truth table0%0/3
A || B
A= $_[0]B= $child
ABresult
1X1
011
000
188 0 ▶ }, $child, $dom || $job->resolved_uri);
Condition0%0/3
$dom || $job->resolved_uri
l!l&&r!l&&!r
000
MC/DC0%0/2
$dom || $job->resolved_uri
$dom $job->resolved_uri
Truth table0%0/3
A || B
A= $domB= $job->resolved_uri
ABresult
1X1
011
000
189 1 };
190
191 1 ▶ if ($type && $type =~ qr{text/(html|xml)}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type =~ qr"text/(html|xml)"u) 1 0 1
Condition33%1/3
$type and $type =~ qr"text/(html|xml)"u
!ll&&!rl&&r
001
MC/DC0%0/2
$type and $type =~ qr"text/(html|xml)"u
$type $type =~ qr"text/(html|xml)"u
Truth table33%1/3
A and B
A= $typeB= $type =~ qr"text/(html|xml)"u
ABresult
0X0
100
111
192 1 ▶ my $encode = guess_encoding($res) || 'utf-8';
Condition50%1/2
guess_encoding($res) || 'utf-8'
l!l
01
MC/DC0%0/1
guess_encoding($res) || 'utf-8'
guess_encoding($res)
Truth table50%1/2
A
A= guess_encoding($res)
Aresult
11
00
193 1 my $body = Encode::decode($encode, $res->body);
194 1 collect_urls_html(Mojo::DOM->new($body), $cb);
195 }
196
197 1 ▶ if ($type && $type =~ qr{text/css}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type and $type =~ qr"text/css"u) 0 1 1
Condition33%1/3
$type and $type =~ qr"text/css"u
!ll&&!rl&&r
010
MC/DC0%0/2
$type and $type =~ qr"text/css"u
$type $type =~ qr"text/css"u
Truth table33%1/3
A and B
A= $typeB= $type =~ qr"text/css"u
ABresult
0X0
100
111
198 0 ▶ my $encode = guess_encoding($res) || 'utf-8';
Condition0%0/2
guess_encoding($res) || 'utf-8'
l!l
00
MC/DC0%0/1
guess_encoding($res) || 'utf-8'
guess_encoding($res)
Truth table0%0/2
A
A= guess_encoding($res)
Aresult
11
00
199 0 my $body = Encode::decode($encode, $res->body);
200 0 collect_urls_css($body, $cb);
201 }
202 };
203  
204 sub enqueue {
205 3 ▶ shift->_enqueue([@_]);
Subroutine enqueue: called CC=1 SCAR=0.0
Pod documented
206 }
207  
208 sub requeue {
209 1 ▶ shift->_enqueue([@_], 1);
Subroutine requeue: called CC=1 SCAR=0.0
Pod documented
210 }
211  
212 sub _enqueue {
213 4 ▶ my ($self, $jobs, $requeue) = @_;
Subroutine _enqueue: called CC=7 SCAR=19.5
214
215 4 for my $job (@$jobs) {
216 4 ▶ if (! ref $job || ref $job ne 'WWW::Crawler::Mojo::Job') {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $job or ref $job ne "WWW::Crawler::Mojo::Job") 2 2 4
Condition100%3/3
not ref $job or ref $job ne "WWW::Crawler::Mojo::Job"
l!l&&r!l&&!r
112
MC/DC100%2/2
not ref $job or ref $job ne "WWW::Crawler::Mojo::Job"
not ref $job ref $job ne "WWW::Crawler::Mojo::Job"
Truth table100%3/3
not(A) or B
A= not ref $jobB= ref $job ne "WWW::Crawler::Mojo::Job"
ABresult
1X1
011
000
217 2 ▶ my $url = !ref $job ? Mojo::URL->new($job) : $job;
Branch: 1 branch
BranchTrueFalseTotal
!ref($job) ? : 1 1 2
218 2 $job = WWW::Crawler::Mojo::Job->new(resolved_uri => $url);
219 }
220
221 4 my $md5 = md5_sum($job->resolved_uri->to_string);
222 4 ▶ if ($requeue || !exists $self->fix->{$md5}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($requeue or not exists $self->fix->{$md5}) 3 1 4
Condition100%3/3
$requeue or not exists $self->fix->{$md5}
l!l&&r!l&&!r
121
MC/DC100%2/2
$requeue or not exists $self->fix->{$md5}
$requeue not exists $self->fix->{$md5}
Truth table100%3/3
A or not(B)
A= $requeueB= not exists $self->fix->{$md5}
ABresult
1X1
011
000
223 3 $self->fix->{$md5} = undef;
224 3 push(@{$self->{queue}}, $job);
225 }
226 }
227 }
228  
229 7 our %tag_attributes = (
230 script => ['src'],
231 link => ['href'],
232 a => ['href'],
233 img => ['src'],
234 area => ['href', 'ping'],
235 embed => ['src'],
236 frame => ['src'],
237 iframe => ['src'],
238 input => ['src'],
239 object => ['data'],
240 form => ['action'],
241 );
242  
243 sub collect_urls_html {
244 2 ▶ my ($dom, $cb) = @_;
Subroutine collect_urls_html: called CC=1 SCAR=3.0
Pod documented
245
246 $dom->find(join(',', keys %tag_attributes))->each(sub {
247 18 ▶ my $dom = shift;
Subroutine __ANON__: called CC=3 SCAR=14.2
248 18 for (@{$tag_attributes{$dom->type}}) {
249 0 ▶ $cb->($dom->{$_}, $dom) if ($dom->{$_});
Branch: 1 branch
BranchTrueFalseTotal
if $dom->{$_} 0 0 0
250 }
251 2 });
252 $dom->find('meta[http\-equiv=Refresh]')->each(sub {
253 0 ▶ my $dom = shift;
Subroutine __ANON__: not called CC=3 SCAR=24.8
254 0 ▶ if (my $href = $dom->{content} && ($dom->{content} =~ qr{URL=(.+)}i)[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $href = $dom->{"content"} && ($dom->{"content"} =~ qr/URL=(.+)/iu)[0]) 0 0 0
Condition0%0/3
$dom->{'content'} && ($dom->{'content'} =~ qr/URL=(.+)/iu)[0]
!ll&&!rl&&r
000
MC/DC0%0/2
$dom->{'content'} && ($dom->{'content'} =~ qr/URL=(.+)/iu)[0]
$dom->{'content'} ($dom->{'content'} =~ qr/URL=(.+)/iu)[0]
Truth table0%0/3
A && B
A= $dom->{'content'}B= ($dom->{'content'} =~ qr/URL=(.+)/iu)[0]
ABresult
0X0
100
111
255 0 $cb->($href, $dom);
256 }
257 2 });
258 $dom->find('style')->each(sub {
259 0 ▶ my $dom = shift;
Subroutine __ANON__: not called CC=2 SCAR=17.9
260 0 ▶ collect_urls_css($dom->content || '', sub { $cb->(shift, $dom) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
Condition0%0/2
$dom->content || ''
l!l
00
MC/DC0%0/1
$dom->content || ''
$dom->content
Truth table0%0/2
A
A= $dom->content
Aresult
11
00
261 2 });
262 $dom->find('*[style]')->each(sub {
263 0 ▶ my $dom = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
264 0 ▶ collect_urls_css($dom->{style}, sub { $cb->(shift, $dom) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
265 2 });
266 }
267  
268 sub collect_urls_css {
269 0 ▶ my ($str, $cb) = @_;
Subroutine collect_urls_css: not called CC=2 SCAR=17.9
Pod documented
270 0 $str =~ s{/\*.+?\*/}{}gs;
271 0 my @urls = ($str =~ m{url\(['"]?(.+?)['"]?\)}g);
272 0 $cb->($_) for (@urls);
273 }
274  
275 7 my $charset_re = qr{\bcharset\s*=\s*['"]?([a-zA-Z0-9_\-]+)['"]?}i;
276  
277 sub guess_encoding {
278 5 ▶ my $res = shift;
Subroutine guess_encoding: called CC=5 SCAR=17.8
Pod documented
279 5 my $type = $res->headers->content_type;
280 5 ▶ return unless ($type);
Branch: 1 branch
BranchTrueFalseTotal
unless $type 0 5 5
281 5 my $charset = ($type =~ $charset_re)[0];
282 5 ▶ return $charset if ($charset);
Branch: 1 branch
BranchTrueFalseTotal
if $charset 2 3 5
283 3 ▶ return _guess_encoding_html($res->body) if ($type =~ qr{text/(html|xml)});
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ qr"text/(html|xml)"u 3 0 3
284 0 ▶ return _guess_encoding_css($res->body) if ($type =~ qr{text/css});
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ qr"text/css"u 0 0 0
285 }
286  
287 sub _guess_encoding_css {
288 0 ▶ return (shift =~ qr{^\s*\@charset ['"](.+?)['"];}is)[0];
Subroutine _guess_encoding_css: not called CC=1 SCAR=6.9
289 }
290  
291 sub _guess_encoding_html {
292 3 ▶ my $head = (shift =~ qr{<head>(.+)</head>}is)[0] or return;
Subroutine _guess_encoding_html: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
my $head = ((shift()) =~ qr"<head>(.+)</head>"isu)[0] or return 1 2 3
293 2 my $charset;
294 Mojo::DOM->new($head)->find('meta[http\-equiv=Content-Type]')->each(sub{
295 1 ▶ $charset = (shift->{content} =~ $charset_re)[0];
Subroutine __ANON__: called CC=1 SCAR=0.0
296 2 });
297 2 return $charset;
298 }
299  
300 sub resolve_href {
301 70 ▶ my ($base, $href) = @_;
Subroutine resolve_href: called CC=6 SCAR=17.9
Pod documented
302 70 ▶ $href = ref $href ? $href : Mojo::URL->new($href);
Branch: 1 branch
BranchTrueFalseTotal
ref $href ? : 0 70 70
303 70 ▶ $base = ref $base ? $base : Mojo::URL->new($base);
Branch: 1 branch
BranchTrueFalseTotal
ref $base ? : 68 2 70
304 70 my $abs = $href->to_abs($base)->fragment(undef);
305 70 ▶ while ($abs->path->parts->[0] && $abs->path->parts->[0] =~ /^\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($abs->path->parts->[0] and $abs->path->parts->[0] =~ /^\./u) 6 70 76
Condition100%3/3
$abs->path->parts->[0] and $abs->path->parts->[0] =~ /^\./u
!ll&&!rl&&r
10606
MC/DC100%2/2
$abs->path->parts->[0] and $abs->path->parts->[0] =~ /^\./u
$abs->path->parts->[0] $abs->path->parts->[0] =~ /^\./u
Truth table100%3/3
A and B
A= $abs->path->parts->[0]B= $abs->path->parts->[0] =~ /^\./u
ABresult
0X0
100
111
306 6 shift @{$abs->path->parts};
307 }
308 70 ▶ $abs->path->trailing_slash($base->path->trailing_slash) if (!$href->path->to_string);
Branch: 1 branch
BranchTrueFalseTotal
unless $href->path->to_string 8 62 70
309 70 return $abs;
310 }
311  
312 sub _urls_redirect {
313 0 ▶ my $tx = shift;
Subroutine _urls_redirect: not called CC=2 SCAR=17.9
314 0 my @urls;
315 0 ▶ @urls = _urls_redirect($tx->previous) if ($tx->previous);
Branch: 1 branch
BranchTrueFalseTotal
if $tx->previous 0 0 0
316 0 unshift(@urls, $tx->req->url->userinfo(undef));
317 0 return @urls;
318 }
319  
320 sub _mod_busyness {
321 36 ▶ my ($self, $uri, $inc) = @_;
Subroutine _mod_busyness: called CC=6 SCAR=17.9
322 36 my $key = _host_key($uri);
323 36 my $hosts = $self->active_conns_per_host;
324
325 return if ($inc > 0 && ($self->active_conn >= $self->max_conn ||
326 36 ▶ ($hosts->{$key} || 0) >= $self->max_conn_per_host));
Branch: 1 branch
BranchTrueFalseTotal
if $inc > 0 and $self->active_conn >= $self->max_conn || ($hosts->{$key} || 0) >= $self->max_conn_per_host 14 22 36
Condition100%8/8
$inc > 0 and $self->active_conn >= $self->max_conn || ($hosts->{$key} || 0) >= $self->max_conn_per_host
!ll&&!rl&&r
111213
$self->active_conn >= $self->max_conn or ($hosts->{$key} || 0) >= $self->max_conn_per_host
l!l&&r!l&&!r
11311
$hosts->{$key} || 0
l!l
1410
MC/DC66%2/3
$inc > 0 and $self->active_conn >= $self->max_conn || ($hosts->{$key} || 0) >= $self->max_conn_per_host
$inc > 0 $self->active_conn >= $self->max_conn $hosts->{$key}
Truth table75%3/4
A and B or C
A= $inc > 0B= $self->active_conn >= $self->max_connC= $hosts->{$key}
ABCresult
0XX0
1000
11X1
1011
327
328 22 $self->{active_conn} += $inc;
329 22 $hosts->{$key} += $inc;
330 22 ▶ delete($hosts->{$key}) unless ($hosts->{$key});
Branch: 1 branch
BranchTrueFalseTotal
unless $hosts->{$key} 10 12 22
331 22 return 1;
332 }
333  
334 sub _host_key {
335 36 ▶ my $uri = ref $_[0] ? $_[0] : Mojo::URL->new($_[0]);
Subroutine _host_key: called CC=7 SCAR=20.4
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 36 0 36
336 36 my $key = $uri->scheme. '://'. $uri->ihost;
337
338 36 ▶ if (my $port = $uri->port) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $port = $uri->port) 8 28 36
339 8 ▶ if (($uri->scheme eq 'https' && $port != 443) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($uri->scheme eq "https" and $port != 443 or $uri->scheme eq "http" and $port != 80) 6 2 8
Condition55%5/9
$uri->scheme eq "https" and $port != 443 or $uri->scheme eq "http" and $port != 80
l!l&&r!l&&!r
602
$uri->scheme eq "https" and $port != 443
!ll&&!rl&&r
206
$uri->scheme eq "http" and $port != 80
!ll&&!rl&&r
020
MC/DC25%1/4
$uri->scheme eq "https" and $port != 443 or $uri->scheme eq "http" and $port != 80
$uri->scheme eq "https" $port != 443 $uri->scheme eq "http" $port != 80
Truth table28%2/7
A and B or C and D
A= $uri->scheme eq "https"B= $port != 443C= $uri->scheme eq "http"D= $port != 80
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
340 ($uri->scheme eq 'http' && $port != 80)) {
341 6 $key .= ':'. $port;
342 }
343 }
344
345 36 return $key;
346 }
347  
348 7 1;
349  
350 =head1 NAME
351  
352 WWW::Crawler::Mojo - A web crawling framework for Perl
353  
354 =head1 SYNOPSIS
355  
356 use strict;
357 use warnings;
358 use utf8;
359 use WWW::Crawler::Mojo;
360 use 5.10.0;
361
362 my $bot = WWW::Crawler::Mojo->new;
363
364 $bot->on(res => sub {
365 my ($bot, $discover, $job, $res) = @_;
366
367 $discover->();
368 });
369
370 $bot->on(refer => sub {
371 my ($bot, $enqueue, $job, $context) = @_;
372
373 $enqueue->();
374 });
375
376 $bot->enqueue('http://example.com/');
377 $bot->crawl;
378  
379 =head1 DESCRIPTION
380  
381 L<WWW::Crawler::Mojo> is a web crawling framework for those who familier with
382 L<Mojo>::* APIs.
383  
384 Note that the module is aimed at trivial use cases of crawling within a
385 moderate range of web pages so DO NOT use it for persistent crawler jobs.
386  
387 =head1 ATTRIBUTE
388  
389 L<WWW::Crawler::Mojo> inherits all attributes from L<Mojo::EventEmitter> and
390 implements the following new ones.
391  
392 =head2 ua
393  
394 A L<Mojo::UserAgent> instance.
395  
396 my $ua = $bot->ua;
397 $bot->ua(Mojo::UserAgent->new);
398  
399 =head2 ua_name
400  
401 Name of crawler for User-Agent header.
402  
403 $bot->ua_name('my-bot/0.01 (+https://example.com/)');
404 say $bot->ua_name; # 'my-bot/0.01 (+https://example.com/)'
405  
406 =head2 active_conn
407  
408 A number of current connections.
409  
410 $bot->active_conn($bot->active_conn + 1);
411 say $bot->active_conn;
412  
413 =head2 active_conns_per_host
414  
415 A number of current connections per host.
416  
417 $bot->active_conns_per_host($bot->active_conns_per_host + 1);
418 say $bot->active_conns_per_host;
419  
420 =head2 depth
421  
422 A number of max depth to crawl. Note that the depth is the number of HTTP
423 requests to get to URI starting with the first job. This doesn't mean the
424 deepness of URI path detected with slash.
425  
426 $bot->depth(5);
427 say $bot->depth; # 5
428  
429 =head2 max_conn
430  
431 A number of max connections.
432  
433 $bot->max_conn(5);
434 say $bot->max_conn; # 5
435  
436 =head2 max_conn_per_host
437  
438 A number of max connections per host.
439  
440 $bot->max_conn_per_host(5);
441 say $bot->max_conn_per_host; # 5
442  
443 =head2 peeping_max_length
444  
445 Max length of peeping API content.
446  
447 $bot->peeping_max_length(100000);
448 say $bot->peeping_max_length; # 100000
449  
450 =head2 queue
451  
452 FIFO array contains L<WWW::Crawler::Mojo::Job> objects.
453  
454 push(@{$bot->queue}, WWW::Crawler::Mojo::Job->new(...));
455 my $job = shift @{$bot->queue};
456  
457 =head1 EVENTS
458  
459 L<WWW::Crawler::Mojo> inherits all events from L<Mojo::EventEmitter> and
460 implements the following new ones.
461  
462 =head2 res
463  
464 Emitted when crawler got response from server.
465  
466 $bot->on(res => sub {
467 my ($bot, $discover, $job, $res) = @_;
468 if (...) {
469 $discover->();
470 } else {
471 # DO NOTHING
472 }
473 });
474  
475 =head2 refer
476  
477 Emitted when new URI is found. You can enqueue the URI conditionally with
478 the callback.
479  
480 $bot->on(refer => sub {
481 my ($bot, $enqueue, $job, $context) = @_;
482 if (...) {
483 $enqueue->();
484 } elseif (...) {
485 $enqueue->(...); # maybe different url
486 } else {
487 # DO NOTHING
488 }
489 });
490  
491 =head2 empty
492  
493 Emitted when queue length got zero. The length is checked every 5 seconds.
494  
495 $bot->on(empty => sub {
496 my ($bot) = @_;
497 say "Queue is drained out.";
498 });
499  
500 =head2 error
501  
502 Emitted when user agent returns no status code for request. Possibly caused by
503 network errors or un-responsible servers.
504  
505 $bot->on(error => sub {
506 my ($bot, $error, $job) = @_;
507 say "error: $_[1]";
508 if (...) { # until failur occures 3 times
509 $bot->requeue($job);
510 }
511 });
512  
513 Note that server errors such as 404 or 500 cannot be catched with the event.
514 Consider res event for the use case instead of this.
515  
516 =head2 start
517  
518 Emitted right before crawl is started.
519  
520 $bot->on(start => sub {
521 my $self = shift;
522 ...
523 });
524  
525 =head1 METHODS
526  
527 L<WWW::Crawler::Mojo> inherits all methods from L<Mojo::EventEmitter> and
528 implements the following new ones.
529  
530 =head2 crawl
531  
532 Start crawling loop.
533  
534 $bot->crawl;
535  
536 =head2 init
537  
538 Initialize crawler settings.
539  
540 $bot->init;
541  
542 =head2 process_job
543  
544 Process a job.
545  
546 $bot->process_job;
547  
548 =head2 say_start
549  
550 Displays starting messages to STDOUT
551  
552 $bot->say_start;
553  
554 =head2 peeping_handler
555  
556 peeping API dispatcher.
557  
558 $bot->peeping_handler($loop, $stream);
559  
560 =head2 discover
561  
562 Parses and discovers links in a web page. Each links are appended to FIFO array.
563  
564 $bot->discover($res, $job);
565  
566 =head2 enqueue
567  
568 Append a job with a URI or L<WWW::Crawler::Mojo::Job> object.
569  
570 $bot->enqueue($job);
571  
572 =head2 requeue
573  
574 Append a job for re-try.
575  
576 $self->on(error => sub {
577 my ($self, $msg, $job) = @_;
578 if (...) { # until failur occures 3 times
579 $bot->requeue($job);
580 }
581 });
582  
583 =head2 collect_urls_html
584  
585 Collects URLs out of HTML.
586  
587 WWW::Crawler::Mojo::collect_urls_html($dom, sub {
588 my ($uri, $dom) = @_;
589 });
590  
591 =head2 collect_urls_css
592  
593 Collects URLs out of CSS.
594  
595 WWW::Crawler::Mojo::collect_urls_css($dom, sub {
596 my $uri = shift;
597 });
598  
599 =head2 guess_encoding
600  
601 Guesses encoding of HTML or CSS with given L<Mojo::Message::Response> instance.
602  
603 $encode = WWW::Crawler::Mojo::guess_encoding($res) || 'utf-8'
604  
605 =head2 resolve_href
606  
607 Resolves URLs with a base URL.
608  
609 WWW::Crawler::Mojo::resolve_href($base, $uri);
610  
611 =head1 EXAMPLE
612  
613 L<https://github.com/jamadam/WWW-Flatten>
614  
615 =head1 AUTHOR
616  
617 Sugama Keita, E<lt>sugama@jamadam.comE<gt>
618  
619 =head1 COPYRIGHT AND LICENSE
620  
621 Copyright (C) jamadam
622  
623 This program is free software; you can redistribute it and/or
624 modify it under the same terms as Perl itself.
625  
626 =cut
« blib/lib/WWW/Crawler/Mojo.pm ↑ Summary blib/lib/WWW/Crawler/Mojo/UserAgent.pm »