From 8cb3b6ad64a49cee77598cb7deaad91e32b6b283 Mon Sep 17 00:00:00 2001 From: Michael Higgins Date: Sun, 22 Feb 2015 22:22:38 -0500 Subject: [PATCH] uTorrent script update Updated the uTorrent script to comply with the new labeling scheme --- autoProcess.ini.sample | 5 +- readSettings.py | 10 ++- uTorrentPostProcess.py | 137 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 uTorrentPostProcess.py diff --git a/autoProcess.ini.sample b/autoProcess.ini.sample index 790dec82..dad86fc5 100644 --- a/autoProcess.ini.sample +++ b/autoProcess.ini.sample @@ -57,7 +57,10 @@ method = renamer delete_failed = 0 [uTorrent] -label= +convert= +couchpotato-label=couchpotato +sickbeard-label=sickbeard +sonarr-label=sonarr webui=False action_before=stop action_after=removedata diff --git a/readSettings.py b/readSettings.py index 40129cf9..7341e42e 100644 --- a/readSettings.py +++ b/readSettings.py @@ -71,7 +71,10 @@ def __init__(self, directory, filename): 'ssl': 'False', 'web_root': ''} # Default uTorrent settings - utorrent_defaults = { 'label': '', + utorrent_defaults = { 'couchpotato-label': 'couchpotato', + 'sickbeard-label': 'sickbeard', + 'sonarr-label': 'sonarr', + 'convert': 'True', 'webui': 'False', 'action_before': 'stop', 'action_after': 'removedata', @@ -306,6 +309,11 @@ def __init__(self, directory, filename): #Read relevant uTorrent section information section = "uTorrent" + self.uTorrent = {} + self.uTorrent['cp'] = config.get(section, "couchpotato-label").lower() + self.uTorrent['sb'] = config.get(section, "sickbeard-label").lower() + self.uTorrent['sonarr'] = config.get(section, "sonarr-label").lower() + self.uTorrent['convert'] = config.getboolean(section, "convert") self.uTorrentLabel = config.get(section, "label").lower() self.uTorrentWebUI = config.getboolean(section, "webui") self.uTorrentActionBefore = config.get(section, "action_before").lower() diff --git a/uTorrentPostProcess.py b/uTorrentPostProcess.py new file mode 100644 index 00000000..0c82834a --- /dev/null +++ b/uTorrentPostProcess.py @@ -0,0 +1,137 @@ +import os +import re +import sys +import autoProcessTV, autoProcessMovie +from readSettings import ReadSettings +from mkvtomp4 import MkvtoMp4 + +#Args: %L %T %D %K %F %I Label, Tracker, Directory, single|multi, NameofFile(if single), InfoHash + +def _authToken(session=None, host=None, username=None, password=None): + auth = None + if not session: + session = requests.Session() + response = session.get(host + "gui/token.html", auth=(username, password), verify=False, timeout=30) + if response.status_code == 200: + auth = re.search("(\S+)<\/div>", response.text).group(1) + else: + print "[uTorrent] Authentication Failed - Status Code " + response.status_code + + return auth,session + +def _sendRequest(session, host='http://localhost:8080/', username=None, password=None, params=None, files=None, fnct=None): + try: + response = session.post(host + "gui/", auth=(username, password), params=params, files=files, timeout=30) + except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError), e: + print "[uTorrent] Problem sending command " + fnct + " - " + str(e) + return False + + if response.status_code == 200: + return True + + print "[uTorrent] Problem sending command " + fnct + ", return code = " + str(response.status_code) + return False + +path = str(sys.argv[3]) +settings = ReadSettings(os.path.dirname(sys.argv[0]), "autoProcess.ini") +label = sys.argv[1].lower() + +categories = [settings.uTorrent['cp'], settings.uTorrent['sb'], settings.uTorrent['sonarr']] + +if label not in categories: + print "No valid label detected" + sys.exit() + +# Import requests +try: + import requests +except ImportError: + print "[ERROR] Python module REQUESTS is required. Install with 'pip install requests' then try again." + sys.exit() + +try: + torrent_hash = sys.argv[6] + web_ui = settings.uTorrentWebUI +except: + web_ui = False + +if settings.uTorrent['convert']: + # Run a uTorrent action before conversion. + if web_ui: + session = requests.Session() + if session: + auth,session = _authToken(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword) + if auth and settings.uTorrentActionBefore: + params = {'token': auth, 'action': settings.uTorrentActionBefore, 'hash': torrent_hash} + _sendRequest(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword, params, None, "Stop") + + # Perform conversion. + delete_dir = False + settings.delete = False + if not settings.output_dir: + settings.output_dir = os.path.join(path, 'converted') + if not os.path.exists(settings.output_dir): + os.mkdir(settings.output_dir) + delete_dir = True + + converter = MkvtoMp4(settings) + + if str(sys.argv[4]) == 'single': + inputfile = os.path.join(path,str(sys.argv[5])) + if MkvtoMp4(settings).validSource(inputfile): + converter.process(inputfile) + else: + for r, d, f in os.walk(path): + for files in f: + inputfile = os.path.join(r, files) + if MkvtoMp4(settings).validSource(inputfile): + converter.process(inputfile) + + path = converter.output_dir + # Run a uTorrent action after conversion. + if web_ui: + if session and auth and settings.uTorrentActionAfter: + params = {'token': auth, 'action': settings.uTorrentActionAfter, 'hash': torrent_hash} + _sendRequest(session, settings.uTorrentHost, settings.uTorrentUsername, settings.uTorrentPassword, params, None, "Remove Data") + +if label == categories[0]: + autoProcessMovie.process(path, settings) + if os.path.exists(settings.output_dir) and delete_dir: + try: + os.rmdir(converter.output_dir) + except: + print "Unable to delete temporary conversion directory" +elif label == categories[1]: + autoProcessTV.processEpisode(path) + if os.path.exists(settings.output_dir) and delete_dir: + try: + os.rmdir(converter.output_dir) + except: + print "Unable to delete temporary conversion directory" +elif label == categories[2]: + host=settings.Sonarr['host'] + port=settings.Sonarr['port'] + apikey = settings.Sonarr['apikey'] + if apikey == '': + print "[WARNING] Your Sonarr API Key can not be blank. Update autoProcess.ini" + sys.exit(POSTPROCESS_ERROR) + try: + ssl=int(settings.Sonarr['ssl']) + except: + ssl=0 + if ssl: + protocol="https://" + else: + protocol="http://" + url = protocol+host+":"+port+"/api/command" + payload = {'name': 'downloadedepisodesscan','path': path} + print "[INFO] Requesting Sonarr to scan folder '"+path+"'" + headers = {'X-Api-Key': apikey} + try: + r = requests.post(url, data=json.dumps(payload), headers=headers) + rstate = r.json() + print "[INFO] Sonarr responds as "+rstate['state']+"." + except: + print "[WARNING] Update to Sonarr failed, check if Sonarr is running, autoProcess.ini for errors, or check install of python modules requests." + sys.exit(POSTPROCESS_ERROR) + sys.exit(POSTPROCESS_SUCCESS)