Skip to content

Instantly share code, notes, and snippets.

@leedo
Created April 27, 2011 17:44
Show Gist options
  • Save leedo/944770 to your computer and use it in GitHub Desktop.
Save leedo/944770 to your computer and use it in GitHub Desktop.
redirect to a random image from rss feed list
use Plack::Builder;
use AnyEvent::Feed;
my $feeds = {};
my $img_re = qr{https?://[^\s]+\.(?:gif|png|jpe?g)}i;
sub add_feed {
my $url = shift;
$feeds->{$url} = {
images => [],
feed => AnyEvent::Feed->new(
url => $url,
interval => 60 * 60, # every hour
on_fetch => sub {
my ($reader, $new, $feed, $error) = @_;
return unless @$new;
my @images = map {($_->content->body =~ /($img_re)/g)} $feed->entries;
$feeds->{$url}{images} = \@images;
},
),
};
}
sub random_image {
my @urls = keys %$feeds;
my $url = $urls[ rand @urls ];
my @images = @{ $feeds->{$url}{images} };
return $images[ rand @images ];
}
add_feed 'http://cutegirlsbeingcute.tumblr.com/rss';
add_feed 'http://getoutoftherecat.tumblr.com/rss';
add_feed 'http://thisiswhyyourefat.tumblr.com/rss';
builder {
mount "/" => sub {
my $env = shift;
return [301, [Location => random_image], []];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment