Skip to content

Instantly share code, notes, and snippets.

@bengalih
Created November 18, 2024 22:47
Show Gist options
  • Save bengalih/1341b528f95384522a28b0fca17ccbf8 to your computer and use it in GitHub Desktop.
Save bengalih/1341b528f95384522a28b0fca17ccbf8 to your computer and use it in GitHub Desktop.
#!D:\Program Files\Python37\python.exe
# UPDATE THE PATH ABOVE TO THE FULL PATH TO YOUR python.exe FILE!!!!
# deluge-banned-files-rpc.py
# bengalih
# v.0.1
# The purpose of this script is to be run with the Execute plugin for Deluge
# Enable it to run on Torrent Add event
# If there are problems, enable Deluge debug logging and search for the name of this script.
# This version is meant to be used with the Deluge Daemon RPC (deluged).
# Configure it in Preferences > Daemon
############################################################################
# Predefined list of file extensions to check
TARGET_EXTENSIONS = ['lnk', 'ps1', 'zipx', 'arj']
# Label to set to
LABEL_TO_SET = "banned" # make sure you define this label in your client
LOG_FILE = 'D:\\ProgramData\\custom_scripts\\deluge\\banned-torrents.txt' # Use double slashes "\\" (escape) on Windows systems
DELUGE_IP = 'localhost' # Set IP (or 127.0.0.1 for localhost)
DELUGE_RPC_PORT = 58846
DELUGE_USERNAME = 'USERNAME'
DELUGE_PASSWORD = 'password123'
############################################################################
from deluge_client import DelugeRPCClient
import sys
import logging
import time
import subprocess
# Set logging level for the 'deluge_client' logger to WARNING or ERROR to suppress info/debug messages
logging.getLogger("deluge_client").setLevel(logging.WARNING)
# Configure logging to append to banned-torrents.txt
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(message)s',
filemode='a' # 'a' to append to the existing file
)
def pause_torrent_and_log_files(torrent_id):
# Connect to the Deluge daemon
client = DelugeRPCClient(DELUGE_IP, DELUGE_RPC_PORT, DELUGE_USERNAME, DELUGE_PASSWORD)
try:
client.connect()
logging.debug("Connected to Deluge daemon.")
print("Connected to Deluge daemon.")
# Set a timeout limit (in seconds) to prevent an infinite loop
timeout = 7200
start_time = time.time()
# Wait for the metadata to be available
while True:
try:
torrent_info = client.core.get_torrent_status(torrent_id, ['name', 'files', 'is_seed'])
# Check if torrent_info is empty or None (if the torrent is deleted)
if not torrent_info:
logging.error(f"Torrent ID {torrent_id} not found. It might have been deleted.")
print(f"Torrent ID {torrent_id} not found. It might have been deleted.")
return # Exit the function
files = torrent_info.get(b'files', [])
# If metadata is available or it's a seed, exit the loop
if files or torrent_info.get(b'is_seed', False):
break
# Timeout handling
if time.time() - start_time > timeout:
logging.error(f"Timeout while waiting for metadata for Torrent ID: {torrent_id}")
print(f"Timeout while waiting for metadata for Torrent ID: {torrent_id}")
return # Exit the function
logging.debug(f"Waiting for metadata to be available for Torrent ID: {torrent_id}...")
print(f"Waiting for metadata to be available for Torrent ID: {torrent_id}...")
time.sleep(1) # Wait for 1 second before checking again
except Exception as e:
logging.error(f"An error occurred while fetching torrent status: {e}")
print(f"An error occurred while fetching torrent status: {e}")
return
# Handle name
name = torrent_info.get(b'name', b'').decode('utf-8') if isinstance(torrent_info.get(b'name', b''), bytes) else torrent_info.get('name', '')
# Check for target file extensions and collect matching files
matching_files = [file.get(b'path', b'').decode('utf-8') for file in files if file.get(b'path', b'').decode('utf-8').endswith(tuple(TARGET_EXTENSIONS))]
if matching_files:
# Log the initial information using the torrent name
logging.info(f"Torrent Name: {name}")
#Change the label of the torrent - We can't do this with sonarr if we want to delete from import queue
#client.label.set_torrent(torrent_id, LABEL_TO_SET)
#logging.info(f"Label updated to '{LABEL_TO_SET}' for Torrent: {name}")
# Pause the torrent
client.core.pause_torrent([torrent_id]) # Pause the torrent
logging.info(f"Torrent '{name}' paused due to matching file extension.")
print(f"Paused Torrent: {name}")
# Write matching files to the log
for file_name in matching_files:
logging.info(f"Banned file for Torrent '{name}': {file_name}")
print(f"Banned file: {file_name}")
# Path to the script you want to call
script_path=r"D:\ProgramData\custom_scripts\deluge\sonarr-blacklist.py"
# Call the script with the torrent_id as an argument
subprocess.run([r"D:\Program Files\Python37\python.exe", script_path, torrent_id])
except Exception as e:
logging.error(f"An error occurred: {e}")
print(f"An error occurred: {e}")
finally:
client.disconnect()
logging.debug("Disconnected from Deluge daemon.")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Please provide the torrent ID as an argument.")
sys.exit(1)
torrent_id = sys.argv[1]
logging.debug(f"Script started with torrent ID: {torrent_id}")
pause_torrent_and_log_files(torrent_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment