Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Created April 15, 2012 00:56
Show Gist options
  • Save perrygeo/2389085 to your computer and use it in GitHub Desktop.
Save perrygeo/2389085 to your computer and use it in GitHub Desktop.
reddit_wallpaper: Gnome wallpaper switcher
#!/usr/bin/python
#reddit wallpaper rotate #Scialex
import json, gconf, syslog, os, random
from urllib2 import urlopen
SAVE_LOCATION = os.path.join(os.path.expanduser('~'), '.background_getter')
GCONF_KEY = '/desktop/gnome/background/picture_filename'
PICTURE_ENDINGS=['png','jpg','gif']
JSON_PAGE = 'http://www.reddit.com/r/earthporn.json' # '+' seperated
IMGUR_JSON_FORMAT = "http://api.imgur.com/2/image/{0}.json"
JSON_CACHE = "/home/mperry/.redditpics.json"
def main():
try:
content = urlopen(JSON_PAGE).read()
print "got reddit feed, caching"
open(JSON_CACHE, 'w').write(content)
except:
print "just use cached reddit feed"
content = open(JSON_CACHE, 'r').read()
json_data = json.loads(content)["data"]["children"]
imageconn, post_id, ext = get_image_data(json_data)
save_name = os.path.join(SAVE_LOCATION, "".join((post_id,'.', ext)))
open(save_name, 'wb').write(imageconn.read())
set_as_background(save_name)
return
def get_image_data(data):
pics = range(0,len(data))
random.shuffle(pics)
for x in pics:
child = data[x]
if child["data"]["domain"] == "i.imgur.com":
url = child["data"]["url"]
print 'found %s, link was direct to i.imgur.com' % url
imgconn = urlopen(url)
if imgconn.headers.maintype == 'image':
return imgconn, child['data']['id'], url.split('.')[-1]
elif child['data']['url'].split('.')[-1] in PICTURE_ENDINGS:
url = child['data']['url']
print 'found %s, link was direct to a non-imgur site' % url
imgconn = urlopen(url)
if imgconn.headers.maintype == 'image':
return imgconn, child['data']['id'], url.split('.')[-1]
elif child["data"]["domain"] == "imgur.com":
name = child["data"]["url"].split('/')[-1]
newdata = json.loads(urlopen(IMGUR_JSON_FORMAT.format(name)).read())
url = newdata["image"]['links']["original"]
print 'found %s, link was not direct' % url
imgconn = urlopen(url)
if imgconn.headers.maintype == 'image':
return imgconn, child['data']['id'], url.split('.')[-1]
print "none of the possibilities could be used"
raise Exception("could not get url")
def set_as_background_old(file_location):
client = gconf.client_get_default()
worked = client.set_string(GCONF_KEY,file_location)
client.suggest_sync()
if worked:
print 'changed the background succsessfully'
else:
print 'was unable to change the background'
raise Exception("could not set gconf key")
return
def set_as_background(img):
"GNOME specific!"
os.system("gsettings set org.gnome.desktop.background picture-uri file://%s" % os.path.abspath(img))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment