clean up a bit
This commit is contained in:
77
app/daily-wallpaper.py
Normal file
77
app/daily-wallpaper.py
Normal file
@ -0,0 +1,77 @@
|
||||
import datetime
|
||||
import os
|
||||
import requests
|
||||
import importlib
|
||||
import logging
|
||||
import slugify
|
||||
import settings
|
||||
import time
|
||||
import croniter
|
||||
|
||||
def main():
|
||||
config = settings.load_settings()
|
||||
logging.basicConfig(level=config['general']['log_level'], format="%(asctime)s [%(levelname)s] %(message)s", force=True)
|
||||
logging.debug(f"Config: {config}")
|
||||
|
||||
chosen_providers = config['general']['provider']
|
||||
|
||||
# Daemon mode
|
||||
if config['daemon']['daemon']:
|
||||
while True:
|
||||
for provider in chosen_providers:
|
||||
download_with_provider(provider, config)
|
||||
if config['daemon']['cron'] != "":
|
||||
now = datetime.datetime.now()
|
||||
cron = croniter.croniter(config['daemon']['cron'], now)
|
||||
next_run = cron.get_next(datetime.datetime)
|
||||
logging.info(f"Next run: {next_run}")
|
||||
time.sleep((next_run - now).total_seconds())
|
||||
else:
|
||||
time.sleep(config['daemon']['interval'])
|
||||
# Download once
|
||||
else:
|
||||
for provider in chosen_providers:
|
||||
download_with_provider(provider, config)
|
||||
|
||||
def download_with_provider(provider_name, config):
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config['general']['user_agent']
|
||||
})
|
||||
|
||||
# Convenience variables, could be inlined
|
||||
provider_settings = config[provider_name] if provider_name in config else None
|
||||
download_location = os.path.abspath(os.path.expanduser(config['general']['location']))
|
||||
|
||||
# Load the provider module
|
||||
provider = importlib.import_module(f"providers.{provider_name}")
|
||||
|
||||
# Create an instance of the provider
|
||||
provider_obj = getattr(provider, provider_name.title())(provider_settings, session)
|
||||
# Get the image URL and title
|
||||
image_url, image_title = provider_obj.get_image_info()
|
||||
logging.debug(f"Image URL: {image_url}")
|
||||
|
||||
# Variables for the file path
|
||||
date = datetime.datetime.now().strftime("%Y-%m-%d")
|
||||
image_title = slugify.slugify(image_title)
|
||||
file_path = f"{download_location}/{provider_name.title()}/{date} [{image_title}].jpg"
|
||||
# Check if we should include the title in the filename
|
||||
if not config['general']['include_title']:
|
||||
file_path = f"{download_location}/{provider_name.title()}/{date}.jpg"
|
||||
# Create the download location if it doesn't exist
|
||||
if not os.path.exists(download_location):
|
||||
os.mkdir(download_location)
|
||||
if not os.path.exists(f"{download_location}/{provider_name.title()}"):
|
||||
os.mkdir(f"{download_location}/{provider_name.title()}")
|
||||
# Check if the file exists and if we should overwrite it
|
||||
if os.path.exists(file_path) and not config['general']['overwrite']:
|
||||
return
|
||||
|
||||
# Download the image
|
||||
image = session.get(image_url).content
|
||||
with open(file_path, "wb") as file:
|
||||
file.write(image)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
90
app/settings.py
Normal file
90
app/settings.py
Normal file
@ -0,0 +1,90 @@
|
||||
import os.path
|
||||
import tomlkit
|
||||
|
||||
local_path = os.path.abspath("config.toml")
|
||||
user_path = os.path.expanduser("~/.config/app/config.toml")
|
||||
|
||||
def default_settings():
|
||||
general = tomlkit.table()
|
||||
general.add("location", "~/Pictures/Wallpapers")
|
||||
general["location"].comment("Download location")
|
||||
general.add("provider", ["bing", "unsplash", "wikimedia"])
|
||||
general["provider"].comment("Which wallpaper provider to use, in order of preference (do no include if you don't want to download the file)")
|
||||
general.add("include_title", True)
|
||||
general.value.item("include_title").comment("Include image title in filename")
|
||||
general.add("set_wallpaper", False)
|
||||
general.value.item("set_wallpaper").comment("Set wallpaper after download")
|
||||
general.add("log", False)
|
||||
general.value.item("log").comment("Log to file, located in the download location")
|
||||
general.add("log_level", "INFO")
|
||||
general["log_level"].comment("Log level, possible values: DEBUG, INFO, WARNING, ERROR, CRITICAL")
|
||||
general.add("overwrite", False)
|
||||
general.value.item("overwrite").comment("Overwrite existing files")
|
||||
general.add("user_agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0")
|
||||
general["user_agent"].comment("User-Agent to use for requests, change to avoid being blocked or to comply with ToS")
|
||||
general.add(tomlkit.nl())
|
||||
|
||||
daemon = tomlkit.table()
|
||||
daemon.add("daemon", False)
|
||||
daemon.value.item("daemon").comment("Run as daemon (continuously in the background)")
|
||||
daemon.add("interval", 86400)
|
||||
daemon["interval"].comment("Interval in seconds (24 hours)")
|
||||
daemon.add("cron", "0 0 * * *")
|
||||
daemon["cron"].comment("Cron expression, overrides interval")
|
||||
daemon.add(tomlkit.nl())
|
||||
|
||||
bing = tomlkit.table()
|
||||
bing.add("size", "UHD")
|
||||
bing["size"].comment('Image size, possible values: "UHD", "1920x1080"')
|
||||
bing.add("country", "us")
|
||||
bing["country"].comment("Country, currently unused")
|
||||
bing.add("market", "en-US")
|
||||
bing["market"].comment("Market, overrides country")
|
||||
bing.add(tomlkit.nl())
|
||||
|
||||
unsplash = tomlkit.table()
|
||||
unsplash.add("collection", 1459961)
|
||||
unsplash["collection"].comment("Collection ID, which gallery to use")
|
||||
unsplash.add("application_id", "")
|
||||
unsplash["application_id"].comment("Unset, currently not used, as we scrape")
|
||||
unsplash.add("access_key", "")
|
||||
unsplash["access_key"].comment("Unset, currently not used, as we scrape")
|
||||
unsplash.add("secret_key", "")
|
||||
unsplash["secret_key"].comment("Unset, currently not used, as we scrape")
|
||||
unsplash.add(tomlkit.nl())
|
||||
|
||||
wikimedia = tomlkit.table()
|
||||
wikimedia.add("authorization", "")
|
||||
wikimedia["authorization"].comment("Unset, currently not used, as Wikimedia does not require it")
|
||||
|
||||
defaults = tomlkit.document()
|
||||
defaults.add("general", general)
|
||||
defaults.add("daemon", daemon)
|
||||
defaults.add("bing", bing)
|
||||
defaults.add("unsplash", unsplash)
|
||||
defaults.add("wikimedia", wikimedia)
|
||||
|
||||
return defaults
|
||||
|
||||
def load_settings():
|
||||
# TODO: Find a better way to do this
|
||||
if os.environ.get("RAPID_DEVELOPMENT") is not None:
|
||||
if os.path.exists(user_path):
|
||||
os.remove(user_path)
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
settings = default_settings()
|
||||
with open(local_path, mode='w') as file:
|
||||
tomlkit.dump(settings, file)
|
||||
return settings
|
||||
|
||||
if os.path.exists(local_path):
|
||||
settings = tomlkit.parse(open(local_path, mode='r').read())
|
||||
elif os.path.exists(user_path):
|
||||
settings = tomlkit.parse(open(user_path, mode='b+r').read())
|
||||
else:
|
||||
settings = default_settings()
|
||||
os.makedirs(os.path.dirname(user_path), exist_ok=True)
|
||||
with open(user_path, mode='w') as file:
|
||||
tomlkit.dump(settings, file)
|
||||
return settings
|
Reference in New Issue
Block a user