blib/lib/WWW/Crawler/Mojo.pm untested

filter: Statementstmt 0.0% 0 / 245 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 70 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 438 CC 40 SCAR 32.1
CC
40
Cov
0%
init
72.0
discover
56.0
guess_encoding
30.0
CRAP 24.8
1 package WWW::Crawler::Mojo;
2 use strict;
3 use warnings;
4 use 5.010;
5 use Mojo::Base 'Mojo::EventEmitter';
6 use WWW::Crawler::Mojo::Job;
7 use WWW::Crawler::Mojo::UserAgent;
8 use Mojo::Message::Request;
9 use Mojo::Util qw{md5_sum xml_escape dumper};
10 use List::Util;
11 our $VERSION = '0.05';
12  
13 has active_conn => 0;
14 has 'crawler_loop_id';
15 has depth => 10;
16 has fix => sub { {} };
17 has active_conns_per_host => sub { {} };
18 has max_conn => 1;
19 has max_conn_per_host => 1;
20 has 'peeping';
21 has 'peeping_port';
22 has peeping_max_length => 30000;
23 has queue => sub { [] };
24 has 'ua' => sub { WWW::Crawler::Mojo::UserAgent->new };
25 has 'ua_name' =>
26 "www-crawler-mojo/$VERSION (+https://github.com/jamadam/www-crawler-mojo)";
27 has 'shuffle';
28  
29 sub crawl {
30 my ($self) = @_;
31
32 $self->init;
33
34 die 'No job is given' if (! scalar @{$self->queue});
35
36 $self->emit('start');
37
38 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
39 }
40  
41 sub init {
42 my ($self) = @_;
43
44 $self->on('empty', sub { say "Queue is drained out." })
45 unless $self->has_subscribers('empty');
46 $self->on('error', sub { say $_[1] })
47 unless $self->has_subscribers('error');
48 $self->on('res', sub { $_[1]->() })
49 unless $self->has_subscribers('res');
50 $self->on('refer', sub { $_[1]->() })
51 unless $self->has_subscribers('refer');
52
53 $self->ua->transactor->name($self->ua_name);
54 $self->ua->max_redirects(5);
55
56 my $loop_id = Mojo::IOLoop->recurring(0.25 => sub {
57 $self->process_job(@_);
58 });
59
60 $self->crawler_loop_id($loop_id);
61
62 # notify queue is drained out
63 Mojo::IOLoop->recurring(5 => sub {
64 $self->emit('empty') if (! scalar @{$self->{queue}});
65 });
66
67 if ($self->peeping || $self->peeping_port) {
68 # peeping API server
69 my $id = Mojo::IOLoop->server({port => $self->peeping_port}, sub {
70 $self->peeping_handler(@_);
71 });
72 $self->peeping_port(Mojo::IOLoop->acceptor($id)->handle->sockport);
73 }
74
75 if ($self->shuffle) {
76 Mojo::IOLoop->recurring($self->shuffle => sub {
77 @{$self->{queue}} = List::Util::shuffle @{$self->{queue}};
78 });
79 }
80 }
81  
82 sub process_job {
83 my $self = shift;
84
85 return unless ($self->{queue}->[0] &&
86 $self->_mod_busyness($self->{queue}->[0]->resolved_uri, 1));
87
88 my $job = shift @{$self->{queue}};
89 my $uri = $job->resolved_uri;
90 my $ua = $self->ua;
91 my $tx = $ua->build_tx($job->method => $uri => $job->tx_params);
92
93 $ua->start($tx, sub {
94 $self->_mod_busyness($uri, -1);
95
96 my ($ua, $tx) = @_;
97
98 $job->redirect(_urls_redirect($tx));
99
100 my $res = $tx->res;
101
102 if (!$res->code) {
103 my $msg = ($res->error) ? $res->error->{message} : 'Unknown error';
104 my $url = $job->resolved_uri;
105 $self->emit('error',
106 "An error occured during crawling $url: $msg", $job);
107 return;
108 }
109
110 $self->emit('res', sub { $self->discover($res, $job) }, $job, $res);
111 });
112 }
113  
114 sub say_start {
115 my $self = shift;
116
117 print <<"EOF";
118 ----------------------------------------
119 Crawling is starting with @{[ $self->queue->[0]->resolved_uri ]}
120 Max Connection : @{[ $self->max_conn ]}
121 Depth : @{[ $self->depth ]}
122 User Agent : @{[ $self->ua_name ]}
123 EOF
124  
125 print <<"EOF" if ($self->peeping_port);
126 Peeping API is available at following URL
127 http://127.0.0.1:@{[ $self->peeping_port ]}/
128 EOF
129
130 print <<"EOF";
131 ----------------------------------------
132 EOF
133 }
134  
135 sub peeping_handler {
136 my ($self, $loop, $stream) = @_;
137 $stream->on(read => sub {
138 my ($stream, $bytes) = @_;
139
140 my $path = Mojo::Message::Request->new->parse($bytes)->url->path;
141
142 if ($path =~ qr{^/queue}) {
143 my $res = sprintf('%s jobs are left.', scalar @{$self->queue});
144 $stream->write("HTTP/1.1 200 OK\n\n");
145 $stream->write($res, sub {shift->close});
146 return;
147 }
148
149 if ($path =~ qr{^/dumper/(\w+)} && defined $self->{$1}) {
150 my $res = substr(dumper($self->{$1}), 0, $self->peeping_max_length);
151 $stream->write("HTTP/1.1 200 OK\n\n");
152 $stream->write($res, sub {shift->close});
153 return;
154 }
155
156 $stream->write(
157 "HTTP/1.1 404 NOT FOUND\n\nNOT FOUND", sub {shift->close});
158 });
159 }
160  
161 sub discover {
162 my ($self, $res, $job) = @_;
163
164 return if ($res->code != 200);
165 return if ($self->depth && $job->depth >= $self->depth);
166
167 my $base = $job->resolved_uri;
168 my $type = $res->headers->content_type;
169
170 if ($type && $type =~ qr{text/(html|xml)} &&
171 (my $base_tag = $res->dom->at('base'))) {
172 $base = resolve_href($base, $base_tag->attr('href'));
173 }
174
175 my $cb = sub {
176 my ($url, $dom) = @_;
177
178 $url = Mojo::URL->new($url);
179
180 return unless
181 (!$url->scheme || $url->scheme =~ qr{http|https|ftp|ws|wss});
182
183 my $child = $job->child(
184 resolved_uri => resolve_href($base, $url), literal_uri => $url);
185
186 $self->emit('refer', sub {
187 $self->enqueue($_[0] || $child);
188 }, $child, $dom || $job->resolved_uri);
189 };
190
191 if ($type && $type =~ qr{text/(html|xml)}) {
192 my $encode = guess_encoding($res) || 'utf-8';
193 my $body = Encode::decode($encode, $res->body);
194 collect_urls_html(Mojo::DOM->new($body), $cb);
195 }
196
197 if ($type && $type =~ qr{text/css}) {
198 my $encode = guess_encoding($res) || 'utf-8';
199 my $body = Encode::decode($encode, $res->body);
200 collect_urls_css($body, $cb);
201 }
202 };
203  
204 sub enqueue {
205 shift->_enqueue([@_]);
206 }
207  
208 sub requeue {
209 shift->_enqueue([@_], 1);
210 }
211  
212 sub _enqueue {
213 my ($self, $jobs, $requeue) = @_;
214
215 for my $job (@$jobs) {
216 if (! ref $job || ref $job ne 'WWW::Crawler::Mojo::Job') {
217 my $url = !ref $job ? Mojo::URL->new($job) : $job;
218 $job = WWW::Crawler::Mojo::Job->new(resolved_uri => $url);
219 }
220
221 my $md5 = md5_sum($job->resolved_uri->to_string);
222 if ($requeue || !exists $self->fix->{$md5}) {
223 $self->fix->{$md5} = undef;
224 push(@{$self->{queue}}, $job);
225 }
226 }
227 }
228  
229 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 my ($dom, $cb) = @_;
245
246 $dom->find(join(',', keys %tag_attributes))->each(sub {
247 my $dom = shift;
248 for (@{$tag_attributes{$dom->type}}) {
249 $cb->($dom->{$_}, $dom) if ($dom->{$_});
250 }
251 });
252 $dom->find('meta[http\-equiv=Refresh]')->each(sub {
253 my $dom = shift;
254 if (my $href = $dom->{content} && ($dom->{content} =~ qr{URL=(.+)}i)[0]) {
255 $cb->($href, $dom);
256 }
257 });
258 $dom->find('style')->each(sub {
259 my $dom = shift;
260 collect_urls_css($dom->content || '', sub { $cb->(shift, $dom) });
261 });
262 $dom->find('*[style]')->each(sub {
263 my $dom = shift;
264 collect_urls_css($dom->{style}, sub { $cb->(shift, $dom) });
265 });
266 }
267  
268 sub collect_urls_css {
269 my ($str, $cb) = @_;
270 $str =~ s{/\*.+?\*/}{}gs;
271 my @urls = ($str =~ m{url\(['"]?(.+?)['"]?\)}g);
272 $cb->($_) for (@urls);
273 }
274  
275 my $charset_re = qr{\bcharset\s*=\s*['"]?([a-zA-Z0-9_\-]+)['"]?}i;
276  
277 sub guess_encoding {
278 my $res = shift;
279 my $type = $res->headers->content_type;
280 return unless ($type);
281 my $charset = ($type =~ $charset_re)[0];
282 return $charset if ($charset);
283 return _guess_encoding_html($res->body) if ($type =~ qr{text/(html|xml)});
284 return _guess_encoding_css($res->body) if ($type =~ qr{text/css});
285 }
286  
287 sub _guess_encoding_css {
288 return (shift =~ qr{^\s*\@charset ['"](.+?)['"];}is)[0];
289 }
290  
291 sub _guess_encoding_html {
292 my $head = (shift =~ qr{<head>(.+)</head>}is)[0] or return;
293 my $charset;
294 Mojo::DOM->new($head)->find('meta[http\-equiv=Content-Type]')->each(sub{
295 $charset = (shift->{content} =~ $charset_re)[0];
296 });
297 return $charset;
298 }
299  
300 sub resolve_href {
301 my ($base, $href) = @_;
302 $href = ref $href ? $href : Mojo::URL->new($href);
303 $base = ref $base ? $base : Mojo::URL->new($base);
304 my $abs = $href->to_abs($base)->fragment(undef);
305 while ($abs->path->parts->[0] && $abs->path->parts->[0] =~ /^\./) {
306 shift @{$abs->path->parts};
307 }
308 $abs->path->trailing_slash($base->path->trailing_slash) if (!$href->path->to_string);
309 return $abs;
310 }
311  
312 sub _urls_redirect {
313 my $tx = shift;
314 my @urls;
315 @urls = _urls_redirect($tx->previous) if ($tx->previous);
316 unshift(@urls, $tx->req->url->userinfo(undef));
317 return @urls;
318 }
319  
320 sub _mod_busyness {
321 my ($self, $uri, $inc) = @_;
322 my $key = _host_key($uri);
323 my $hosts = $self->active_conns_per_host;
324
325 return if ($inc > 0 && ($self->active_conn >= $self->max_conn ||
326 ($hosts->{$key} || 0) >= $self->max_conn_per_host));
327
328 $self->{active_conn} += $inc;
329 $hosts->{$key} += $inc;
330 delete($hosts->{$key}) unless ($hosts->{$key});
331 return 1;
332 }
333  
334 sub _host_key {
335 my $uri = ref $_[0] ? $_[0] : Mojo::URL->new($_[0]);
336 my $key = $uri->scheme. '://'. $uri->ihost;
337
338 if (my $port = $uri->port) {
339 if (($uri->scheme eq 'https' && $port != 443) ||
340 ($uri->scheme eq 'http' && $port != 80)) {
341 $key .= ':'. $port;
342 }
343 }
344
345 return $key;
346 }
347  
348 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