lib/WWW/Monitor/Task.pm untested

filter: Statementstmt 0.0% 0 / 232 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 24 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 369 CC 28 SCAR 32.1
CC
28
Cov
0%
get_url_data
90.0
sync_cache
30.0
run
20.0
CRAP 24.8
1 #WWW/monitor.pm. Written in 2007 by Yaron Kahanoitch. This
2 # source code has been placed in the public domain by the author.
3 # Please be kind and preserve the documentation.
4  
5  
6 package WWW::Monitor::Task;
7  
8  
9 #use 5.008;
10 use warnings;
11 use strict;
12 use HTTP::Response;
13 use HTTP::Request;
14 use HTTP::Headers;
15 use HTTP::Status;
16 use HTML::TreeBuilder;
17 #use Carp;
18  
19  
20  
21 our(@ISA, @EXPORT, @EXPORT_OK, $VERSION);
22  
23 $VERSION = 0.24;
24  
25 @ISA = qw(
26 Exporter
27 );
28 @EXPORT = qw ();
29 @EXPORT_OK = qw ();
30  
31 our $HASH_SEPARATOR = "\n";
32 our $HASH_KEY_PREFIX = "__HASH_KEY__";
33  
34 =head1 NAME
35  
36 WWW::Monitor::Task - A Task class for monitoring single web page
37 against a cached version.
38  
39 =head1 VERSION
40  
41 Version 0.1
42  
43 =cut
44  
45 =head1 Description
46  
47 This class is responsible for tracking a single web page and reporting
48 changes. This class should be considered as a private asset of
49 L<WWW::Monitor>. For details please refer to <WWW::Monitor>
50  
51 =head1 EXPORT
52  
53 =head1 FUNCTIONS
54  
55 =head2 new
56  
57 A constructor.
58  
59 =cut
60  
61 sub new {
62 my $this = shift;
63 my %arg;
64 unless (@_ % 2) {
65 %arg = @_;
66 } else {
67 carp ("Parameters for WWW::Monitor::Task should be given as pair of 'OPTION'=>'VAL'");
68 }
69 my $class = ref($this) || $this;
70 my $self = {};
71 carp ("Url is not given") unless exists $arg{URL};
72 $self->{url} = $arg{URL};
73 $self->{cache} = $arg{CACHE};
74 bless($self, $class);
75 }
76  
77 =head2 run ( mechanize, carrier, <cache>)
78  
79 Executes Task. Parameters:
80  
81 mechanize - Web mechanize object.
82  
83 L<WWW::Monitor::Task> assumes that the given object implements or
84 inherits WWW::mechnize abstraction. See
85 L<http://search.cpan.org/~petdance/WWW-Mechanize-1.20/lib/WWW/Mechanize.pm>.
86  
87 carrier- Object which will conduct the notification; see L<WWW::Monitor> for details
88  
89 cache - optional - A cache class.
90  
91 =cut
92  
93 sub run {
94 my $self = shift;
95 $self->{error} = "";
96 my ($mechanize,$carrier) = (shift,shift);
97 my $cache = "";
98 if (@_) { $cache = shift;}
99 my $url_i = $self->{url};
100 $self->{cache} = $cache if ($cache);
101 my $responses = {};
102  
103 #Get Url data. Output data is stored in the hash ref $responses.
104 $self->get_url_data($mechanize,$url_i,$responses) or return 0;
105  
106 #Compares Pages list with cache.
107 my ($url_keys_for_comapre,$old_pages_to_compare,$new_pagets_to_compare,$missing_pages,$added_pages,$existsInCache) = $self->sync_cache($url_i,$responses);
108  
109 # if a page does not exist in cache we don't want to notify this
110 return 1 unless ($existsInCache);
111  
112 #Activate Notification.
113 $self->be_notified($carrier,$url_i,$missing_pages,$added_pages,$old_pages_to_compare,$new_pagets_to_compare,$url_keys_for_comapre);
114 return 1;
115 }
116  
117 =head2 be_notified
118  
119 (Private method)
120 Tests if a page has changed. If yes, notification call back is being called.
121  
122 =cut
123  
124 sub be_notified {
125 my $self = shift;
126 my $notify_ind = 0;
127 my ($carrier,$url,$missing_pages,$added_pages,$old_pages_to_compare,$new_pages_to_compare,$url_keys_for_comapre) = @_;
128 my $cache = $self->{cache};
129 my $ret = 1;
130 #Extract textual information from missing pages.
131 $self->{missing_parts} = $missing_pages;
132 my $notify_ind1 = values(%$missing_pages);
133  
134 #Extract added information from added pages.
135 $self->{added_parts} = $added_pages;
136 my $notify_ind2 = values(%$added_pages);
137
138 my $index = 0;
139 #Go over on all pages that exists in cache and perform textual comparison
140 $self->{changed} = {};
141 if (@$old_pages_to_compare) {
142 while ($index < scalar(@$old_pages_to_compare)) {
143 my $t1 = $self->format_html($old_pages_to_compare->[$index]);
144 my $t2 = $self->format_html($new_pages_to_compare->[$index]);
145
146 if ($$t1 ne $$t2) {
147 my $tmp = [$old_pages_to_compare->[$index], $new_pages_to_compare->[$index] ];
148 $self->{changed}{$url_keys_for_comapre->[$index]} = $tmp;
149 $cache->set($url_keys_for_comapre->[$index],$new_pages_to_compare->[$index]->as_string);
150 $notify_ind = 1;
151 }
152 ++$index;
153 }
154 }
155  
156  
157 #If notification is required, perform it.
158 if ($notify_ind or $notify_ind1 or $notify_ind2) {
159 $self->{time1} = HTTP::Date::time2str($self->validity($url));
160 $self->{time2} = HTTP::Date::time2str(time());
161 $self->store_validity($url,time());
162 return $carrier->notify($url,$self);
163 } else { return 1;}
164 }
165  
166 =head2 is_html
167  
168 (Private method)
169 Return true if page is html
170  
171 =cut
172  
173 sub is_html {
174 my $self = shift;
175 my $response = shift;
176 return $response->header('Content-Type') =~ m%^text/html%;
177 }
178  
179 =head2 missing_parts
180  
181 Return hash reference which includes parts that exists only in old cached version. Every entry in the returned list is a reference to HTTP::REsponse object.
182  
183 =cut
184  
185 sub missing_parts {
186 my $self = shift;
187 return $self->{missing_parts};
188 }
189  
190 =head2 added_parts
191  
192 Return hash reference which includes parts that exists only in the new cached version.Every entry in the returned list is a reference to HTTP::REsponse object.
193  
194 =cut
195  
196 sub added_parts {
197 my $self = shift;
198 return $self->{added_parts};
199 }
200  
201 =head2 old_version_time_stamp
202  
203 Return the time when the url was previously cached. Time is returned in seconds since epoch.
204  
205 =cut
206  
207 sub old_version_time_stamp {
208 my $self = shift;
209 return $self->{time1};
210 }
211  
212 =head2 new_version_time_stamp
213  
214 Return the time when the url was queried. Time is returned in seconds since epoch.
215  
216 =cut
217  
218 sub new_version_time_stamp {
219 my $self = shift;
220 return $self->{time2};
221 }
222  
223 =head2 changed_parts
224  
225 Return a list that consists of all changed parts.
226  
227 =cut
228  
229 sub changed_parts {
230 my $self = shift;
231 return keys %{$self->{changed}};
232 }
233  
234 =head2 get_old_new_pair [ urls key ]
235  
236 Return a list of two elements. The first one is the old cached version and the second one is the new version.
237 The given url key must be one of the keys returned by changed_parts method.
238 Each of the pair two pairs is a reference to L<HTTP::Response> object.
239  
240  
241  
242 =cut
243  
244 sub get_old_new_pair {
245 my $self = shift;
246 my $url_key = shift;
247 if (exists $self->{changed}{$url_key}) {
248 return @{$self->{changed}{$url_key}};
249 } else {
250 return 0;
251 }
252 }
253  
254 =head2 format_html [ leftmargin, rightmargin]
255  
256 Return a textual version of HTML
257 left and right margins set the margin for the returned data.
258  
259 =cut
260  
261 sub format_html {
262 my $self = shift;
263 my $response_ref = shift;
264 my $leftmargin = 0;
265 my $rightmargin = 120;
266  
267 if (@_) {
268 $leftmargin = shift;
269 $rightmargin = shift;
270 }
271
272 my $reftype = ref($response_ref);
273 if (($reftype ne 'REF') and $self->is_html($response_ref)) {
274 my $tree = HTML::TreeBuilder->new->parse($response_ref->content);
275 my $formatter = HTML::FormatText->new(leftmargin => $leftmargin, rightmargin => $rightmargin);
276 my $ret = $formatter->format($tree);
277 return \$ret;
278 } elsif ($reftype eq 'REF') { #Backward compatibility case to ver 0.126
279 my $tree = HTML::TreeBuilder->new->parse($response_ref);
280 my $formatter = HTML::FormatText->new(leftmargin => $leftmargin, rightmargin => $rightmargin);
281 my $ret = $formatter->format($tree);
282 return \$ret;
283 } else { #We have non html data
284 my $content = $response_ref->content;
285 return \$content;
286 }
287 }
288  
289 =head2 get_hash_cache_key
290  
291 (Private method)
292 Return a hash key that stores information about the entire visible part or the URL.
293  
294 =cut
295  
296 sub get_hash_cache_key {
297 my $self = shift;
298 my $url = shift;
299 return $HASH_KEY_PREFIX.$url;
300 }
301  
302 =head2 get_cache_hash
303  
304 (Private Method)
305 Returns all urls which were last cached.
306 return true if the url was previously hashed.
307  
308 =cut
309  
310 sub get_cache_hash {
311 my ($self,$url,$is_cached_site) = @_;
312 my $cache = $self->{cache};
313 my $ret = {};
314 $$is_cached_site = 1;
315 my $hash_key = $self->get_hash_cache_key($url);
316 $cache->exists($hash_key) or do { $$is_cached_site = 0;return 0;};
317 foreach $hash_key (split($HASH_SEPARATOR, $cache->get($hash_key))) {
318 my $tmp = $cache->get($hash_key);
319 my $tmp2 = HTTP::Response->parse( $tmp );
320 if ($tmp2) {
321 $ret->{$hash_key} = $tmp2;
322 } else { #Backward compatibility to version 0.126
323 $ret->{$hash_key} = \$tmp;
324 }
325 }
326 return $ret;
327 }
328  
329 =head2 store_validity
330  
331 (Private method)
332 Store current time in the main hash key
333  
334 =cut
335  
336 sub store_validity {
337 my ($self,$url) = (@_);
338 my $cache = $self->{cache};
339 my $hash_key = $self->get_hash_cache_key($url);
340 $cache->set_validity($hash_key,time()) if ($cache->exists($hash_key));
341 return 1;
342
343 }
344  
345 =head2 validity
346  
347 (private method)
348 Retreive date validity of per stores url
349  
350 =cut
351  
352 sub validity {
353 my ($self,$url) = (@_);
354 my $cache = $self->{cache};
355 my $hash_key = $self->get_hash_cache_key($url);
356 if ($cache->exists($hash_key)) {
357 return $cache->validity($hash_key);
358 }
359 return 0;
360 }
361  
362 =head2 store_cache_hash
363  
364 Store General information of a web address, including all frames and dates.
365  
366 =cut
367  
368 sub store_cache_hash {
369 my ($self,$url,$data,$added_data,$deleted_data) = (@_);
370 my $cache = $self->{cache};
371 my $hash_key = $self->get_hash_cache_key($url);
372 my $header = join($HASH_SEPARATOR,keys %$data);
373 $cache->set($hash_key,join($HASH_SEPARATOR,keys %$data));
374 while (my ($key,$value) = each %$added_data) {
375 $cache->set($key,$value->as_string);
376 $cache->set_validity($key,time());
377 }
378 while (my ($key2,$value2) = each %$deleted_data) {
379 $cache->purge($key2,$value2);
380 }
381 return 1;
382 }
383  
384 =head2 sync_cache
385  
386 (Private method)
387  
388 =cut
389  
390  
391 #sync_cache (Privatre method) takes newly retrieved data, and stores and compresses it with
392 # the cache data. That is, It returns as follows:
393 # might_be_changed - Urls that are included in the retrieved pages and are in the cache.
394 # Those pages are potentialy changed, and therefore should be examinated by HTML comparison.
395 # deleted_data - Pages which exist in the cache and not in the new set.
396 # added_data - Pages which exist only in the new version.
397 # In addition, the sub purges all deleted pages from cache and stores the added pages.
398 # Due to performance reasons, all the "might_be_changed" pages are not cached.
399 # This is left for the caller to do.
400 sub sync_cache {
401 my ($self,$url,$new_data_http) = @_;
402 my $cache = $self->{cache};
403 my $is_cached_site;
404 my $old_data = $self->get_cache_hash($url,\$is_cached_site);
405 my ($added_data,$deleted_data) = ({},{});
406 my @old_pages_to_compare;
407 my @new_pages_to_compare;
408 my @url_keys_for_comapre;
409 my $index_new = 0;my $index_old = 0;
410 my @new_keys = sort (keys %$new_data_http);
411 my @old_keys = ($old_data)?(sort(keys %$old_data)):();
412 # print "Scalars: ", scalar(@new_keys), "==",scalar(@old_keys),"\n";
413 while ($index_new < scalar(@new_keys) and $index_old < scalar(@old_keys)) {
414 if ($new_keys[$index_new] eq $old_keys[$index_old]) {
415 if ($new_data_http->{$new_keys[$index_new]}->code() != RC_NOT_MODIFIED) {
416 push @old_pages_to_compare, $old_data->{ $old_keys[$index_old]};
417 my $a_response = $new_data_http->{$new_keys[$index_new]};
418 push @new_pages_to_compare, $a_response;
419 push @url_keys_for_comapre,$new_keys[$index_new];
420 }
421 ++$index_old;++$index_new;next;
422 }
423 if ($new_keys[$index_new] lt $old_keys[$index_old]) {
424 my $a_response = $new_data_http->{$new_keys[$index_new]};
425 $added_data->{$new_keys[$index_new]} = $a_response;
426 ++$index_new;
427 next;
428 }
429 $deleted_data->{$old_keys[$index_old]} = $old_data->{$old_keys[$index_old]};
430 ++$index_old;next;
431 }
432 while ($index_new < scalar(@new_keys)) {
433 my $a_response = $new_data_http->{$new_keys[$index_new]};
434 $added_data->{$new_keys[$index_new]} = $a_response;
435 ++$index_new;
436 }
437 while ($index_old < scalar(@old_keys)) {
438 $deleted_data->{$old_keys[$index_old]} = $old_data->{$old_keys[$index_old]};
439 ++$index_old;
440 }
441 # print "Goota cache\n";
442 $self->store_cache_hash($url,$new_data_http,$added_data,$deleted_data) or die ("Cannot store $url in cache");
443 return (\@url_keys_for_comapre,\@old_pages_to_compare,\@new_pages_to_compare,$deleted_data,$added_data,$is_cached_site);
444 }
445  
446 =head2 get_url_data
447  
448 (Private method)
449  
450 =cut
451  
452 # get_url_data recurses over all pages which construct a given web page--including all type
453 # of included frames and dynamic pages--and retrieves them into a given hash reference
454 # $response.
455 sub get_url_data {
456 my $self = shift;
457 my $mechanize = shift;
458 my $url = shift;
459 my $responses = shift;
460 my $cache = $self->{cache};
461 my $r = HTTP::Request->new('GET',$url);
462 # Only allow "identity" for the time being
463 $r->header( 'Accept-Encoding', 'identity' );
464 if ($cache->exists($url)) {
465 my $validity = $cache->validity($url);
466 $r->header('If-Modified-Since'=>HTTP::Date::time2str($cache->validity($url))) if ($validity);
467 }
468 my $response = $mechanize->request( $r );
469
470 if ($response->code() == 304) {
471 $response = HTTP::Response->parse($cache->get($url));
472 $mechanize->_update_page($r,$response);
473 } elsif(!($self->{status} = $response->is_success())) {
474 $self->{error} = $response->status_line;
475 return 0;
476 }
477 $responses->{$url} = $response;
478 my $frames = [];
479 my $output = $mechanize->find_all_links( tag_regex => qr/^([ia]?frame)$/i);
480 push @$frames,@$output if ($output);
481 $output = $mechanize->find_all_links( tag_regex => qr/meta/);
482 push @$frames,@$output if ($output);
483  
484 foreach my $link (@$frames) {
485 next unless ($link->url_abs =~ m%^http.*//%);
486 unless (exists $responses->{$link->url_abs()}) {
487 $self->get_url_data($mechanize,$link->url_abs(),$responses) or return 0;
488 }
489 }
490 return 1;
491 }
492  
493 =head2 success
494  
495 return true upon success of the last run execution.
496  
497 =cut
498  
499 sub success {
500 my $self = shift;
501 return $self->{status};
502 }
503  
504  
505 =head1 AUTHOR
506  
507 Yaron Kahanovitch, C<< <yaron-helpme at kahanovitch.com> >>
508  
509 =head1 BUGS
510  
511 Please report any bugs or feature requests to
512 C<bug-www-monitor at rt.cpan.org>, or through the web interface at
513 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=WWW-Monitor>.
514 I will be notified, and then you'll automatically be notified of progress on
515 your bug as I make changes.
516  
517 =head1 SUPPORT
518  
519 You can find documentation for this module with the perldoc command. perldoc WWW::Monitor
520 You can also look for information at:
521  
522 =over 4
523  
524 =item * AnnoCPAN: Annotated CPAN documentation
525  
526 L<http://annocpan.org/dist/WWW-Monitor>
527  
528 =item * CPAN Ratings
529  
530 L<http://cpanratings.perl.org/d/WWW-Monitor>
531  
532 =item * RT: CPAN's request tracker
533  
534 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=WWW-Monitor>
535  
536 =item * Search CPAN
537  
538 L<http://search.cpan.org/dist/WWW-Monitor>
539  
540 =back
541  
542 =head1 ACKNOWLEDGMENTS
543  
544 =head1 COPYRIGHT & LICENSE
545  
546 Copyright 2007 Yaron Kahanovitch, all rights reserved.
547  
548 This program is free software; you can redistribute it and/or modify it
549 under the same terms as Perl itself.
550  
551 1; # End of WWW::Monitor::Task