#!/usr/bin/env python3 """Uses unsplash API to set wallpapers from the cli.""" import requests import argparse from QuickWall.SetPaper import SetPaper from QuickWall.utility import (is_nitrogen, clear_cache) from QuickWall.logger import Logger from QuickWall.setter import WallSetter # Declare the logger logger = Logger("main") def parse(): """Parse the arguments.""" parser = argparse.ArgumentParser(description="QuickWall - Quickly set\ latest wallpapers from Unsplash\ directly from the commandline.") parser.add_argument('--version', action='version', version='0.0.1-3', help='show the program version number and exit') parser.add_argument('--clear-cache', help="Clear the cache from the\ cache folder (~/.QuickWall)", action='store_true') parser.add_argument('--setter', help="Wallpaper setter to be used.\ Currently supported ones: nitrogen, feh (default: nitrogen)",
"""Functions related to setting the wallpaper.""" from pathlib import Path from os import makedirs, remove from downloader_cli.download import Download from QuickWall.logger import Logger from QuickWall.blacklist import Blacklist from QuickWall.wal import Wal # Declare the logger logger = Logger("SetPaper") class SetPaper: """ Download the wallpaper and set it using nitrogen. """ def __init__(self, entity_list, setter, passed_dir="~/.cache/QuickWall", disable_blacklist=False, disable_theme=False): self.entity_list = entity_list self._dir_path = Path(passed_dir).expanduser() self._exists() makedirs(self._dir_path, exist_ok=True) self.setter_type = setter # Update by calling the following function self.disable_blacklist = disable_blacklist self._disable_theme = disable_theme
"""All utility related functions defined here""" import subprocess from pathlib import Path from shutil import rmtree from os import mkdir from QuickWall.logger import Logger # Declare logger logger = Logger("Utility") def is_nitrogen(): """ Check if nitrogen is present or not """ command = "nitrogen --help" p = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE) ret, err = p.communicate() return True if err is None else False def is_feh(): """ Check if feh is installed. """ command = "feh --help"
import requests from re import sub from QuickWall.logger import Logger logger = Logger('Wall') class Wall: """ Class to do tasks like downloading the wallpaper. URL list has 4 entries: desc: Description of the image name: Name of the user who uploaded the image dw_link: Download link of the image unique_id: ID to save the image """ def __init__(self, photo_id, random=None, search=None): self.s_term = None self._acces_key = sub( r'\n|"', '', requests.get("https://deepjyoti30server.herokuapp.com/key").text) self._URL = "https://api.unsplash.com/photos/" self._URL_list = [] self.random = random self.search = search self.id = photo_id self._build_URL()
import subprocess from pathlib import Path from QuickWall.logger import Logger logger = Logger("GNOME") class GNOMESetter: def __init__(self): self.cmd = "gsettings set org.gnome.desktop.background picture-uri file://{wallpaper}" self._extract_prev_wall() def _extract_prev_wall(self): """Extract the saved wallpaper from the cmd line.""" self.SAVED_WALL = subprocess.check_output(["gsettings", "get", "org.gnome.desktop.background", "picture-uri"])[1:-2].decode('utf-8') def set(self, wallpaper): """Set the wallpaper temporarily.""" subprocess.call(self.cmd.format(wallpaper=wallpaper).split(" ")) def set_perm(self, wallpaper): """Set the wallpaper permanently.""" self.set(wallpaper) def restore(self): """Restore the saved wallpaper.""" self.set_perm(self.SAVED_WALL)
"""All blacklist related functions.""" from pathlib import Path from QuickWall.logger import Logger # Declare logger logger = Logger("blacklist") class Blacklist: """ Functions to be used related to blacklist. """ def __init__(self, unique_id): self.blacklist_path = Path('~/.cache/QuickWall/blacklist').expanduser() self.unique_id = unique_id def is_blacklisted(self): """ Check if the passed unique_id is available in the blacklist. """ if not self.blacklist_path.exists(): return False blacklist = open(self.blacklist_path).read().split('\n')[1:] logger.debug(str(blacklist)) if self.unique_id in blacklist:
"""Set the theme extracted from the wallpaper.""" from pywal import (colors, export, sequences, theme, settings) import os from QuickWall.logger import Logger logger = Logger("wal") class Wal: """Change the theme based on the passed wallpaper""" def set(self, wallpaper): logger.debug("{}".format(wallpaper)) self.colors_plain = colors.get(wallpaper) sequences.send(self.colors_plain, to_send=True) colors.palette() def save(self): export.every(self.colors_plain) def restore(self): self.colors_plain = theme.file( os.path.join(settings.CACHE_DIR, "colors.json")) sequences.send(self.colors_plain, to_send=True)
"""Functions related to usign feh as wallpaper setter.""" import subprocess from pathlib import Path from QuickWall.logger import Logger # Declare the logger logger = Logger("feh") class feh: def __init__(self): self.feh_config_path = Path('~/.fehbg').expanduser() self.current = self._find_current() def _find_current(self): """ Extract the current wall path. """ return open(self.feh_config_path).read().split(' ')[4] def restore(self): """ Restore the wallpaper """ command = "feh --bg-fill {}".format(self.current) subprocess.Popen(command.split(), stdout=subprocess.PIPE) def set(self, file_path): """
"""Set wallpapers in KDE.""" import dbus from os import path, system from shutil import copy from QuickWall.logger import Logger logger = Logger("KDE") def setwallpaper(filepath): """ This script is taken from https://github.com/pashazz/ksetwallpaper/ All the credit goes to the user for the code, I'm just using it to add a functionality to my app. """ jscript = """var allDesktops = desktops(); for ( i = 0; i < allDesktops.length;i++ ) { d = allDesktops[i]; d.wallpaperPlugin = "org.kde.image"; d.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General"); d.writeConfig("Image", "file://%s") } """ bus = dbus.SessionBus() plasma = dbus.Interface(bus.get_object('org.kde.plasmashell', '/PlasmaShell'), dbus_interface='org.kde.PlasmaShell') plasma.evaluateScript(jscript % filepath)
"""Setter related functions.""" from QuickWall.nitrogen import nitrogen from QuickWall.feh import feh from QuickWall.kde import KDEsetpaper from QuickWall.xfce import XFCESetter from QuickWall.gnome import GNOMESetter from QuickWall.logger import Logger from QuickWall.utility import get_desktop_environment # Declare the logger logger = Logger("Setter") LockscreenCompatibleSetters = ["kde"] class WallSetter: """ Select the wallpaper setter. """ def __init__(self, setter_type, lockscreen=False): self.setter_type = setter_type self.available_setters = { 'nitrogen': nitrogen, 'feh': feh, 'kde': KDEsetpaper, 'xfce': XFCESetter, 'gnome': GNOMESetter, } self.setter = None self._select_setter()
"""Functions related to nitrogen.""" import subprocess from QuickWall.logger import Logger # Declare logger logger = Logger("nitrogen") class nitrogen: """ Class to use nitrogen to set wallpapers. """ def restore(self): """ Restore the wallpaper using nitrogen. """ logger.info("Restoring the last wallpaper...") c = 'nitrogen --restore' subprocess.Popen(c.split(), stdout=subprocess.PIPE) def set(self, file_path): """ Set the wallpaper temporaririly """ c = 'nitrogen --set-zoom-fill {}'.format(file_path) p = subprocess.Popen(c.split(' '), stdout=subprocess.PIPE) ret, err = p.communicate() def set_perm(self, file_path):
#!/usr/bin/env python3 """Uses unsplash API to set wallpapers from the cli.""" import requests import argparse from QuickWall.SetPaper import SetPaper from QuickWall.utility import (is_nitrogen, clear_cache, migrate_to_new_loc) from QuickWall.logger import Logger from QuickWall.setter import WallSetter from QuickWall.wall import Wall from QuickWall.blacklist import Blacklist # Declare the logger logger = Logger("main") def parse(): """Parse the arguments.""" parser = argparse.ArgumentParser(description="QuickWall - Quickly set\ latest wallpapers from Unsplash\ directly from the commandline.", epilog="If you find any bugs, feel\ free to raise an issue in the GitHub\ [https://github.com/deepjyoti30/QuickWall] page." ) parser.add_argument('--version', action='version', version='0.0.1-4', help='show the program version number and exit')
"""All code related to setting wallpaper in xfce is defined here.""" import os from pathlib import Path from bs4 import BeautifulSoup from QuickWall.logger import Logger logger = Logger("XFCE") class XFCESetter: def __init__(self): self.cmd = "xfconf-query -c xfce4-desktop -p {wallpaper_image} -s {wallpaper}" # Save the value of the previous wallpaper. self._extract_prev_wall() def _extract_prev_wall(self): """Extract the saved wallpaper from the xml file.""" FILE = Path("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml").expanduser() try: soup = BeautifulSoup(open(FILE, 'r'), features="html.parser") wall = soup.find("property", attrs={"name": "last-image"}) except FileNotFoundError: logger.warning("{}: Not found. Wallpaper will not be restored!".format(FILE)) return except Exception as e: logger.error("While extracting the wallpaper, error thrown: {}".format(e)) return if wall == "": logger.warning("No value of last image. Wallpaper will not be restored!")