| 1 | package Plagger::Plugin::Filter::Delicious; | ||
| 2 | use strict; | ||
| 3 | use base qw( Plagger::Plugin ); | ||
| 4 | |||
| 5 | use Digest::MD5 qw(md5_hex); | ||
| 6 | use Plagger::UserAgent; | ||
| 7 | use XML::Feed; | ||
| 8 | |||
| 9 | sub register { | ||
| 10 | my($self, $context) = @_; | ||
| 11 | $context->register_hook( | ||
| 12 | $self, | ||
| 13 | 'update.entry.fixup' => \&update, | ||
| 14 | ); | ||
| 15 | } | ||
| 16 | |||
| 17 | sub update { | ||
| 18 | my($self, $context, $args) = @_; | ||
| 19 | |||
| 20 | my $interval = $self->conf->{interval} || 1; | ||
| 21 | sleep $interval; | ||
| 22 | |||
| 23 | my $md5 = md5_hex($args->{entry}->permalink); | ||
| 24 | my $url = "http://del.icio.us/rss/url/$md5"; | ||
| 25 | |||
| 26 | $self->log(info => "Going to fetch $url"); | ||
| 27 | |||
| 28 | my $ua = Plagger::UserAgent->new; | ||
| 29 | my $res = $ua->fetch($url); | ||
| 30 | |||
| 31 | if ($res->is_error) { | ||
| 32 | $self->log(error => "Fetch URL $url failed."); | ||
| 33 | return; | ||
| 34 | } | ||
| 35 | |||
| 36 | my $feed = XML::Feed->parse(\$res->content); | ||
| 37 | |||
| 38 | unless ($feed) { | ||
| 39 | $context->log(warn => "Feed error $url: " . XML::Feed->errstr); | ||
| 40 | return; | ||
| 41 | } | ||
| 42 | |||
| 43 | for my $entry ($feed->entries) { | ||
| 44 | my @tag = split / /, ($entry->category || ''); | ||
| 45 | @tag or next; | ||
| 46 | |||
| 47 | for my $tag (@tag) { | ||
| 48 | $args->{entry}->add_tag($tag); | ||
| 49 | } | ||
| 50 | } | ||
| 51 | |||
| 52 | my $delicious_users = $feed->entries; | ||
| 53 | if ($delicious_users >= 30 && $self->conf->{scrape_big_numbers}) { | ||
| 54 | my $url = "http://del.icio.us/url/$md5"; | ||
| 55 | $self->log(info => "users count is more than 30. Trying to scrape from $url."); | ||
| 56 | sleep $interval; | ||
| 57 | |||
| 58 | my $res = $ua->fetch($url); | ||
| 59 | |||
| 60 | if ($res->is_error) { | ||
| 61 | $context->log(warn => "Fetch error $url: " . $res->http_response->message); | ||
| 62 | return; | ||
| 63 | } | ||
| 64 | |||
| 65 | $delicious_users = | ||
| 66 | ( $res->content =~ m#<h4[^>]*>[^<>]*this url has been saved by\D+(\d+)#s )[0]; | ||
| 67 | } | ||
| 68 | $args->{entry}->meta->{delicious_rate} = rate_of_color($delicious_users); | ||
| 69 | $args->{entry}->meta->{delicious_users} = $delicious_users; | ||
| 70 | $self->log(info => "set delicious_users to $delicious_users"); | ||
| 71 | } | ||
| 72 | |||
| 73 | sub rate_of_color { | ||
| 74 | my $n = shift; | ||
| 75 | return 100 unless $n; | ||
| 76 | int(log($n) / log(0.82) + 100); | ||
| 77 | } | ||
| 78 | |||
| 79 | 1; | ||
| 80 | |||
| 81 | __END__ |