root/trunk/plagger/lib/Plagger/Plugin/Aggregator/Simple.pm

Revision 1333 (checked in by miyagawa, 14 years ago)

added Unicode tests. use XML::Atom's ForceUnicode? in Aggregator::Simple

  • Property svn:keywords set to Id Revision
Line 
1 package Plagger::Plugin::Aggregator::Simple;
2 use strict;
3 use base qw( Plagger::Plugin );
4
5 use Feed::Find;
6 use Plagger::Enclosure;
7 use Plagger::UserAgent;
8 use List::Util qw(first);
9 use UNIVERSAL::require;
10 use URI;
11 use XML::Feed;
12 use XML::Feed::RSS;
13
14 $XML::Feed::RSS::PREFERRED_PARSER = first { $_->require } qw( XML::RSS::Liberal XML::RSS::LibXML XML::RSS );
15
16 sub register {
17     my($self, $context) = @_;
18     $context->register_hook(
19         $self,
20         'customfeed.handle'  => \&aggregate,
21     );
22 }
23
24 sub aggregate {
25     my($self, $context, $args) = @_;
26
27     my $url = $args->{feed}->url;
28     my $res = $self->fetch_content($url) or return;
29
30     my $content_type = eval { $res->content_type } ||
31                        $res->http_response->content_type ||
32                        "text/xml";
33
34     $content_type =~ s/;.*$//; # strip charset= cruft
35
36     my $content = $res->content;
37     if ( $Feed::Find::IsFeed{$content_type} || $self->looks_like_feed(\$content) ) {
38         $self->handle_feed($url, \$content, $args->{feed});
39     } else {
40         $content = Plagger::Util::decode_content($res);
41         my @feeds = Feed::Find->find_in_html(\$content, $url);
42         if (@feeds) {
43             $url = $feeds[0];
44             $res = $self->fetch_content($url) or return;
45             $self->handle_feed($url, \$res->content, $args->{feed});
46         } else {
47             return;
48         }
49     }
50
51     return 1;
52 }
53
54 sub looks_like_feed {
55     my($self, $content_ref) = @_;
56     $$content_ref =~ m!<rss |<rdf:RDF\s+.*?xmlns="http://purl\.org/rss|<feed\s+xmlns="!s;
57 }
58
59 sub fetch_content {
60     my($self, $url) = @_;
61
62     my $context = Plagger->context;
63     $context->log(info => "Fetch $url");
64
65     my $agent = Plagger::UserAgent->new;
66        $agent->parse_head(0);
67     my $response = $agent->fetch($url, $self);
68
69     if ($response->is_error) {
70         $context->log(error => "GET $url failed: " .
71                       $response->http_status . " " .
72                       $response->http_response->message);
73         return;
74     }
75
76     # TODO: handle 301 Moved Permenently and 410 Gone
77     $context->log(debug => $response->status . ": $url");
78
79     $response;
80 }
81
82 sub handle_feed {
83     my($self, $url, $xml_ref, $feed) = @_;
84
85     my $context = Plagger->context;
86
87     my $args = { content => $$xml_ref };
88     $context->run_hook('aggregator.filter.feed', $args);
89
90     # override XML::LibXML with Liberal
91     my $sweeper; # XML::Liberal >= 0.13
92
93     eval { require XML::Liberal };
94     if (!$@ && $XML::Liberal::VERSION >= 0.10) {
95         $sweeper = XML::Liberal->globally_override('LibXML');
96     }
97
98     local $XML::Atom::ForceUnicode = 1;
99     my $remote = eval { XML::Feed->parse(\$args->{content}) };
100
101     unless ($remote) {
102         $context->log(error => "Parsing $url failed. " . ($@ || XML::Feed->errstr));
103         return;
104     }
105
106     $feed ||= Plagger::Feed->new;
107     $feed->title(_u($remote->title)) unless defined $feed->title;
108     $feed->url($url);
109     $feed->link($remote->link);
110     $feed->description(_u($remote->tagline)); # xxx should support Atom 1.0
111     $feed->language($remote->language);
112     $feed->author(_u($remote->author));
113     $feed->updated($remote->modified);
114     $feed->source_xml($$xml_ref);
115
116     if ($remote->format eq 'Atom') {
117         $feed->id( $remote->{atom}->id );
118     }
119
120     if ($remote->format =~ /^RSS/) {
121         $feed->image( $remote->{rss}->image )
122             if $remote->{rss}->image;
123     } elsif ($remote->format eq 'Atom') {
124         $feed->image({ url => $remote->{atom}->logo })
125             if $remote->{atom}->logo;
126     }
127
128     for my $e ($remote->entries) {
129         my $entry = Plagger::Entry->new;
130         $entry->title(_u($e->title));
131         $entry->author(_u($e->author));
132
133         my $category = $e->category;
134            $category = [ $category ] if $category && (!ref($category) || ref($category) ne 'ARRAY');
135         $entry->tags([ map _u($_), @$category ]) if $category;
136
137         # XXX XML::Feed doesn't support extracting atom:category yet
138         if ($remote->format eq 'Atom' && $e->{entry}->can('categories')) {
139             my @categories = $e->{entry}->categories;
140             for my $cat (@categories) {
141                 $entry->add_tag( _u($cat->label || $cat->term) );
142             }
143         }
144
145         my $date = eval { $e->issued } || eval { $e->modified };
146         $entry->date( Plagger::Date->rebless($date) ) if $date;
147
148         # xxx nasty hack. We should remove this once XML::Atom or XML::Feed is fixed
149         if (!$entry->date && $remote->format eq 'Atom' && $e->{entry}->version eq '1.0') {
150             if ( $e->{entry}->published ) {
151                 my $dt = XML::Atom::Util::iso2dt( $e->{entry}->published );
152                 $entry->date( Plagger::Date->rebless($dt) ) if $dt;
153             }
154         }
155
156         $entry->link($e->link);
157         $entry->feed_link($feed->link);
158         $entry->id($e->id);
159         $entry->body(_u($e->content->body || $e->summary->body));
160
161         # enclosure support, to be added to XML::Feed
162         if ($remote->format =~ /^RSS / and my $encls = $e->{entry}->{enclosure}) {
163             # some RSS feeds contain multiple enclosures, and we support them
164             $encls = [ $encls ] unless ref $encls eq 'ARRAY';
165
166             for my $encl (@$encls) {
167                 my $enclosure = Plagger::Enclosure->new;
168                 $enclosure->url( URI->new($encl->{url}) );
169                 $enclosure->length($encl->{length});
170                 $enclosure->auto_set_type($encl->{type});
171                 $entry->add_enclosure($enclosure);
172             }
173         } elsif ($remote->format eq 'Atom') {
174             for my $link ( grep { defined $_->rel && $_->rel eq 'enclosure' } $e->{entry}->link ) {
175                 my $enclosure = Plagger::Enclosure->new;
176                 $enclosure->url( URI->new($link->href) );
177                 $enclosure->length($link->length);
178                 $enclosure->auto_set_type($link->type);
179                 $entry->add_enclosure($enclosure);
180             }
181         }
182
183         # TODO: move MediaRSS, Hatena, iTunes and those specific parser to be subclassed
184
185         # Media RSS
186         my $media_ns = "http://search.yahoo.com/mrss";
187         my $media = $e->{entry}->{$media_ns}->{group} || $e->{entry};
188         my $content = $media->{$media_ns}->{content} || [];
189            $content = [ $content ] unless ref $content && ref $content eq 'ARRAY';
190
191         for my $media_content (@{$content}) {
192             my $enclosure = Plagger::Enclosure->new;
193             $enclosure->url( URI->new($media_content->{url}) );
194             $enclosure->auto_set_type($media_content->{type});
195             $entry->add_enclosure($enclosure);
196         }
197
198         if (my $thumbnail = $media->{$media_ns}->{thumbnail}) {
199             $entry->icon({
200                 url   => $thumbnail->{url},
201                 width => $thumbnail->{width},
202                 height => $thumbnail->{height},
203             });
204         }
205
206         # Hatena Image extensions
207         my $hatena = $e->{entry}->{"http://www.hatena.ne.jp/info/xmlns#"} || {};
208         if ($hatena->{imageurl}) {
209             my $enclosure = Plagger::Enclosure->new;
210             $enclosure->url($hatena->{imageurl});
211             $enclosure->auto_set_type;
212             $entry->add_enclosure($enclosure);
213         }
214
215         if ($hatena->{imageurlsmall}) {
216             $entry->icon({ url   => $hatena->{imageurlsmall} });
217         }
218
219         # Apple photocast feed
220         my $apple = $e->{entry}->{"http://www.apple.com/ilife/wallpapers"} || {};
221         if ($apple->{image}) {
222             my $enclosure = Plagger::Enclosure->new;
223             $enclosure->url( URI->new($apple->{image}) );
224             $enclosure->auto_set_type;
225             $entry->add_enclosure($enclosure);
226         }
227         if ($apple->{thumbnail}) {
228             $entry->icon({ url => $apple->{thumbnail} });
229         }
230
231         my $args = {
232             entry      => $entry,
233             feed       => $feed,
234             orig_entry => $e,
235             orig_feed  => $remote,
236         };
237         $context->run_hook('aggregator.entry.fixup', $args);
238
239         $feed->add_entry($entry);
240     }
241
242     $context->log(info => "Aggregate $url success: " . $feed->count . " entries.");
243     $context->update->add($feed);
244 }
245
246 sub _u {
247     my $str = shift;
248     Encode::_utf8_on($str);
249     $str;
250 }
251
252 1;
253
254 __END__
255
256 =head1 NAME
257
258 Plagger::Plugin::Aggregator::Simple - Dumb simple aggregator
259
260 =head1 SYNOPSIS
261
262   - module: Aggregator::Simple
263
264 =head1 DESCRIPTION
265
266 This plugin implements a Plagger dumb aggregator. It crawls
267 subscription sequentially and parses XML feeds using L<XML::Feed>
268 module.
269
270 It can be also used as a base class for custom aggregators. See
271 L<Plagger::Plugin::Aggregator::Xango> for example.
272
273 =head1 AUTHOR
274
275 Tatsuhiko Miyagawa
276
277 =head1 SEE ALSO
278
279 L<Plagger>, L<XML::Feed>, L<XML::RSS::LibXML>
280
281 =cut
Note: See TracBrowser for help on using the browser.