From fad04f1a1691e54a13408e861e708f14558ccb9f Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 14:22:01 +0530 Subject: [PATCH 1/6] added constants file and refactored set wallpaper --- Constants.py | 2 ++ freshpaper.py | 74 +++++++++++++++++++++++++++++---------------------- 2 files changed, 44 insertions(+), 32 deletions(-) create mode 100644 Constants.py diff --git a/Constants.py b/Constants.py new file mode 100644 index 0000000..7a6d844 --- /dev/null +++ b/Constants.py @@ -0,0 +1,2 @@ +NASA_IMAGE_URL = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY" +BING_IMAGE_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=EN-IN" diff --git a/freshpaper.py b/freshpaper.py index e7bae65..ae9a2fd 100644 --- a/freshpaper.py +++ b/freshpaper.py @@ -9,6 +9,8 @@ from subprocess import check_call, CalledProcessError from PIL import Image +from Constants import NASA_IMAGE_URL, BING_IMAGE_URL + try: # for python3 from urllib.request import urlopen, urlretrieve, HTTPError, URLError @@ -40,24 +42,28 @@ def set_wallpaper(image_path): ) ) - if sys.platform.startswith("win32"): + setWallpaperForWindows(image_path) + setWallpaperForMacOS(image_path) + setWallpaperForLinux(image_path) - bmp_image = Image.open(image_path) - bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" - bmp_image.save(bmp_img_path, "BMP") - key = win32api.RegOpenKeyEx( - win32con.HKEY_CURRENT_USER, - "Control Panel\\Desktop", - 0, - win32con.KEY_SET_VALUE, - ) - win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") - win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") - win32gui.SystemParametersInfo( - win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 + log.info("Wallpaper successfully updated. :)") + + +def setWallpaperForLinux(image_path): + if sys.platform.startswith("linux"): + check_call( + [ + "gsettings", + "set", + "org.gnome.desktop.background", + "picture-uri", + "file://{}".format(image_path), + ] ) - os.remove(bmp_img_path) - elif sys.platform.startswith("darwin"): + + +def setWallpaperForMacOS(image_path): + if sys.platform.startswith("darwin"): try: command = """ osascript -e 'tell application "System Events" @@ -76,18 +82,25 @@ def set_wallpaper(image_path): except CalledProcessError or FileNotFoundError: log.error("Setting wallpaper failed.") sys.exit(1) - elif sys.platform.startswith("linux"): - check_call( - [ - "gsettings", - "set", - "org.gnome.desktop.background", - "picture-uri", - "file://{}".format(image_path), - ] - ) - log.info("Wallpaper successfully updated. :)") + +def setWallpaperForWindows(image_path): + if sys.platform.startswith("win32"): + bmp_image = Image.open(image_path) + bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" + bmp_image.save(bmp_img_path, "BMP") + key = win32api.RegOpenKeyEx( + win32con.HKEY_CURRENT_USER, + "Control Panel\\Desktop", + 0, + win32con.KEY_SET_VALUE, + ) + win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") + win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") + win32gui.SystemParametersInfo( + win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 + ) + os.remove(bmp_img_path) def get_saved_wallpaper(wall_dir): @@ -136,10 +149,9 @@ def download_image_bing(download_dir, image_extension="jpg"): """ # mkt(s) HIN, EN-IN - url = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=EN-IN" try: - image_data = json.loads(urlopen(url).read().decode("utf-8")) + image_data = json.loads(urlopen(BING_IMAGE_URL).read().decode("utf-8")) image_url = "http://www.bing.com" + image_data["images"][0]["url"] @@ -180,10 +192,8 @@ def download_image_nasa(download_dir, image_extension="jpg"): :return: downloaded image path """ - url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY" - try: - image_data = json.loads(urlopen(url).read().decode("utf-8")) + image_data = json.loads(urlopen(NASA_IMAGE_URL).read().decode("utf-8")) image_url = image_data.get("url") From 6d0e6da7d7030eaf4989638335930e333698bcc0 Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 14:42:31 +0530 Subject: [PATCH 2/6] refactoring and added wallpaper utils --- src/__init__.py | 0 Constants.py => src/constants.py | 2 + freshpaper.py => src/freshpaper.py | 100 ++++------------------------- src/wallpaperUtils.py | 99 ++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 86 deletions(-) create mode 100644 src/__init__.py rename Constants.py => src/constants.py (62%) rename freshpaper.py => src/freshpaper.py (65%) create mode 100644 src/wallpaperUtils.py diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Constants.py b/src/constants.py similarity index 62% rename from Constants.py rename to src/constants.py index 7a6d844..64fa359 100644 --- a/Constants.py +++ b/src/constants.py @@ -1,2 +1,4 @@ NASA_IMAGE_URL = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY" BING_IMAGE_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=EN-IN" +BING_IMAGE_DESCRIPTION = "Bing photo of the day" +NASA_IMAGE_DESCRIPTION = "Bing photo of the day" diff --git a/freshpaper.py b/src/freshpaper.py similarity index 65% rename from freshpaper.py rename to src/freshpaper.py index ae9a2fd..a5073d9 100644 --- a/freshpaper.py +++ b/src/freshpaper.py @@ -8,8 +8,10 @@ from datetime import datetime from subprocess import check_call, CalledProcessError from PIL import Image +from pip._vendor.requests import ConnectionError -from Constants import NASA_IMAGE_URL, BING_IMAGE_URL +from constants import NASA_IMAGE_URL, BING_IMAGE_URL, BING_IMAGE_DESCRIPTION, NASA_IMAGE_DESCRIPTION +from src.wallpaperUtils import wallpaperUtils try: # for python3 @@ -28,81 +30,6 @@ log = logging.getLogger(__name__) - -def set_wallpaper(image_path): - """ Given a path to an image, set it as the wallpaper """ - if not os.path.exists(image_path): - log.error("Image does not exist.") - sys.exit(1) - - log.info("Updating wallpaper..") - log.info( - "Name of wallpaper: {}".format( - re.sub("([a-z])([A-Z])", r"\1 \2", image_path.split("/")[-1].split("_")[0]) - ) - ) - - setWallpaperForWindows(image_path) - setWallpaperForMacOS(image_path) - setWallpaperForLinux(image_path) - - log.info("Wallpaper successfully updated. :)") - - -def setWallpaperForLinux(image_path): - if sys.platform.startswith("linux"): - check_call( - [ - "gsettings", - "set", - "org.gnome.desktop.background", - "picture-uri", - "file://{}".format(image_path), - ] - ) - - -def setWallpaperForMacOS(image_path): - if sys.platform.startswith("darwin"): - try: - command = """ - osascript -e 'tell application "System Events" - set desktopCount to count of desktops - repeat with desktopNumber from 1 to desktopCount - tell desktop desktopNumber - set picture to "{image_path}" - end tell - end repeat - end tell' - """.format( - image_path=image_path - ) - - check_call([command], shell=True) - except CalledProcessError or FileNotFoundError: - log.error("Setting wallpaper failed.") - sys.exit(1) - - -def setWallpaperForWindows(image_path): - if sys.platform.startswith("win32"): - bmp_image = Image.open(image_path) - bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" - bmp_image.save(bmp_img_path, "BMP") - key = win32api.RegOpenKeyEx( - win32con.HKEY_CURRENT_USER, - "Control Panel\\Desktop", - 0, - win32con.KEY_SET_VALUE, - ) - win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") - win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") - win32gui.SystemParametersInfo( - win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 - ) - os.remove(bmp_img_path) - - def get_saved_wallpaper(wall_dir): """ returns random saved wallpaper's path """ @@ -227,8 +154,8 @@ def download_image_nasa(download_dir, image_extension="jpg"): freshpaperSources = { - "bing": {"download": download_image_bing, "description": "Bing photo of the day"}, - "nasa": {"download": download_image_nasa, "description": "NASA photo of the day"}, + "bing": {"download": download_image_bing, "description": BING_IMAGE_DESCRIPTION}, + "nasa": {"download": download_image_nasa, "description": NASA_IMAGE_DESCRIPTION}, } @@ -240,17 +167,18 @@ def download_image_nasa(download_dir, image_extension="jpg"): type=click.Choice(freshpaperSources.keys()), help="Source for setting the wallpaper.", ) -def main(ctx, source): - if ctx.invoked_subcommand is None: - dir_name = get_wallpaper_directory() # Wallpaper directory name - +def main(context, source): + if context.invoked_subcommand is None: + directory_name = get_wallpaper_directory() # Wallpaper directory name + wallpaper = wallpaperUtils() try: download_image = freshpaperSources.get(source)["download"] - image_path = download_image(dir_name) - set_wallpaper(image_path) + image_path = download_image(directory_name) + + wallpaper.set_wallpaper(image_path) except ConnectionError: - image_path = get_saved_wallpaper(dir_name) - set_wallpaper(image_path) + image_path = get_saved_wallpaper(directory_name) + wallpaper.set_wallpaper(image_path) except Exception as e: log.error(e) diff --git a/src/wallpaperUtils.py b/src/wallpaperUtils.py new file mode 100644 index 0000000..907293d --- /dev/null +++ b/src/wallpaperUtils.py @@ -0,0 +1,99 @@ +import os +import re +import sys +from subprocess import check_call, CalledProcessError +import logging + +from PIL import Image + +try: + # for python3 + from urllib.request import urlopen, urlretrieve, HTTPError, URLError +except ImportError: + # for python2 + from urllib import urlretrieve + from urllib2 import urlopen, HTTPError, URLError + +if sys.platform.startswith("win32"): + import win32api + import win32con + import win32gui + +logging.basicConfig(level=logging.INFO, format="%(message)s") + +log = logging.getLogger(__name__) + + +class wallpaperUtils: + def __init__(self): + pass + + def set_wallpaper(self, image_path): + """ Given a path to an image, set it as the wallpaper """ + if not os.path.exists(image_path): + log.error("Image does not exist.") + sys.exit(1) + + log.info("Updating wallpaper..") + log.info( + "Name of wallpaper: {}".format( + re.sub("([a-z])([A-Z])", r"\1 \2", image_path.split("/")[-1].split("_")[0]) + ) + ) + + self.setWallpaperForWindows(image_path) + self.setWallpaperForMacOS(image_path) + self.setWallpaperForLinux(image_path) + + log.info("Wallpaper successfully updated. :)") + + def setWallpaperForLinux(self, image_path): + if sys.platform.startswith("linux"): + check_call( + [ + "gsettings", + "set", + "org.gnome.desktop.background", + "picture-uri", + "file://{}".format(image_path), + ] + ) + + def setWallpaperForMacOS(self, image_path): + if sys.platform.startswith("darwin"): + try: + command = """ + osascript -e 'tell application "System Events" + set desktopCount to count of desktops + repeat with desktopNumber from 1 to desktopCount + tell desktop desktopNumber + set picture to "{image_path}" + end tell + end repeat + end tell' + """.format( + image_path=image_path + ) + + check_call([command], shell=True) + except CalledProcessError or FileNotFoundError: + log.error("Setting wallpaper failed.") + sys.exit(1) + + def setWallpaperForWindows(self, image_path): + if sys.platform.startswith("win32"): + bmp_image = Image.open(image_path) + bmp_img_path = os.path.splitext(image_path)[0] + ".bmp" + bmp_image.save(bmp_img_path, "BMP") + key = win32api.RegOpenKeyEx( + win32con.HKEY_CURRENT_USER, + "Control Panel\\Desktop", + 0, + win32con.KEY_SET_VALUE, + ) + win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0") + win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, "0") + win32gui.SystemParametersInfo( + win32con.SPI_SETDESKWALLPAPER, bmp_img_path, 1 + 2 + ) + os.remove(bmp_img_path) From 7257cdd536a25621c7387c573cbb469c1e677603 Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 15:08:55 +0530 Subject: [PATCH 3/6] refactoring download utils --- src/{constants.py => Constants.py} | 1 + src/DownloadUtils.py | 112 +++++++++++++++++ src/{wallpaperUtils.py => WallpaperUtils.py} | 2 +- src/freshpaper.py | 126 +++---------------- 4 files changed, 134 insertions(+), 107 deletions(-) rename src/{constants.py => Constants.py} (88%) create mode 100644 src/DownloadUtils.py rename src/{wallpaperUtils.py => WallpaperUtils.py} (99%) diff --git a/src/constants.py b/src/Constants.py similarity index 88% rename from src/constants.py rename to src/Constants.py index 64fa359..5594617 100644 --- a/src/constants.py +++ b/src/Constants.py @@ -2,3 +2,4 @@ BING_IMAGE_URL = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=EN-IN" BING_IMAGE_DESCRIPTION = "Bing photo of the day" NASA_IMAGE_DESCRIPTION = "Bing photo of the day" +IMAGE_SOURCES = ['bing', 'nasa'] diff --git a/src/DownloadUtils.py b/src/DownloadUtils.py new file mode 100644 index 0000000..65b3fdf --- /dev/null +++ b/src/DownloadUtils.py @@ -0,0 +1,112 @@ +import json +import logging +import os +import re +from datetime import datetime + +from pip._vendor.requests import ConnectionError + +from Constants import NASA_IMAGE_URL, BING_IMAGE_URL + +try: + # for python3 + from urllib.request import urlopen, urlretrieve, HTTPError, URLError +except ImportError: + # for python2 + from urllib import urlretrieve + from urllib2 import urlopen, HTTPError, URLError + + +logging.basicConfig(level=logging.INFO, format="%(message)s") + +log = logging.getLogger(__name__) + +class DownloadUtils: + + def __init__(self): + pass + + def download_image_bing(self, download_dir, image_extension="jpg"): + """ + Download & save the image + :param download_dir: directory where to download the image + :param image_extension: directory where to download the image + :return: downloaded image path + """ + # mkt(s) HIN, EN-IN + + + try: + image_data = json.loads(urlopen(BING_IMAGE_URL).read().decode("utf-8")) + + image_url = "http://www.bing.com" + image_data["images"][0]["url"] + + image_name = re.search(r"OHR\.(.*?)_", image_url).group(1) + + image_url_hd = "http://www.bing.com/hpwp/" + image_data["images"][0]["hsh"] + date_time = datetime.now().strftime("%d_%m_%Y") + image_file_name = "{image_name}_{date_stamp}.{extention}".format( + image_name=image_name, date_stamp=date_time, extention=image_extension + ) + + image_path = os.path.join(os.sep, download_dir, image_file_name) + log.debug("download_dir: {}".format(download_dir)) + log.debug("image_file_name: {}".format(image_file_name)) + log.debug("image_path: {}".format(image_path)) + + if os.path.isfile(image_path): + log.info("No new wallpaper yet..updating to latest one.\n") + return image_path + + try: + log.info("Downloading..") + urlretrieve(image_url_hd, filename=image_path) + except HTTPError: + log.info("Downloading...") + urlretrieve(image_url, filename=image_path) + return image_path + except URLError: + log.error("Something went wrong..\nMaybe Internet is not working...") + raise ConnectionError + + + def download_image_nasa(self, download_dir, image_extension="jpg"): + """ + Download & save the image + :param download_dir: directory where to download the image + :param image_extension: directory where to download the image + :return: downloaded image path + """ + + try: + image_data = json.loads(urlopen(NASA_IMAGE_URL).read().decode("utf-8")) + + image_url = image_data.get("url") + + image_name = image_data.get("title").split(" ")[0] + + image_url_hd = image_data.get("hdurl") + date_time = datetime.now().strftime("%d_%m_%Y") + image_file_name = "{image_name}_{date_stamp}.{extention}".format( + image_name=image_name, date_stamp=date_time, extention=image_extension + ) + + image_path = os.path.join(os.sep, download_dir, image_file_name) + log.debug("download_dir: {}".format(download_dir)) + log.debug("image_file_name: {}".format(image_file_name)) + log.debug("image_path: {}".format(image_path)) + + if os.path.isfile(image_path): + log.info("No new wallpaper yet..updating to latest one.\n") + return image_path + + try: + log.info("Downloading..") + urlretrieve(image_url_hd, filename=image_path) + except HTTPError: + log.info("Downloading...") + urlretrieve(image_url, filename=image_path) + return image_path + except URLError: + log.error("Something went wrong..\nMaybe Internet is not working...") + raise ConnectionError \ No newline at end of file diff --git a/src/wallpaperUtils.py b/src/WallpaperUtils.py similarity index 99% rename from src/wallpaperUtils.py rename to src/WallpaperUtils.py index 907293d..264f70f 100644 --- a/src/wallpaperUtils.py +++ b/src/WallpaperUtils.py @@ -24,7 +24,7 @@ log = logging.getLogger(__name__) -class wallpaperUtils: +class WallpaperUtils: def __init__(self): pass diff --git a/src/freshpaper.py b/src/freshpaper.py index a5073d9..8e8c4f4 100644 --- a/src/freshpaper.py +++ b/src/freshpaper.py @@ -1,17 +1,14 @@ +import logging import os -import re import sys -import click -import json -import logging from random import choice -from datetime import datetime -from subprocess import check_call, CalledProcessError -from PIL import Image + +import click from pip._vendor.requests import ConnectionError -from constants import NASA_IMAGE_URL, BING_IMAGE_URL, BING_IMAGE_DESCRIPTION, NASA_IMAGE_DESCRIPTION -from src.wallpaperUtils import wallpaperUtils +from Constants import BING_IMAGE_DESCRIPTION, NASA_IMAGE_DESCRIPTION, IMAGE_SOURCES +from src.DownloadUtils import DownloadUtils +from src.WallpaperUtils import WallpaperUtils try: # for python3 @@ -22,14 +19,13 @@ from urllib2 import urlopen, HTTPError, URLError if sys.platform.startswith("win32"): - import win32api - import win32con - import win32gui + pass logging.basicConfig(level=logging.INFO, format="%(message)s") log = logging.getLogger(__name__) + def get_saved_wallpaper(wall_dir): """ returns random saved wallpaper's path """ @@ -67,110 +63,21 @@ def get_wallpaper_directory(): return wall_dir -def download_image_bing(download_dir, image_extension="jpg"): - """ - Download & save the image - :param download_dir: directory where to download the image - :param image_extension: directory where to download the image - :return: downloaded image path - """ - # mkt(s) HIN, EN-IN - - - try: - image_data = json.loads(urlopen(BING_IMAGE_URL).read().decode("utf-8")) - - image_url = "http://www.bing.com" + image_data["images"][0]["url"] - - image_name = re.search(r"OHR\.(.*?)_", image_url).group(1) - - image_url_hd = "http://www.bing.com/hpwp/" + image_data["images"][0]["hsh"] - date_time = datetime.now().strftime("%d_%m_%Y") - image_file_name = "{image_name}_{date_stamp}.{extention}".format( - image_name=image_name, date_stamp=date_time, extention=image_extension - ) - - image_path = os.path.join(os.sep, download_dir, image_file_name) - log.debug("download_dir: {}".format(download_dir)) - log.debug("image_file_name: {}".format(image_file_name)) - log.debug("image_path: {}".format(image_path)) - - if os.path.isfile(image_path): - log.info("No new wallpaper yet..updating to latest one.\n") - return image_path - - try: - log.info("Downloading..") - urlretrieve(image_url_hd, filename=image_path) - except HTTPError: - log.info("Downloading...") - urlretrieve(image_url, filename=image_path) - return image_path - except URLError: - log.error("Something went wrong..\nMaybe Internet is not working...") - raise ConnectionError - - -def download_image_nasa(download_dir, image_extension="jpg"): - """ - Download & save the image - :param download_dir: directory where to download the image - :param image_extension: directory where to download the image - :return: downloaded image path - """ - - try: - image_data = json.loads(urlopen(NASA_IMAGE_URL).read().decode("utf-8")) - - image_url = image_data.get("url") - - image_name = image_data.get("title").split(" ")[0] - - image_url_hd = image_data.get("hdurl") - date_time = datetime.now().strftime("%d_%m_%Y") - image_file_name = "{image_name}_{date_stamp}.{extention}".format( - image_name=image_name, date_stamp=date_time, extention=image_extension - ) - - image_path = os.path.join(os.sep, download_dir, image_file_name) - log.debug("download_dir: {}".format(download_dir)) - log.debug("image_file_name: {}".format(image_file_name)) - log.debug("image_path: {}".format(image_path)) - - if os.path.isfile(image_path): - log.info("No new wallpaper yet..updating to latest one.\n") - return image_path - - try: - log.info("Downloading..") - urlretrieve(image_url_hd, filename=image_path) - except HTTPError: - log.info("Downloading...") - urlretrieve(image_url, filename=image_path) - return image_path - except URLError: - log.error("Something went wrong..\nMaybe Internet is not working...") - raise ConnectionError - - -freshpaperSources = { - "bing": {"download": download_image_bing, "description": BING_IMAGE_DESCRIPTION}, - "nasa": {"download": download_image_nasa, "description": NASA_IMAGE_DESCRIPTION}, -} - - @click.group(invoke_without_command=True) @click.pass_context @click.option( "--source", default="bing", - type=click.Choice(freshpaperSources.keys()), + type=click.Choice(IMAGE_SOURCES), help="Source for setting the wallpaper.", ) def main(context, source): if context.invoked_subcommand is None: directory_name = get_wallpaper_directory() # Wallpaper directory name - wallpaper = wallpaperUtils() + wallpaper = WallpaperUtils() + downloadUtils = DownloadUtils() + freshpaperSources = construct_freshpaper_sources(downloadUtils.download_image_bing, + downloadUtils.download_image_nasa) try: download_image = freshpaperSources.get(source)["download"] image_path = download_image(directory_name) @@ -183,5 +90,12 @@ def main(context, source): log.error(e) +def construct_freshpaper_sources(source1, source2): + return { + "bing": {"download": source1, "description": BING_IMAGE_DESCRIPTION}, + "nasa": {"download": source2, "description": NASA_IMAGE_DESCRIPTION}, + } + + if __name__ == "__main__": main() From 0ba639579f598d201c45238cf8951f9b695b72da Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 15:13:05 +0530 Subject: [PATCH 4/6] added system utils --- src/SystemUtils.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++ src/freshpaper.py | 49 +++++-------------------------------- 2 files changed, 66 insertions(+), 43 deletions(-) create mode 100644 src/SystemUtils.py diff --git a/src/SystemUtils.py b/src/SystemUtils.py new file mode 100644 index 0000000..4334720 --- /dev/null +++ b/src/SystemUtils.py @@ -0,0 +1,60 @@ +import logging +import os +import sys +from random import choice + +try: + # for python3 + from urllib.request import urlopen, urlretrieve, HTTPError, URLError +except ImportError: + # for python2 + + from urllib import urlretrieve + from urllib2 import urlopen, HTTPError, URLError + +if sys.platform.startswith("win32"): + pass + +logging.basicConfig(level=logging.INFO, format="%(message)s") + +log = logging.getLogger(__name__) + + +class SystemUtils: + def __init__(self): + pass + + def get_saved_wallpaper(self, wall_dir): + """ returns random saved wallpaper's path """ + + files = os.listdir(wall_dir) + if files: + log.info("\nRandomly picking from saved wallpapers.") + image_name = choice(files) + image_path = os.path.join(os.sep, wall_dir, image_name) + return image_path + else: + log.error("There is no wallpaper available offline.") + sys.exit(1) + + def get_wallpaper_directory(self): + """ check if `default` wallpaper download directory exists or not, create if doesn't exist """ + pictures_dir = "" + wall_dir_name = "freshpaper" + os.path.join(os.sep, os.path.expanduser("~"), "a", "freshpaper") + if sys.platform.startswith("win32"): + pictures_dir = "My Pictures" + elif sys.platform.startswith("darwin"): + pictures_dir = "Pictures" + elif sys.platform.startswith("linux"): + pictures_dir = "Pictures" + wall_dir = os.path.join( + os.sep, os.path.expanduser("~"), pictures_dir, wall_dir_name + ) + + if not os.path.isdir(wall_dir): + log.error("wallpaper directory does not exist.") + os.makedirs(wall_dir) + log.info("created wallpaper directory at: {}".format(wall_dir)) + + return wall_dir diff --git a/src/freshpaper.py b/src/freshpaper.py index 8e8c4f4..34b556d 100644 --- a/src/freshpaper.py +++ b/src/freshpaper.py @@ -1,13 +1,12 @@ import logging -import os import sys -from random import choice import click from pip._vendor.requests import ConnectionError from Constants import BING_IMAGE_DESCRIPTION, NASA_IMAGE_DESCRIPTION, IMAGE_SOURCES from src.DownloadUtils import DownloadUtils +from src.SystemUtils import SystemUtils from src.WallpaperUtils import WallpaperUtils try: @@ -26,65 +25,29 @@ log = logging.getLogger(__name__) -def get_saved_wallpaper(wall_dir): - """ returns random saved wallpaper's path """ - - files = os.listdir(wall_dir) - if files: - log.info("\nRandomly picking from saved wallpapers.") - image_name = choice(files) - image_path = os.path.join(os.sep, wall_dir, image_name) - return image_path - else: - log.error("There is no wallpaper available offline.") - sys.exit(1) - - -def get_wallpaper_directory(): - """ check if `default` wallpaper download directory exists or not, create if doesn't exist """ - pictures_dir = "" - wall_dir_name = "freshpaper" - os.path.join(os.sep, os.path.expanduser("~"), "a", "freshpaper") - if sys.platform.startswith("win32"): - pictures_dir = "My Pictures" - elif sys.platform.startswith("darwin"): - pictures_dir = "Pictures" - elif sys.platform.startswith("linux"): - pictures_dir = "Pictures" - wall_dir = os.path.join( - os.sep, os.path.expanduser("~"), pictures_dir, wall_dir_name - ) - - if not os.path.isdir(wall_dir): - log.error("wallpaper directory does not exist.") - os.makedirs(wall_dir) - log.info("created wallpaper directory at: {}".format(wall_dir)) - - return wall_dir - - @click.group(invoke_without_command=True) @click.pass_context @click.option( "--source", - default="bing", + default="nasa", type=click.Choice(IMAGE_SOURCES), help="Source for setting the wallpaper.", ) def main(context, source): if context.invoked_subcommand is None: - directory_name = get_wallpaper_directory() # Wallpaper directory name wallpaper = WallpaperUtils() downloadUtils = DownloadUtils() + systemUtils = SystemUtils() + directory_name = systemUtils.get_wallpaper_directory() # Wallpaper directory name freshpaperSources = construct_freshpaper_sources(downloadUtils.download_image_bing, - downloadUtils.download_image_nasa) + downloadUtils.download_image_nasa) try: download_image = freshpaperSources.get(source)["download"] image_path = download_image(directory_name) wallpaper.set_wallpaper(image_path) except ConnectionError: - image_path = get_saved_wallpaper(directory_name) + image_path = systemUtils.get_saved_wallpaper(directory_name) wallpaper.set_wallpaper(image_path) except Exception as e: log.error(e) From 1d147fbe699922499b7feea9825f8cde0b50eedf Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 15:19:24 +0530 Subject: [PATCH 5/6] removed import --- src/freshpaper.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/freshpaper.py b/src/freshpaper.py index 34b556d..625a669 100644 --- a/src/freshpaper.py +++ b/src/freshpaper.py @@ -2,7 +2,6 @@ import sys import click -from pip._vendor.requests import ConnectionError from Constants import BING_IMAGE_DESCRIPTION, NASA_IMAGE_DESCRIPTION, IMAGE_SOURCES from src.DownloadUtils import DownloadUtils From cd5e1c89405c832baeebb1692887525023d9e114 Mon Sep 17 00:00:00 2001 From: pratiksaxena Date: Sat, 19 Oct 2019 15:21:02 +0530 Subject: [PATCH 6/6] refactoring --- src/{freshpaper.py => Freshpaper.py} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/{freshpaper.py => Freshpaper.py} (98%) diff --git a/src/freshpaper.py b/src/Freshpaper.py similarity index 98% rename from src/freshpaper.py rename to src/Freshpaper.py index 625a669..d4f7441 100644 --- a/src/freshpaper.py +++ b/src/Freshpaper.py @@ -28,7 +28,7 @@ @click.pass_context @click.option( "--source", - default="nasa", + default="bing", type=click.Choice(IMAGE_SOURCES), help="Source for setting the wallpaper.", )