Last active
December 13, 2015 22:28
-
-
Save dmtrs/4984301 to your computer and use it in GitHub Desktop.
Random Tumblr photo on my desktop background (Gnome)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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']) { | |
++$r; | |
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, implode('.',array($post->blog_name, $post->id))); | |
$wait=(isset($config['sleep']) ? $config['sleep'] : 60); | |
for($i=0;$i<$wait;$i++) | |
{ | |
echo '.'; | |
sleep(1); | |
} | |
echo "\n"; | |
} | |
} | |
function setBackground($url, $name='tumblr_backgroud_image') | |
{ | |
$filename = __DIR__.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$name; | |
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"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment