Plagger/Plugin/Subscription/OPML.pm untested

filter: Statementstmt 0.0% 0 / 69 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 112 CC 6 SCAR 15.5
CC
6
Cov
0%
start_element
12.0
load_opml
6.0
end_element
6.0
CRAP 4.7
1 package Plagger::Plugin::Subscription::OPML;
2 use strict;
3 use base qw( Plagger::Plugin );
4  
5 use Plagger::Util;
6 use URI;
7 use XML::LibXML::SAX;
8  
9 our $HAS_LIBERAL;
10 BEGIN {
11 eval { require XML::Liberal; $HAS_LIBERAL = 1 };
12 }
13  
14 sub register {
15 my($self, $context) = @_;
16  
17 $context->register_hook(
18 $self,
19 'subscription.load' => \&load,
20 );
21 }
22  
23 sub load {
24 my($self, $context) = @_;
25 my $uri = URI->new($self->conf->{url})
26 or $context->error("config 'url' is missing");
27  
28 $self->load_opml($context, $uri);
29 }
30  
31 sub load_opml {
32 my($self, $context, $uri) = @_;
33  
34 my $xml = Plagger::Util::load_uri($uri, $self);
35  
36 if ($HAS_LIBERAL) {
37 my $parser = XML::Liberal->new('LibXML');
38 my $doc = $parser->parse_string($xml);
39 $xml = $doc->toString;
40 }
41  
42 my $handler = Plagger::Plugin::Subscription::OPML::SAXHandler->new(
43 callback => sub { $context->subscription->add(@_) },
44 );
45  
46 my $parser = XML::LibXML::SAX->new(Handler => $handler);
47 $parser->parse_string($xml);
48 }
49  
50 package Plagger::Plugin::Subscription::OPML::SAXHandler;
51 use base qw( XML::SAX::Base );
52  
53 sub new {
54 my $class = shift;
55 bless { @_ }, $class;
56 }
57  
58 sub start_element {
59 my $self = shift;
60 my($ref) = @_;
61  
62 if ($ref->{LocalName} eq 'outline') {
63 if (_attr($ref, 'htmlUrl', 'xmlUrl')) {
64 my $feed = Plagger::Feed->new;
65 $feed->url(_attr($ref, 'xmlUrl'));
66 $feed->link(_attr($ref, 'htmlUrl'));
67 $feed->title(_attr($ref, 'title', 'text'));
68 $feed->tags([ grep { defined && $_ ne 'Subscriptions' } @{$self->{containers}} ]);
69 $self->{callback}->($feed);
70 } else {
71 my $tag = _attr($ref, 'title', 'text');
72 push @{$self->{containers}}, $tag;
73 }
74 }
75 }
76  
77 sub end_element {
78 my $self = shift;
79 my($ref) = @_;
80  
81 if ($ref->{LocalName} eq 'outline') {
82 pop @{$self->{containers}};
83 }
84 }
85  
86 sub _attr {
87 my($ref, @attr) = @_;
88  
89 for my $attr (@attr) {
90 return $ref->{Attributes}->{"{}$attr"}->{Value}
91 if defined $ref->{Attributes}->{"{}$attr"};
92 }
93  
94 return;
95 }
96  
97 package Plagger::Plugin::Subscription::OPML;
98  
99 1;
100  
101 __END__