def save_wallpaper(): if not os.path.exists(config.savedir): os.makedirs(config.savedir) config.log(config.savedir + " created") if not os.path.isfile(config.savedir + '/titles.txt'): with open(config.savedir + '/titles.txt', 'w') as f: f.write('Titles of the saved wallpapers:') config.log(config.savedir + "/titles.txt created") wpcount = 0 origpath = config.walldir newpath = config.savedir if config.opsys == "Windows": origpath = origpath + ('\\wallpaper.bmp') while os.path.isfile(config.savedir + '\\wallpaper' + str(wpcount) + '.bmp'): wpcount += 1 newpath = newpath + ('\\wallpaper' + str(wpcount) + '.bmp') else: origpath = origpath + ('/wallpaper.jpg') while os.path.isfile(config.savedir + '/wallpaper' + str(wpcount) + '.jpg'): wpcount += 1 newpath = newpath + ('/wallpaper' + str(wpcount) + '.jpg') shutil.copyfile(origpath, newpath) with open(config.walldir + '/title.txt', 'r') as f: title = f.read() with open(config.savedir + '/titles.txt', 'a') as f: f.write('\n' + 'wallpaper' + str(wpcount) + ': ' + title) print("Current wallpaper saved to " + newpath)
def choose_valid(links): if len(links) == 0: print("No links were returned from any of those subreddits. Are they valid?") sys.exit(1) for i, origlink in enumerate(links): link = origlink[0] config.log("checking link # {0}: {1}".format(i, link)) if not (link[-4:] == '.png' or link[-4:] == '.jpg' or link[-5:] == '.jpeg'): if re.search('(imgur\.com)(?!/a/)', link): link = link.replace("/gallery", "") link += ".jpg" else: continue if not (connection.connected(link) and check_dimensions(link) and check_blocklist(link)): continue def check_same_url(link): with open(config.walldir + '/url.txt', 'r') as f: currlink = f.read() if currlink == link: print("current wallpaper is the most recent, will not re-download the same wallpaper.") sys.exit(0) else: return True if config.force_dl or not (os.path.isfile(config.walldir + '/url.txt')) or check_same_url(link): return [link, origlink[1], origlink[2]] print("No valid links were found from any of those subreddits. Try increasing the maxlink parameter.") sys.exit(0)
def choose_valid(links): if len(links) == 0: print("No links were returned from any of those subreddits. Are they valid?") sys.exit(1) for i, origlink in enumerate(links): link = origlink[0] config.log("checking link # {0}: {1}".format(i, link)) if not (link[-4:] == '.png' or link[-4:] == '.jpg' or link[-5:] == '.jpeg'): if re.search('(imgur\.com)(?!/a/)', link): link = link.replace("/gallery", "") link += ".jpg" else: continue if not (connection.connected(link) and check_dimensions(link) and check_blacklist(link)): continue def check_same_url(link): with open(config.walldir + '/url.txt', 'r') as f: currlink = f.read() if currlink == link: print("current wallpaper is the most recent, will not re-download the same wallpaper.") sys.exit(0) else: return True if config.force_dl or not (os.path.isfile(config.walldir + '/url.txt')) or check_same_url(link): return [link, origlink[1], origlink[2]] print("No valid links were found from any of those subreddits. Try increasing the maxlink parameter.") sys.exit(0)
def get_links(): print("searching for valid images...") if config.randomsub: parsedsubs = pick_random(config.subs) else: parsedsubs = config.subs[0] for sub in config.subs[1:]: parsedsubs = parsedsubs + '+' + sub url = "http://www.reddit.com/r/" + parsedsubs + "/" + config.sortby + ".json?limit=" + str(config.maxlinks) config.log("Grabbing json file " + url) uaurl = request.Request(url, headers={ 'User-Agent': 'wallpaper-reddit python script, github.com/markubiak/wallpaper-reddit'}) response = request.urlopen(uaurl) content = response.read().decode('utf-8') try: data = json.loads(content) except (AttributeError, ValueError): print( 'Was redirected from valid Reddit formatting. Likely a router redirect, such as a hotel or airport.' 'Exiting...') sys.exit(0) response.close() links = [] for i in data["data"]["children"]: links.append([i["data"]["url"], i["data"]["title"], "http://reddit.com" + i["data"]["permalink"]]) return links
def set_image_title(img, title): config.log("setting title") title = remove_tags(title) draw = ImageDraw.Draw(img) font = ImageFont.truetype(config.walldir + '/fonts/Cantarell-Regular.otf', size=config.titlesize) x = 0 y = 0 if config.titlealign_x == "left": x = config.titleoffset_x elif config.titlealign_x == "center": text_x = font.getsize(title)[0] x = (img.size[0] - text_x)/2 elif config.titlealign_x == "right": text_x = font.getsize(title)[0] x = img.size[0] - text_x - config.titleoffset_x if config.titlealign_y == "top": y = config.titleoffset_y elif config.titlealign_y == "bottom": text_y = font.getsize(title)[1] y = img.size[1] - text_y - config.titleoffset_y # shadow = Image.new('RGBA', img.size, (255,255,255,0)) # shadowdraw = ImageDraw.Draw(shadow) # shadowdraw.text((x+2, y+2), title, font=font, fill=(255,255,255)) draw.text((x+2, y+2), title, font=font, fill=(0, 0, 0, 127)) draw.text((x, y), title, font=font) del draw return img
def set_image_title(img, title): config.log("setting title") title = remove_tags(title) draw = ImageDraw.Draw(img) font = ImageFont.truetype(config.walldir + '/fonts/Cantarell-Regular.otf', size=config.titlesize) x = 0 y = 0 if config.titlealign_x == "left": x = config.titleoffset_x elif config.titlealign_x == "center": text_x = font.getsize(title)[0] x = (img.size[0] - text_x) / 2 elif config.titlealign_x == "right": text_x = font.getsize(title)[0] x = img.size[0] - text_x - config.titleoffset_x if config.titlealign_y == "top": y = config.titleoffset_y elif config.titlealign_y == "bottom": text_y = font.getsize(title)[1] y = img.size[1] - text_y - config.titleoffset_y draw.text((x + 2, y + 2), title, font=font, fill=(0, 0, 0, 127)) draw.text((x, y), title, font=font) del draw return img
def download_image(url, title): uaurl = request.Request( url, headers={ 'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7' }) f = request.urlopen(uaurl) print("downloading " + url) try: img = Image.open(f) if config.resize: config.log("resizing the downloaded wallpaper") img = ImageOps.fit(img, (config.minwidth, config.minheight), Image.ANTIALIAS) if config.settitle: img = set_image_title(img, title) if config.opsys == "Windows": img.convert('RGB').save(config.walldir + '\\wallpaper.bmp', "BMP") else: img.convert('RGB').save(config.walldir + '/wallpaper.jpg', "JPEG") except IOError: print("Error saving image!") sys.exit(1)
def check_dimensions(url): resp = request.urlopen(request.Request(url, headers={ 'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7', 'Range': 'bytes=0-16384' })) try: with Image.open(resp) as img: dimensions = img.size if dimensions[0] >= config.minwidth and dimensions[1] >= config.minheight: config.log("Size checks out") return True except IOError: config.log("Image dimensions could not be read") return False
def check_dimensions(url): resp = request.urlopen(request.Request(url, headers={ 'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7', 'Range': 'bytes=0-16384' })) try: with Image.open(resp) as img: dimensions = img.size if (dimensions[0] / dimensions[1]) >= config.minratio: if dimensions[0] >= config.minwidth and dimensions[1] >= config.minheight: config.log("Size checks out") return True except IOError: config.log("Image dimensions could not be read") return False
def run(): try: config.init_config() # blacklist the current wallpaper if requested if config.blacklistcurrent: reddit.blacklist_current() # check if the program is run in a special case (save or startup) if config.save: wallpaper.save_wallpaper() sys.exit(0) if config.autostartup: if config.opsys == "Linux": dfile = resource_string(__name__, 'conf_files/linux-autostart.desktop') path = os.path.expanduser("~/.config") + "/autostart" if not os.path.exists(path): os.makedirs(path) config.log(path + " created") with open(path + "/wallpaper-reddit.desktop", "wb") as f: f.write(dfile) print("Autostart file created at " + path) sys.exit(0) else: print( "Automatic startup creation only currently supported on Linux" ) sys.exit(1) if config.startup: connection.wait_for_connection(config.startupattempts, config.startupinterval) # make sure you're actually connected to reddit if not connection.connected("http://www.reddit.com"): print( "ERROR: You do not appear to be connected to Reddit. Exiting") sys.exit(1) links = reddit.get_links() titles = links[1] permalinks = links[2] valid = reddit.choose_valid(links[0]) valid_url = valid[0] title = titles[valid[1]] permalink = permalinks[valid[1]] download.download_image(valid_url, title) download.save_info(valid_url, title, permalink) wallpaper.set_wallpaper() external_script() except KeyboardInterrupt: sys.exit(1)
def download_image(url, title): uaurl = request.Request(url, headers={'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7'}) f = request.urlopen(uaurl) print("downloading " + url) try: img = Image.open(f) if config.resize: config.log("resizing the downloaded wallpaper") img = ImageOps.fit(img, (config.minwidth, config.minheight), Image.ANTIALIAS) if config.settitle: img = set_image_title(img, title) if config.opsys == "Windows": img.save(config.walldir + '\\wallpaper.bmp', "BMP") else: img.save(config.walldir + '/wallpaper.jpg', "JPEG") except IOError: print("Error saving image!") sys.exit(1)
def wait_for_connection(tries, interval): config.log('Waiting for a connection...') for i in range(tries): if config.opsys == "Linux": # Reloads /etc/resolv.conf # credit: http://stackoverflow.com/questions/21356781/urrlib2-urlopen-name-or-service-not-known-persists-when-starting-script-witho libc = ctypes.cdll.LoadLibrary('libc.so.6') res_init = libc.__res_init res_init() config.log('Attempt # ' + str(i + 1) + ' to connect...') if connected("http://www.reddit.com"): config.log('Connected to the internet, checking if you\'re being redirectied...') if check_not_redirected(): config.log('No redirection. Starting the main script...') return True config.log('Redirected. Trying again...') time.sleep(interval) return False
def wait_for_connection(tries, interval): config.log('Waiting for a connection...') for i in range(tries): if config.opsys == "Linux": # Reloads /etc/resolv.conf # credit: http://stackoverflow.com/questions/21356781/urrlib2-urlopen-name-or-service-not-known-persists-when-starting-script-witho libc = ctypes.cdll.LoadLibrary('libc.so.6') res_init = libc.__res_init res_init() config.log('Attempt # ' + str(i + 1) + ' to connect...') if connected("http://www.reddit.com"): config.log( 'Connected to the internet, checking if you\'re being redirectied...' ) if check_not_redirected(): config.log('No redirection. Starting the main script...') return True config.log('Redirected. Trying again...') time.sleep(interval) return False
def run(): try: config.init_config() # blacklist the current wallpaper if requested if config.blacklistcurrent: reddit.blacklist_current() # check if the program is run in a special case (save or startup) if config.save: wallpaper.save_wallpaper() sys.exit(0) if config.autostartup: if config.opsys == "Linux": dfile = resource_string(__name__, 'conf_files/linux-autostart.desktop') path = os.path.expanduser("~/.config") + "/autostart" if not os.path.exists(path): os.makedirs(path) config.log(path + " created") with open(path + "/wallpaper-reddit.desktop", "wb") as f: f.write(dfile) print("Autostart file created at " + path) sys.exit(0) else: print("Automatic startup creation only currently supported on Linux") sys.exit(1) if config.startup: connection.wait_for_connection(config.startupattempts, config.startupinterval) # make sure you're actually connected to reddit if not connection.connected("http://www.reddit.com"): print("ERROR: You do not appear to be connected to Reddit. Exiting") sys.exit(1) links = reddit.get_links() if (config.lottery == True): random.shuffle(links) valid = reddit.choose_valid(links) download.download_image(valid[0], valid[1]) download.save_info(valid) wallpaper.set_wallpaper() external_script() except KeyboardInterrupt: sys.exit(1)