#!/usr/bin/python
# http://aaa.b000.ru wallpaper rotate
from urllib2 import Request, urlopen, URLError, HTTPError
from subprocess import Popen, PIPE
import subprocess
import re, random, os, sys
BASE_URL = "http://aaa.b000.ru/size/1920x1200/"
OUTPUT_DIR = "~/pix/wp-random/"
def load_url(url, post_data=None):
user_agent = " >>> Webii Bot. [webii.ru] v.0.0.1"
headers = { 'User-Agent' : user_agent }
req = Request(url, post_data, headers) # POST data
try:
urlh = urlopen(req)
except HTTPError, e:
print url, ' failed, code : ', e.code
return False, False, e.code
except URLError, e:
print 'We failed to reach a server - ' + url
print 'Reason: ', e.reason
return False, False, e.code
info = urlh.info()
not_readed = True
i = 0
real_url = url
while not_readed:
try:
data = urlh.read()
except:
i = i + 1
if i>5:
not_readed = False
else:
not_readed = False
real_url = urlh.geturl()
urlh.close()
return data, real_url, urlh.info()
if __name__ == "__main__":
page = str(random.randint(0, 298))+"/"
data,a,b = load_url(BASE_URL+page)
if data:
img = re.compile(r'class="image" href="(.*?)"')
urls = img.findall(data)
if len(urls)>0:
wall, a,b = load_url(random.choice(urls))
if wall == False:
print "Can't download image"
sys.exit()
wallpaper = OUTPUT_DIR+str(random.randint(10000, 99999999))+".jpg"
while os.path.exists(wallpaper):
wallpaper = OUTPUT_DIR+str(random.randint(10000, 99999999))+".jpg"
f = open(wallpaper, 'w')
f.write(wall)
f.close()
p1 = Popen(["feh", "--bg-scale", wallpaper], stdout=PIPE)#, shell=e, env=en )
output = p1.communicate()[0]
else:
print "Can't download page"