| 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 | use Data::Dumper; | ||
| 10 | |||
| 11 | our $VERSION = '0.01'; | ||
| 12 | |||
| 13 | sub new { | ||
| 14 | my $class = shift; | ||
| 15 | |||
| 16 | my $self = {}; | ||
| 17 | |||
| 18 | bless $self, $class; | ||
| 19 | |||
| 20 | return $self; | ||
| 21 | } | ||
| 22 | |||
| 23 | sub scrap { | ||
| 24 | my $self = shift; | ||
| 25 | my $config = shift; | ||
| 26 | |||
| 27 | my @subreddits = (); | ||
| 28 | |||
| 29 | foreach ( @{ $config->{subreddits} } ) { | ||
| 30 | my @posts = $self->getPosts($_); | ||
| 31 | |||
| 32 | push @subreddits, | ||
| 33 | { | ||
| 34 | name => $_->{name}, | ||
| 35 | url => "https://www.reddit.com/r/" . $_->{name}, | ||
| 36 | articles => \@posts | ||
| 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 = | ||
| 49 | $base | ||
| 50 | . $subreddit->{name} | ||
| 51 | . "/new.json?limit=" | ||
| 52 | . ( $subreddit->{limit} || 5 ); | ||
| 53 | my $r = HTTP::Request->new( 'GET', $url ); | ||
| 54 | my $ua = LWP::UserAgent->new(); | ||
| 55 | my $response = $ua->request($r); | ||
| 56 | |||
| 57 | my @subreddits = (); | ||
| 58 | |||
| 59 | if ( $response->is_success ) { | ||
| 60 | my $responseContent = decode_json $response->decoded_content; | ||
| 61 | my @children = @{ $responseContent->{data}->{children} }; | ||
| 62 | |||
| 63 | foreach (@children) { | ||
| 64 | my $text = $_->{data}->{title}; | ||
| 65 | $text =~ s/^\s+|\s+$//g; | ||
| 66 | |||
| 67 | push @subreddits, | ||
| 68 | { | ||
| 69 | text => encode( 'utf8', $text ), | ||
| 70 | link => $_->{data}->{url} | ||
| 71 | }; | ||
| 72 | } | ||
| 73 | } else { | ||
| 74 | die $response->status_line; | ||
| 75 | } | ||
| 76 | |||
| 77 | return @subreddits; | ||
| 78 | } | ||
| 79 | |||
| 80 | 1; | ||
| 81 | |||
| 82 | __END__ |