Last active
February 22, 2022 22:05
-
-
Save sam2332/a8017d785e8b2087a7f60fa41cfd86a2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##Magic Logging Bootstrap | |
import logging | |
import sys,os | |
logging.basicConfig( | |
filename='randomWp.log', | |
level=logging.INFO, | |
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s', | |
datefmt='%Y-%m-%d %H:%M:%S' | |
) | |
exlogger = logging.getLogger("Exception") | |
def handle_exception(exc_type, exc_value, exc_traceback): | |
if issubclass(exc_type, KeyboardInterrupt): | |
sys.__excepthook__(exc_type, exc_value, exc_traceback) | |
return | |
exlogger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) | |
sys.excepthook = handle_exception | |
class StreamToLogger(object): | |
""" | |
Fake file-like stream object that redirects writes to a logger instance. | |
""" | |
def __init__(self, logger, level): | |
self.logger = logger | |
self.level = level | |
self.linebuf = '' | |
def write(self, buf): | |
for line in buf.rstrip().splitlines(): | |
self.logger.log(self.level, line.rstrip()) | |
def flush(self): | |
pass | |
log = logging.getLogger('Stdout') | |
sys.stdout = StreamToLogger(log,logging.INFO) | |
log = logging.getLogger('Stderr') | |
sys.stderr = StreamToLogger(log,logging.ERROR) | |
##Finished Magic Logging Bootstrap | |
if os.path.exists('wp-lock'): | |
print('wp-lock file is present') | |
sys.exit(1) | |
with open('wp-lock','w') as f: | |
f.write(' ') | |
import psutil | |
import os | |
import random | |
from bs4 import BeautifulSoup | |
from queue import Queue | |
import os | |
import time | |
import requests | |
import subprocess | |
def getRandomBackground(): | |
try: | |
bgs = os.listdir(wallpaper_dir) | |
if len(bgs)==0: return None | |
return os.path.join(wallpaper_dir,random.choice(bgs)) | |
except Exception as e: | |
print(e) | |
return None | |
def downloadSomePapers(): | |
if os.path.exists('wp-downloading'): | |
print('wp-downloading file is present') | |
sys.exit(1) | |
with open('wp-downloading','w') as f: | |
f.write(' ') | |
sfw = 1 | |
sketchy = 0 | |
nsfw = 0 | |
blacklist=[ | |
'https://wallhaven.cc/images/layout/logo_sm.png' | |
] | |
wallpaper_dir = os.path.expanduser("/home/srudloff/Pictures/Wallpapers") | |
if not os.path.exists(wallpaper_dir): | |
os.mkdir(wallpaper_dir) | |
def process4WalledPage(url,existing): | |
res = requests.get(url,headers={"User-Agent":'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}) | |
soup = BeautifulSoup(res.text,features="lxml") | |
for item in soup.find_all('img'): | |
if 'data-src' in item.attrs: | |
if item.attrs['data-src'] not in blacklist: | |
item = item.attrs['data-src'] | |
item = item.replace("https://th.wallhaven.cc/small/", "") | |
item = item.replace("/","/wallhaven-") | |
url = f"https://w.wallhaven.cc/full/{item}" | |
if url not in existing: | |
fn = item.split('/').pop() | |
yield((fn, url)) | |
random_url = f"https://wallhaven.cc/random?purity={sfw}{sketchy}{nsfw}" | |
for filename,url in process4WalledPage(random_url,[]): | |
print(f"{url} => {filename}") | |
out_path = os.path.join(wallpaper_dir,filename) | |
if not os.path.exists(out_path): | |
res = requests.get(url) | |
if res.status_code == 200 and len(res.content)>1: | |
with open(out_path,'wb') as f: | |
f.write(res.content) | |
os.unlink('wp-downloading') | |
def get_DBUS_SESSION_BUS_ADDRESS(): | |
PID = None | |
for p in psutil.process_iter(): | |
if p.name() == "gnome-session-binary": | |
PID = p.pid | |
break | |
logging.debug(PID) | |
DBUS_SESSION_BUS_ADDRESS=None | |
with open(f'/proc/{PID}/environ', 'rb') as f: | |
d = f.read() | |
for line in d.split(b'\x00'): | |
if b'DBUS_SESSION_BUS_ADDRESS' in line: | |
line = line.split(b'=', maxsplit=1) | |
DBUS_SESSION_BUS_ADDRESS = line[1].decode('utf-8') | |
logging.debug(DBUS_SESSION_BUS_ADDRESS) | |
os.environ['DBUS_SESSION_BUS_ADDRESS'] = DBUS_SESSION_BUS_ADDRESS | |
return DBUS_SESSION_BUS_ADDRESS | |
wallpaper_dir = os.path.expanduser("~/Pictures/Wallpapers/") | |
logging.debug(wallpaper_dir) | |
old_wp = subprocess.check_output(["/usr/bin/gsettings","get","org.gnome.desktop.background","picture-uri"]).decode('utf-8').strip().rstrip("'").lstrip("'") | |
try: | |
os.unlink(old_wp) | |
except Exception as e: | |
pass | |
wallpaper =None | |
while wallpaper is None: | |
wallpaper = getRandomBackground() | |
if wallpaper is None: | |
downloadSomePapers() | |
logging.info(f'Changing Wallpaper to: {wallpaper}') | |
cmd =f"DBUS_SESSION_BUS_ADDRESS='{get_DBUS_SESSION_BUS_ADDRESS()}' /usr/bin/gsettings set org.gnome.desktop.background picture-uri {wallpaper}" | |
logging.debug(cmd) | |
os.system(cmd) | |
os.unlink('wp-lock') | |
if len(os.listdir(wallpaper_dir))<15: | |
downloadSomePapers() |
reorg
You can modify this code below and run it to add a menu option to unity search
echo ~/.local/share/applications/randomwallpaper.desktop << EOF
[Desktop Entry]
Type=Application
Terminal=false
Name=Random Wallpaper
Icon=/home/$USER/refresh.svg
Exec=python3 /home/$USER/randomWallpaper.py
EOF;
sudo update-desktop-database
and for cron the following will change wall paper every 15 min
15 * * * * /usr/bin/python3 ~/randomWallpaper.py
I added a bunch of locking code to the project so that we dont have multiple fetchers running at the same time
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated script to always show random wallpapers and to delete them from my system after showing them.