blib/lib/Web/PageMeta.pm

filter: Statementstmt 94.5% 173 / 183 Branchbran 71.0% 27 / 38 Conditioncond 78.5% 11 / 14 MC/DCmcdc 57.1% 4 / 7 Subroutinesub 94.2% 33 / 35 Podpod 0.0% 0 / 1 totaltotal 89.2% 248 / 278 CC 29 SCAR 14.8
CC
29
Cov
90%
_build__fetch_page_meta_ft
13.1
compile_headers
4.4
__ANON__
4.0
CRAP 4.4
↑ Summary Build »
1 package Web::PageMeta;
2  
3 3 our $VERSION = '0.07';
4  
5 3 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use MooseX::Types::URI qw(Uri);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use MooseX::StrictConstructor;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Future '0.44';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use Future::HTTP::AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use Web::Scraper::LibXML;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use Encode qw(find_mime_encoding);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use HTTP::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use List::Util qw(pairmap);
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 3 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 3 has 'url' => (
24 isa => Uri,
25 is => 'ro',
26 required => 1,
27 coerce => 1,
28 );
29  
30 3 has 'timeout' => (
31 isa => 'Int',
32 is => 'rw',
33 required => 1,
34 default => 5 * 60,
35 );
36  
37 3 has 'max_size' => (
38 isa => 'Int',
39 is => 'rw',
40 required => 1,
41 default => 100 * 1024 * 1024,
42 );
43  
44 3 has 'user_agent' => (
45 isa => 'Str',
46 is => 'ro',
47 required => 1,
48 default =>
49 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
50 lazy => 1,
51 );
52  
53 has 'extra_headers' => (
54 isa => 'HashRef',
55 is => 'ro',
56 required => 1,
57 18 ▶ default => sub {{}},
Subroutine __ANON__: called CC=1 SCAR=0.0
58 3 lazy => 1,
59 );
60  
61 3 has 'cookie_jar' => (
62 isa => 'Object',
63 is => 'ro',
64 predicate => 'has_cookie_jar',
65 );
66  
67 has 'title' => (
68 isa => 'Str',
69 is => 'ro',
70 lazy => 1,
71 7 ▶ default => sub {return $_[0]->page_meta->{title} // ''},
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]->page_meta->{"title"} // ""
l!l
30
MC/DC0%0/1
$_[0]->page_meta->{"title"} // ""
$_[0]->page_meta->{"title"}
Truth table50%1/2
A
A= $_[0]->page_meta->{"title"}
Aresult
11
00
72 3 );
73 has 'image' => (
74 isa => 'Str',
75 is => 'ro',
76 lazy => 1,
77 12 ▶ default => sub {return $_[0]->page_meta->{image} // ''},
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]->page_meta->{"image"} // ""
l!l
110
MC/DC0%0/1
$_[0]->page_meta->{"image"} // ""
$_[0]->page_meta->{"image"}
Truth table50%1/2
A
A= $_[0]->page_meta->{"image"}
Aresult
11
00
78 3 );
79 has 'description' => (
80 isa => 'Str',
81 is => 'ro',
82 lazy => 1,
83 1 ▶ default => sub {return $_[0]->page_meta->{description} // ''},
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]->page_meta->{"description"} // ""
l!l
10
MC/DC0%0/1
$_[0]->page_meta->{"description"} // ""
$_[0]->page_meta->{"description"}
Truth table50%1/2
A
A= $_[0]->page_meta->{"description"}
Aresult
11
00
84 3 );
85  
86 has 'image_data' => (
87 isa => 'Str',
88 is => 'ro',
89 lazy => 1,
90 2 ▶ default => sub {$_[0]->fetch_image_data_ft->get},
Subroutine __ANON__: called CC=1 SCAR=0.0
91 3 );
92  
93 has 'page_meta' => (
94 isa => 'HashRef',
95 is => 'rw',
96 lazy => 1,
97 10 ▶ default => sub {$_[0]->fetch_page_meta_ft->get},
Subroutine __ANON__: called CC=1 SCAR=0.0
98 3 );
99  
100 has 'page_body_hdr' => (
101 isa => 'ArrayRef',
102 is => 'ro',
103 lazy => 1,
104 0 ▶ default => sub {$_[0]->fetch_page_body_hdr_ft->get},
Subroutine __ANON__: not called CC=1 SCAR=6.9
105 3 );
106  
107 3 has 'fetch_page_body_hdr_ft' => (
108 isa => 'Future',
109 is => 'ro',
110 lazy => 1,
111 builder => '_build__fetch_page_body_hdr_ft',
112 );
113  
114 3 has 'fetch_page_meta_ft' => (
115 isa => 'Future',
116 is => 'ro',
117 lazy => 1,
118 builder => '_build__fetch_page_meta_ft',
119 );
120  
121 3 has 'fetch_image_data_ft' => (
122 isa => 'Future',
123 is => 'ro',
124 lazy => 1,
125 builder => '_build__fetch_image_data_ft',
126 );
127  
128 has '_ua' => (
129 is => 'ro',
130 lazy => 1,
131 2 ▶ default => sub {Future::HTTP::AnyEvent->new()},
Subroutine __ANON__: called CC=1 SCAR=0.0
132 3 );
133  
134 3 has '_html_meta_scraper' => (
135 is => 'ro',
136 lazy => 1,
137 builder => '_build__html_meta_scraper',
138 );
139  
140 3 has 'extra_scraper' => (
141 is => 'ro',
142 predicate => 'has_extra_scraper',
143 );
144  
145 sub _build__html_meta_scraper {
146 state $html_meta_scraper = scraper {
147 11 ▶ process '/html/head/meta[contains(@property, "og:")]',
Subroutine __ANON__: called CC=1 SCAR=0.0
148 'head_meta_og[]' => {
149 key => '@property',
150 val => '@content',
151 };
152 11 process '/html/head/title', 'title' => 'TEXT';
153 11 process '/html/head/meta[@name="description"]', 'description' => '@content';
154 11 process '/html/head/base', 'base_href' => '@href';
155 11 ▶ };
Subroutine _build__html_meta_scraper: called CC=1 SCAR=0.0
156 11 return $html_meta_scraper;
157 }
158  
159 sub compile_headers {
160 26 ▶ my ($self) = @_;
Subroutine compile_headers: called CC=3 SCAR=14.7
Pod undocumented
161  
162 26 my %headers = (
163 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
164 'User-Agent' => $self->user_agent,
165 );
166 26 ▶ if ($self->has_cookie_jar) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_cookie_jar) 0 26 26
167 0 my $cookies = $self->cookie_jar->get_cookies($self->url);
168 0 ▶ if (%$cookies) {
Branch: 1 branch
BranchTrueFalseTotal
if (%$cookies) 0 0 0
169 0 ▶ $headers{'Cookie'} = join("; ", pairmap {$a . "=" . $b} %$cookies);
Subroutine __ANON__: not called CC=1 SCAR=6.9
170 0 $headers{'Cookie2'} = '$Version="1"';
171 }
172 }
173 26 %headers = (%headers, %{$self->extra_headers});
174 26 return \%headers;
175 }
176  
177 18 ▶async sub _build__fetch_page_body_hdr_ft {
Subroutine _build__fetch_page_body_hdr_ft: called CC=2 SCAR=6.9
178 18 my ($self) = @_;
179  
180 # await url htmp http download
181 18 my $timer = time();
182 18 my $timeout = $self->timeout;
183 18 my $timeout_at = $timer + $timeout;
184 18 my $max_size = $self->max_size;
185 18 my $cur_size = 0;
186 18 my $body = '';
187 my ( undef, $headers ) = await $self->_ua->http_get(
188 $self->url,
189 headers => $self->compile_headers,
190 timeout => $timeout,
191 on_header => sub {
192 12 ▶ my ($hdrs) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
193 12 ▶ my $content_type = $hdrs->{"content-type"} || '';
Condition100%2/2
$hdrs->{'content-type'} || ''
l!l
111
MC/DC100%1/1
$hdrs->{'content-type'} || ''
$hdrs->{'content-type'}
Truth table100%2/2
A
A= $hdrs->{'content-type'}
Aresult
11
00
194 12 ▶ if ($content_type =~ /^text\/html\s*(?:;|$)/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($content_type =~ m[^text/html\s*(?:;|$)]i) { } 9 3 12
elsif ($hdrs->{'Status'} != 200) { } 2 1 3
195 9 return 1;
196 }
197 elsif ($hdrs->{Status} != 200) {
198 # non-200 status handled below with exception
199 2 return 1;
200 }
201 else {
202 $log->warnf( 'unsupported content-type "%s", status "%d", fetching %s',
203 1 $content_type, $hdrs->{Status}, $self->url );
204 1 return 0;
205 }
206 },
207 on_body => sub {
208 17 ▶ my ( $part_body, undef ) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
209  
210 17 $body .= $part_body;
211  
212 17 ▶ if ( time() > $timeout_at ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Web::PageMeta::time() > $timeout_at) 1 16 17
213 1 $log->warnf( 'timeout %ds fetching %s',
214 $timeout, $self->url );
215 1 return 0;
216 }
217  
218 16 $cur_size += length($part_body);
219 16 ▶ if ($cur_size > $max_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_size > $max_size) 1 15 16
220 1 $log->warnf( 'max size %d exceeded with %d fetching %s',
221 $max_size, $cur_size, $self->url );
222 1 return 0;
223 }
224  
225 15 return 1;
226 },
227 18 );
228 13 my $status = _get_update_status_reason($headers);
229 13 $log->debugf('page meta fetch %d %s finished in %.3fs', $status, $self->url, time() - $timer);
230 HTTP::Exception->throw($status, status_message => $headers->{Reason})
231 13 ▶ if ($status != 200);
Branch: 1 branch
BranchTrueFalseTotal
if $status != 200 2 11 13
232  
233 11 return [$body, $headers];
234 3 }
235  
236 18 ▶async sub _build__fetch_page_meta_ft {
Subroutine _build__fetch_page_meta_ft: called CC=13 SCAR=25.7
237 18 my ($self) = @_;
238  
239 18 my ( $body, $headers ) = @{await $self->fetch_page_body_hdr_ft};
240  
241 # turn body to utf-8
242 11 ▶ if (my $content_type = $headers->{'content-type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $content_type = $headers->{"content-type"}) 5 6 11
243 5 ▶ if (my ($charset) = ($content_type =~ m/\bcharset=(.+)/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($charset) = $content_type =~ /\bcharset=(.+)/) 5 0 5
244 5 ▶ if (my $decoder = find_mime_encoding($charset)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $decoder = &find_mime_encoding($charset)) 5 0 5
245 5 $body = $decoder->decode($body);
246 }
247 }
248 }
249  
250 # scrape default head meta
251 11 my $scraper_data = $self->_html_meta_scraper->scrape(\$body);
252 my %page_meta = (
253 title => $scraper_data->{title} // '',
254 11 ▶ description => $scraper_data->{description} // '',
Condition100%4/4
$scraper_data->{"title"} // ""
l!l
38
$scraper_data->{"description"} // ""
l!l
38
MC/DC100%1/1
$scraper_data->{"title"} // ""
$scraper_data->{"title"}
MC/DC100%1/1
$scraper_data->{"description"} // ""
$scraper_data->{"description"}
Truth table100%2/2
A
A= $scraper_data->{"title"}
Aresult
11
00
Truth table100%2/2
A
A= $scraper_data->{"description"}
Aresult
11
00
255 );
256 11 ▶ foreach my $attr (@{$scraper_data->{head_meta_og} // []}) {
Condition100%2/2
$scraper_data->{"head_meta_og"} // []
l!l
101
MC/DC100%1/1
$scraper_data->{"head_meta_og"} // []
$scraper_data->{"head_meta_og"}
Truth table100%2/2
A
A= $scraper_data->{"head_meta_og"}
Aresult
11
00
257 19 my $key = $attr->{key};
258 19 my $val = $attr->{val};
259 19 ▶ next unless $key =~ m/^og:(.+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $key =~ /^og:(.+)$/ 0 19 19
260 19 $page_meta{$1} = $val;
261 }
262  
263 # do any other extra scraping
264 11 ▶ if ($self->has_extra_scraper) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_extra_scraper) 1 10 11
265 1 my $escraper_data = $self->extra_scraper->scrape(\$body);
266 1 foreach my $key (keys %{$escraper_data}) {
267 1 $page_meta{$key} = $escraper_data->{$key};
268 }
269 }
270  
271 # make image links absolute
272 11 ▶ if ($page_meta{image}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($page_meta{"image"}) 11 0 11
273 my $base_url = (
274 $scraper_data->{base_href}
275 11 ▶ ? URI::WithBase->new($scraper_data->{base_href}, $self->url)->abs->as_string
Branch: 1 branch
BranchTrueFalseTotal
$scraper_data->{'base_href'} ? : 2 9 11
276 : $self->url
277 );
278 11 $page_meta{image} = URI::WithBase->new($page_meta{image}, $base_url)->abs->as_string;
279 }
280  
281 11 return $self->page_meta(\%page_meta);
282 3 }
283  
284 8 ▶async sub _build__fetch_image_data_ft {
Subroutine _build__fetch_image_data_ft: called CC=3 SCAR=11.4
285 8 my ($self) = @_;
286  
287 # await for image link
288 8 await $self->fetch_page_meta_ft;
289 8 my $fetch_url = $self->image;
290 8 ▶ HTTP::Exception->throw(404, status_message => 'No image found')
Branch: 1 branch
BranchTrueFalseTotal
unless $fetch_url 0 8 8
291 unless $fetch_url;
292  
293 # await image http download
294 8 my $timer = time();
295 8 my $timeout = $self->timeout;
296 8 my $timeout_at = $timer + $timeout;
297 8 my $max_size = $self->max_size;
298 8 my $cur_size = 0;
299 8 my $body = '';
300 my ( undef, $headers ) = await $self->_ua->http_get(
301 $fetch_url,
302 headers => $self->compile_headers,
303 on_body => sub {
304 8 ▶ my ( $part_body, undef ) = @_;
Subroutine __ANON__: called CC=3 SCAR=13.1
305  
306 8 $body .= $part_body;
307  
308 8 ▶ if ( time() > $timeout_at ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Web::PageMeta::time() > $timeout_at) 0 8 8
309 0 $log->warnf( 'timeout %ds fetching %s',
310 $timeout, $self->url );
311 0 return 0;
312 }
313  
314 8 $cur_size += length($part_body);
315 8 ▶ if ( $cur_size > $max_size ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_size > $max_size) 0 8 8
316 0 $log->warnf( 'max size %d exceeded with %d fetching %s',
317 $max_size, $cur_size, $self->url );
318 0 return 0;
319 }
320  
321 8 return 1;
322 },
323 8 );
324 8 my $status = _get_update_status_reason($headers);
325 8 $log->debugf('img fetch %d %s for %s finished in %.3fs',
326 $status, $fetch_url, $self->url, time() - $timer);
327 HTTP::Exception->throw($status, status_message => $headers->{Reason})
328 8 ▶ if ($status != 200);
Branch: 1 branch
BranchTrueFalseTotal
if $status != 200 0 8 8
329  
330 8 return $self->{image_data} = $body;
331 3 }
332  
333 sub _get_update_status_reason {
334 21 ▶ my ($headers) = @_;
Subroutine _get_update_status_reason: called CC=2 SCAR=6.9
335 21 my $status = $headers->{Status};
336 21 ▶ unless (HTTP::Status::status_message($status)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&HTTP::Status::status_message($status)) 1 20 21
337 1 $headers->{Reason} = sprintf('(%d) %s', $status, $headers->{Reason});
338 1 $status = $headers->{Status} = 503;
339 }
340 21 return $status;
341 }
342  
343 3 __PACKAGE__->meta->make_immutable;
344  
345 3 1;
346  
347 __END__
348  
349 =head1 NAME
350  
351 Web::PageMeta - get page open-graph / meta data
352  
353 =head1 SYNOPSIS
354  
355 use Web::PageMeta;
356 my $page = Web::PageMeta->new(url => "https://www.apa.at/");
357 say $page->title;
358 say $page->image;
359  
360 async fetch previews and images:
361  
362 use Web::PageMeta;
363 my @urls = qw(
364 https://www.apa.at/
365 http://www.diepresse.at/
366 https://metacpan.org/
367 https://github.com/
368 );
369 my @page_views = map { Web::PageMeta->new( url => $_ ) }
370 @urls;
371 Future->wait_all( map { $_->fetch_image_data_ft, } @page_views )->get;
372 foreach my $pv (@page_views) {
373 say 'title> '.$pv->title;
374 say 'img_size> '.length($pv->image_data);
375 }
376  
377 # alternativelly instead of Future->wait_all()
378 use Future::Utils qw( fmap_void );
379 fmap_void(
380 sub { return $_[0]->fetch_image_data_ft },
381 foreach => [@page_views],
382 concurrent => 3
383 )->get;
384  
385 =head1 DESCRIPTION
386  
387 Get (not only) open-graph web page meta data. can be used in both normal
388 and async code.
389  
390 For any other than 200 http status codes during data downloads,
391 L<HTTP::Exception> is thrown.
392  
393 =head1 ACCESSORS
394  
395 =head2 new
396  
397 Constructor, only L</url> is required.
398  
399 =head2 url
400  
401 HTTP url to fetch data from.
402  
403 =head2 timeout
404  
405 In addition to L<AnyEvent::HTTP> timeout will also check time during download
406 as the data are being downloaded and dies when over the limit. Default 5
407 minutes.
408  
409 =head2 max_size
410  
411 Will die when the document or image size is greater than this limit.
412 Default 100MB.
413  
414 =head2 user_agent
415  
416 User-Agent header to use for http requests.
417 Default is one from Chrome 89.0.4389.90.
418  
419 =head2 extra_headers
420  
421 HashRef with extra http request headers.
422  
423 =head2 cookie_jar
424  
425 Accepts optional L<HTTP::Cookies> compatible object that must provide
426 C<get_cookies()> method. If set will send http cookie headers with each
427 request.
428  
429 =head2 title
430  
431 Returns title of the page.
432  
433 =head2 description
434  
435 Returns description of the page.
436  
437 =head2 image
438  
439 Returns image location of the page.
440  
441 =head2 image_data
442  
443 Returns image binary data of L</image> link.
444  
445 Will throw 404 exception if there is not L</image> link.
446  
447 =head2 page_meta
448  
449 Returns hash ref with all open-graph data.
450  
451 =head2 extra_scraper
452  
453 L<Web::Scraper::LibXML> object to fetch image, title or description from different
454 than default location.
455  
456 use Web::Scraper::LibXML;
457 use Web::PageMeta;
458 my $escraper = scraper {
459 process_first '.slider .camera_wrap div', 'image' => '@data-src';
460 };
461 my $wmeta = Web::PageMeta->new(
462 url => 'https://www.meon.eu/',
463 extra_scraper => $escraper,
464 );
465  
466 =head2 page_body_hdr
467  
468 Returns array ref with page [$body,$headers]. Can be useful for
469 post-processing or special/additional data extractions.
470  
471 Only C<text/html> content-type is accepted for fetching.
472  
473 =head2 fetch_page_meta_ft
474  
475 Returns future object for fetching paga meta data. See L</"ASYNC USE">.
476 On done L</page_meta> hash is returned.
477  
478 =head2 fetch_image_data_ft
479  
480 Returns future object for fetching image data. See L</"ASYNC USE">
481 On done L</image_data> scalar is returned.
482  
483 =head2 fetch_page_body_hdr_ft
484  
485 Returns future object for fetching page content and headers. See L</"ASYNC USE">
486 On done L</page_body_hdr> array ref is returned.
487  
488 =head1 ASYNC USE
489  
490 To run multiple page meta data or image http requests in parallel or
491 to be used in async programs L</fetch_page_meta_ft> and L<fetch_image_data_ft>
492 returning L<Future> object can be used. See L</SYNOPSIS> or F<t/02_async.t>
493 for sample use.
494  
495 =head1 SEE ALSO
496  
497 L<https://ogp.me/>
498  
499 =head1 AUTHOR
500  
501 Jozef Kutej, C<< <jkutej at cpan.org> >>
502  
503 =head1 LICENSE AND COPYRIGHT
504  
505 Copyright 2021 jkutej@cpan.org
506  
507 This program is free software; you can redistribute it and/or modify it
508 under the terms of either: the GNU General Public License as published
509 by the Free Software Foundation; or the Artistic License.
510  
511 See http://dev.perl.org/licenses/ for more information.
512  
513 =cut
↑ Summary Build »