Last Updated: February 25, 2016
·
1.839K
· dmtrs

Random Tumblr photo on my desktop background (Gnome)

I heavily use tumblr lately so I though of creating a script that will update my desktop’s background image on Gnome every some seconds with a random image from some tumblr blogs I like.

#!/usr/bin/php
<?php
$config = array(
    'api_key' => 'get your api key from http://www.tumblr.com/oauth/apps',
    'sleep'   => 45,
    'debug'   => true,
    'blogs'   => array(
        'whiteshoe',
        'devopsreactions',
        'afr0diti',
        //...
    )
);
if(empty($config['api_key']))
    throw new Exception('Api key is empty');

if(empty($config['blogs']))
    throw new Exception('Blogs can not be empty array');
$r=0;
while(true) {
    $blog_url = url($config['blogs'], $config['api_key']);
    $response = json_decode(get($blog_url));
    $posts = ($response->meta->status == 200) ? $response->response->posts : array();
    if(isset($config['debug']) && $config['debug']) {
        echo "[debug] request {$r}, {$response->meta->status} @ {$blog_url}\n";
    }
    if(!empty($posts)) {
        mt_srand(time());
        $rand  = mt_rand(0, count($posts)-1);
        $post  = $posts[$rand];
        printDetails($post);
        $photo = array_shift($post->photos);
        $url   = $photo->original_size->url;
        setBackground($url);
        sleep(isset($config['sleep']) ? $config['sleep'] : 60);
    }
}

function setBackground($url)
{
    $filename = __DIR__.DIRECTORY_SEPARATOR.'tumblr_backgroud_image';
    file_put_contents($filename, file_get_contents($url));
    exec('gsettings set org.gnome.desktop.background picture-uri file:///'.$filename);
}

function url($blog, $key)
{
    if(is_array($blog)) {
        $x    = array_rand($blog);
        $blog = $blog[$x];
    }
    return "http://api.tumblr.com/v2/blog/{$blog}.tumblr.com/posts/photo?api_key={$key}";
}
function get($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, '30');
    $content = trim(curl_exec($ch));
    curl_close($ch);
    return $content;
}

function printDetails($post)
{
    foreach(array('blog_name','id','post_url','caption') as $info)
    {
        echo $post->{$info};
        echo "\n";
    }
    echo "\n";
}

Code is on gist:4984301, comments and improvements are welcome. Mac OS version to come soon...