Change quotesite to use BettIrssi, clean up module hierarchy for the plugins
[quotesite.git] / quotesite / TwitterGrabber.pm
1 # (c) 2010 by Ralf Ertzinger <ralf@camperquake.de>
2 # licensed under GNU GPL v2
3 #
4 # Grabber for twitter
5
6 package quotesite::TwitterGrabber;
7
8 use quotesite::GrabberBase;
9 @ISA = qw(quotesite::GrabberBase);
10
11 use LWP::Simple qw(!get);
12 use Data::Dumper;
13 use XML::Simple;
14 use HTML::Entities qw(decode_entities);
15 use Encode;
16
17 use strict;
18
19 sub new {
20     my $class = shift;
21     my $self = $class->SUPER::new();
22
23     $self->{'NAME'} = 'twitter.com';
24     $self->{'PATTERNS'} = ['(https?://twitter.com/(?:\#\!/)?[^/]+/status(?:es)?/(\d+))'];
25
26     bless($self, $class);
27     $self->_prepare_parameters();
28
29     return $self;
30 }
31
32 sub _parse {
33     my $self = shift;
34     my $url = shift;
35     my $pattern = shift;
36     my $content;
37     my $metadata = {};
38     my $p = XML::Simple->new();
39     my $t;
40
41     $url =~ m|$pattern|;
42     $url = $1;
43
44     $metadata->{'URL'} = $url;
45     $metadata->{'ID'} = $2;
46     $metadata->{'TYPE'} = 'quote';
47     $metadata->{'SOURCE'} = $self->{'NAME'};
48     $metadata->{'CONTENT'} = undef;
49
50     # Get the XML file containing the quote
51     unless(defined($content = LWP::Simple::get(sprintf('http://api.twitter.com/1/statuses/show/%s.xml', $2)))) {
52         $self->error('Could not download quote');
53         return undef;
54     }
55
56     unless(defined($t = $p->XMLin($content))) {
57         $self->error('Could not parse XML metadata');
58         return undef;
59     }
60
61     $metadata->{'CONTENT'} = decode_entities($t->{'text'});
62     $metadata->{'ID'} = $t->{'user'}->{'screen_name'} . '/' . $metadata->{'ID'};
63
64     unless(defined($metadata->{'CONTENT'})) {
65         $self->error('Could not extract quote content');
66         return undef;
67     }
68
69     return $metadata;
70 }
71
72 1;