You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

134 lines
4.3 KiB

#!/usr/bin/python3
import sys, argparse, pathlib, os, requests, subprocess, re, shutil
if sys.platform == "win32":
import ctypes
class Service:
def __init__(self, name, base_url, random = False, limit = 1):
self.name = name
self.base_url = base_url
self.url = self.base_url
self.limit = limit
self.tags = []
if random == False:
self.tags.append("order:random")
if self.limit > 0:
self.url += f"?limit={str(self.limit)}"
class URLGenerator:
def __init__(self, service):
self.url = service.base_url + "?tags="
self.args = ["order:random"]
def set_tag(self, tag):
self.args.append(tag)
def set_width(self, value):
self.args.append(f"width:{value}")
def set_height(self, value):
self.args.append(f"height:{value}")
def set_rating(self, value):
self.args.append(f"rating:{value}")
def generate_url(self):
return self.url + "+".join(self.args)
services = [
Service(name="konachan", base_url="https://konachan.com/post.json", random=False, limit=1),
Service(name="yande.re", base_url="https://yande.re/post.json", random=False, limit=1)
#Service(name="e926", base_url="https://e926.net/posts/random.json", random=True, limit=1),
#Service(name="e621", base_url="https://e621.net/posts/random.json", random=True, limit=1)
]
download_dir = os.path.join(pathlib.Path.home(), "Downloads", "Wallpaper-Roulette")
service = services[0]
if not os.path.exists(download_dir):
os.mkdir(download_dir)
def show_version():
git_revision = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).decode('ascii').strip()
message = f"Wallpaper Roulette v1.0.0-{git_revision}\n"
message += "Author: GayCookie ([email protected])\n"
message += "Source: https://git.gaycookie.dev/shits-and-giggles/wallpaper-roulette"
return message
def clean_up():
for file in os.listdir(download_dir):
file_path = os.path.join(download_dir, file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))
def download_image(url):
req = requests.get(url)
response, id = req.json()[0]["file_url"], req.json()[0]["id"]
ext = re.search("\.[0-9a-z]+$", response)
fileName = "{0}{1}".format(id, ext[0]) #url.split("/")[-1]
if os.path.exists(os.path.join(download_dir, fileName)):
set_wallpaper(os.path.join(download_dir, fileName))
else:
req = requests.get(response, stream = True)
if req.status_code == 200:
req.raw.decode_content = True
with open(os.path.join(download_dir, fileName), 'wb') as file:
shutil.copyfileobj(req.raw, file)
set_wallpaper(fileName)
else:
return False
def set_wallpaper(filename):
file = os.path.join(download_dir, filename)
# This works only on Windows 10
if sys.platform == "win32":
ctypes.windll.user32.SystemParametersInfoW(20, 0, file , 0)
# This works only on Linux when using Gnome.
if sys.platform == "linux":
os.system(f'gsettings set org.gnome.desktop.background picture-uri "{file}"')
if __name__ == "__main__":
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-v', '--version', action="version", version=show_version(), help="Show version and information.")
parser.add_argument('-s', '--service', default="konachan", help="Which service being used to find images.")
parser.add_argument('-t', '--tag', default="animal_ears", help="Tag to be used for searching images.")
parser.add_argument('-x', '--width', default="1920", help="Exact image size (Width).")
parser.add_argument('-y', '--height', default="1080", help="Exact image size (Height).")
parser.add_argument('-r', '--rating', default="safe", help="Image rating (may differ per API).")
parser.add_argument('-c', '--clean', action='store_true', help="Remove previous downloaded images.")
args = parser.parse_args()
for service in services:
if service.name == args.service:
service = service
break
generator = URLGenerator(service)
generator.set_tag(args.tag)
generator.set_width(args.width)
generator.set_height(args.height)
generator.set_rating(args.rating)
# If '--clear' is being used, previous downloaded files will be cleared.
if args.clean:
clean_up()
## Download
url = generator.generate_url()
download_image(url)