Skip to content

Instantly share code, notes, and snippets.

@trygveaa
Created March 12, 2016 23:36
Show Gist options
  • Save trygveaa/0b6287bde3dfa6db221e to your computer and use it in GitHub Desktop.
Save trygveaa/0b6287bde3dfa6db221e to your computer and use it in GitHub Desktop.
Script to set a random background from desktopography or reddit
#!/usr/bin/perl
use strict;
use warnings;
use POSIX;
use File::Temp qw(tempfile);
use LWP::Simple qw($ua get getstore is_success);
if (rand > 0.5) {
set_background_from_desktopography();
} else {
set_background_from_reddit();
}
sub set_background_from_desktopography {
my $year = 2005 + int(rand 10);
my $page = get("http://www.desktopography.net/exhibition/$year")
or die "Couldn't fetch page: $!";
my @links = grep(/<a.*"\/exhibition\/$year\//, split(/\n/, $page));
my $failed_attempts = 0;
while ($failed_attempts++ < 5) {
$links[rand @links] =~ /.*href="([^"]*)".*/;
my $url = "http://www.desktopography.net$1/1920x1200/download";
set_background("desktopography", $url);
}
}
sub set_background_from_reddit {
my $posts_json = get("http://www.reddit.com/r/wallpaper+wallpapers+earthporn.json?limit=100")
or die "Couldn't fetch feed: $!";
$posts_json =~ s/.*?"children": \[.*?"data": \{//;
my @posts = split(/"data": \{/, $posts_json);
my $failed_attempts = 0;
while ($failed_attempts++ < 5) {
$posts[rand @posts] =~ /"permalink": "([^"]+)".*"url": "([^"]+)"/;
my $permalink = $1;
my $url = $2;
$url =~ s|//imgur.com/(.+)|//i.imgur.com/$1.jpg|;
set_background($permalink, $url);
}
}
sub set_background {
my ($name, $url) = @_;
my ($fh, $filename) = tempfile(UNLINK => 1);
if (is_success(getstore($url, $filename)) &&
system("feh", "--bg-fill", $filename) == 0) {
printf "Fetched %s %s\n", $name, $url;
exit;
} else {
printf STDERR "Failed %s %s\n", $name, $url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment