Last active
March 2, 2022 21:40
-
-
Save xthesaintx/88c012bdebd1d1dd8854140ffcbbc751 to your computer and use it in GitHub Desktop.
Watch Folder - The watched folder feature of qbittorrent on the Pi is pretty flaky and I find I have to keep resetting it. So I wrote my own in Python... It's pretty hacky to get the script to wait for the file to be finished writing (as depending on where the file is copied from 2 to god knows how many events watch_dog will raise on closed), an…
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
import time | |
import subprocess | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
from watchdog.events import PatternMatchingEventHandler | |
import qbittorrentapi | |
import os | |
import logging | |
import shutil | |
logging.basicConfig(filename='/home/pi/Scripts/watch.log', filemode='a', format ='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d-%m-%Y %H:%M:%S' ) | |
logger=logging.getLogger() | |
logger.setLevel(logging.INFO) | |
#folder check interval | |
t = 10 | |
#Paths | |
path = "/mnt/HDD2TB/watch" | |
temp_path ="/mnt/HDD2TB/watch/temp/" | |
class Watcher: | |
DIRECTORY_TO_WATCH = path | |
def __init__(self): | |
self.observer = Observer() | |
def run(self): | |
event_handler = Handler(patterns=["*.torrent"],ignore_patterns=["._*"],ignore_directories=True) | |
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=False) | |
self.observer.start() | |
try: | |
while True: | |
time.sleep(t) | |
except: | |
self.observer.stop() | |
logger.warning ("Error") | |
self.observer.join() | |
class Handler(PatternMatchingEventHandler): | |
global tfile | |
@staticmethod | |
def on_any_event(event): | |
if event.is_directory: | |
return None | |
elif event.event_type == 'created': | |
return None | |
elif event.event_type == 'modified': | |
return None | |
elif event.event_type == 'closed': | |
# Wait so doesn't prematurely action | |
time.sleep(5) | |
# Set the base vars for checking stability | |
historicalSize = -1 | |
tfile = "" | |
# Check file size is stable | |
if os.path.exists(event.src_path): | |
while (historicalSize != os.path.getsize(event.src_path)): | |
historicalSize = os.path.getsize(event.src_path) | |
time.sleep(5) | |
# Check that the file is there... We might of moved it already | |
if os.path.exists(event.src_path): | |
file_done = False | |
else: | |
file_done = True | |
# If the file is there and not completed its move check that we can move it (not locked) | |
while not file_done: | |
try: | |
if os.path.exists(event.src_path): | |
shutil.copy(event.src_path, temp_path) | |
if os.path.exists(event.src_path): | |
os.remove(event.src_path) | |
# Mark the file as complete | |
file_done = True | |
tfile = temp_path+(os.path.relpath(event.src_path, path)) | |
#LOG ON TO QBIT AND ADD TORRENT | |
qbt_client = qbittorrentapi.Client(host="192.168.0.122:8080", username='admin', password='adminadmin') | |
added = qbt_client.torrents_add(torrent_files=tfile) | |
# If it added to Qbit, delete the files | |
if added == "Ok.": | |
logger.info ("ADDED: "+tfile) | |
if os.path.exists(tfile): | |
os.remove(tfile) | |
else: | |
logger.warning ("FAILED: "+tfile) | |
return True | |
except: | |
return True | |
return None | |
if __name__ == '__main__': | |
w = Watcher() | |
w.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-- Running the script as a service --
sudo touch /etc/systemd/system/watch.service
sudo nano /etc/systemd/system/watch.service
-- Service file contents --
#Start of file
[Unit]
Description=Watch
After=network.target
[Service]
User=pi
Group=pi
Restart=always
RestartSec=10
PermissionsStartOnly=true
ExecStart=python3 /home/pi/Scripts/watch.py
[Install]
WantedBy=multi-user.target
#End of file
-- Start and Enable --
sudo systemctl start watch4
sudo systemctl enable watch4
systemctl status watch4