| 1 | package Fancazzista::Scrap::RedditScrapper; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use LWP::UserAgent; | ||
| 6 | use HTTP::Request; | ||
| 7 | use JSON; | ||
| 8 | use Encode qw(encode); | ||
| 9 | |||
| 10 | our $VERSION = '1.00'; | ||
| 11 | |||
| 12 | sub new { | ||
| 13 | my $class = shift; | ||
| 14 | |||
| 15 | my $self = {}; | ||
| 16 | |||
| 17 | bless $self, $class; | ||
| 18 | |||
| 19 | return $self; | ||
| 20 | } | ||
| 21 | |||
| 22 | sub scrap { | ||
| 23 | my $self = shift; | ||
| 24 | my $config = shift; | ||
| 25 | |||
| 26 | my @subreddits = (); | ||
| 27 | |||
| 28 | foreach ( @{ $config->{subreddits} } ) { | ||
| 29 | my @posts = $self->getPosts($_); | ||
| 30 | |||
| 31 | push @subreddits, | ||
| 32 | { | ||
| 33 | name => $_->{name}, | ||
| 34 | url => "https://www.reddit.com/r/" . $_->{name}, | ||
| 35 | articles => \@posts, | ||
| 36 | from_reddit => 1, | ||
| 37 | }; | ||
| 38 | } | ||
| 39 | |||
| 40 | return @subreddits; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub getPosts { | ||
| 44 | my $self = shift; | ||
| 45 | my $subreddit = shift; | ||
| 46 | |||
| 47 | my $base = "https://www.reddit.com/r/"; | ||
| 48 | my $url = $base . $subreddit->{name} . "/new.json?limit=" . ( $subreddit->{limit} || 5 ); | ||
| 49 | my $r = HTTP::Request->new( 'GET', $url ); | ||
| 50 | my $ua = LWP::UserAgent->new(); | ||
| 51 | my $response = $ua->request($r); | ||
| 52 | |||
| 53 | my @subreddits = (); | ||
| 54 | |||
| 55 | if ( $response->is_success ) { | ||
| 56 | my $responseContent = decode_json $response->decoded_content; | ||
| 57 | my @children = @{ $responseContent->{data}->{children} }; | ||
| 58 | |||
| 59 | foreach (@children) { | ||
| 60 | my $text = $_->{data}->{title}; | ||
| 61 | $text =~ s/^\s+|\s+$//g; | ||
| 62 | |||
| 63 | push @subreddits, | ||
| 64 | { | ||
| 65 | text => encode( 'utf8', $text ), | ||
| 66 | link => $_->{data}->{url} | ||
| 67 | }; | ||
| 68 | } | ||
| 69 | } else { | ||
| 70 | die $response->status_line; | ||
| 71 | } | ||
| 72 | |||
| 73 | return @subreddits; | ||
| 74 | } | ||
| 75 | |||
| 76 | 1; | ||
| 77 | |||
| 78 | __END__ |