Code: Select all
### NZBGET POST-PROCESSING SCRIPT ###
##############################################################################
import os
import sys
import datetime
import core
from core.autoProcess.autoProcessComics import autoProcessComics
from core.autoProcess.autoProcessGames import autoProcessGames
from core.autoProcess.autoProcessMovie import autoProcessMovie
from core.autoProcess.autoProcessMusic import autoProcessMusic
from core.autoProcess.autoProcessTV import autoProcessTV
from core.nzbToMediaUtil import getDirs, extractFiles, cleanDir, update_downloadInfoStatus, get_downloadInfo, CharReplace, convert_to_ascii, get_nzoid, plex_update
from core.nzbToMediaUserScript import external_script
from core import logger, nzbToMediaDB
# post-processing
def process(inputDirectory, inputName=None, status=0, clientAgent='manual', download_id=None, inputCategory=None, failureLink=None):
if core.SAFE_MODE and inputDirectory == core.NZB_DEFAULTDIR:
logger.error(
'The input directory:[%s] is the Default Download Directory. Please configure category directories to prevent processing of other media.' % (
inputDirectory))
return [-1, ""]
if not download_id and clientAgent == 'sabnzbd':
download_id = get_nzoid(inputName)
if clientAgent != 'manual' and not core.DOWNLOADINFO:
logger.debug('Adding NZB download info for directory %s to database' % (inputDirectory))
myDB = nzbToMediaDB.DBConnection()
encoded, inputDirectory1 = CharReplace(inputDirectory)
encoded, inputName1 = CharReplace(inputName)
controlValueDict = {"input_directory": unicode(inputDirectory1)}
newValueDict = {"input_name": unicode(inputName1),
"input_hash": unicode(download_id),
"input_id": unicode(download_id),
"client_agent": unicode(clientAgent),
"status": 0,
"last_update": datetime.date.today().toordinal()
}
myDB.upsert("downloads", newValueDict, controlValueDict)
# auto-detect section
if inputCategory is None:
inputCategory = 'UNCAT'
usercat = inputCategory
section = core.CFG.findsection(inputCategory).isenabled()
if section is None:
section = core.CFG.findsection("ALL").isenabled()
if section is None:
logger.error(
'Category:[%s] is not defined or is not enabled. Please rename it or ensure it is enabled for the appropriate section in your autoProcessMedia.cfg and try again.' % (
inputCategory))
return [-1, ""]
else:
usercat = "ALL"
if len(section) > 1:
logger.error(
'Category:[%s] is not unique, %s are using it. Please rename it or disable all other sections using the same category name in your autoProcessMedia.cfg and try again.' % (
inputCategory, section.keys()))
return [-1, ""]
if section:
sectionName = section.keys()[0]
logger.info('Auto-detected SECTION:%s' % (sectionName))
else:
logger.error("Unable to locate a section with subsection:%s enabled in your autoProcessMedia.cfg, exiting!" % (
inputCategory))
return [-1, ""]
try:
extract = int(section[usercat]['extract'])
except:
extract = 0
try:
if int(section[usercat]['remote_path']) and not core.REMOTEPATHS:
logger.error('Remote Path is enabled for %s:%s but no Network mount points are defined. Please check your autoProcessMedia.cfg, exiting!' % (
sectionName, inputCategory))
return [-1, ""]
except:
logger.error('Remote Path %s is not valid for %s:%s Please set this to either 0 to disable or 1 to enable!' % (
section[usercat]['remote_path'], sectionName, inputCategory))
inputName, inputDirectory = convert_to_ascii(inputName, inputDirectory)
if extract == 1:
logger.debug('Checking for archives to extract in directory: %s' % (inputDirectory))
extractFiles(inputDirectory)
logger.info("Calling %s:%s to post-process:%s" % (sectionName, inputCategory, inputName))
if sectionName == "CouchPotato":
result = autoProcessMovie().process(sectionName, inputDirectory, inputName, status, clientAgent, download_id,
inputCategory, failureLink)
elif sectionName in ["SickBeard", "NzbDrone"]:
result = autoProcessTV().processEpisode(sectionName, inputDirectory, inputName, status, clientAgent,
download_id, inputCategory, failureLink)
elif sectionName == "HeadPhones":
result = autoProcessMusic().process(sectionName, inputDirectory, inputName, status, clientAgent, inputCategory)
elif sectionName == "Mylar":
result = autoProcessComics().processEpisode(sectionName, inputDirectory, inputName, status, clientAgent,
inputCategory)
elif sectionName == "Gamez":
result = autoProcessGames().process(sectionName, inputDirectory, inputName, status, clientAgent, inputCategory)
elif sectionName == 'UserScript':
result = external_script(inputDirectory, inputName, inputCategory, section[usercat])
else:
result = [-1, ""]
plex_update(inputCategory)
if result[0] == 0:
if clientAgent != 'manual':
# update download status in our DB
update_downloadInfoStatus(inputName, 1)
if not sectionName in ['UserScript', 'NzbDrone']:
# cleanup our processing folders of any misc unwanted files and empty directories
cleanDir(inputDirectory, sectionName, inputCategory)
return result
def main(args, section=None):
# Initialize the config
core.initialize(section)
# clientAgent for NZBs
clientAgent = core.NZB_CLIENTAGENT
logger.info("#########################################################")
logger.info("## ..::[%s]::.. ##" % os.path.basename(__file__))
logger.info("#########################################################")
# debug command line options
logger.debug("Options passed into nzbToMedia: %s" % args)
# Post-Processing Result
result = [0, ""]
status = 0
# NZBGet
if os.environ.has_key('NZBOP_SCRIPTDIR'):
# Check if the script is called from nzbget 11.0 or later
if os.environ['NZBOP_VERSION'][0:5] < '11.0':
logger.error("NZBGet Version %s is not supported. Please update NZBGet." %(str(os.environ['NZBOP_VERSION'])))
sys.exit(core.NZBGET_POSTPROCESS_ERROR)
logger.info("Script triggered from NZBGet Version %s." %(str(os.environ['NZBOP_VERSION'])))
# Check if the script is called from nzbget 13.0 or later
if os.environ.has_key('NZBPP_TOTALSTATUS'):
if not os.environ['NZBPP_TOTALSTATUS'] == 'SUCCESS':
logger.info("Download failed with status %s." %(os.environ['NZBPP_STATUS']))
status = 1
else:
# Check par status
if os.environ['NZBPP_PARSTATUS'] == '1' or os.environ['NZBPP_PARSTATUS'] == '4':
logger.warning("Par-repair failed, setting status \"failed\"")
status = 1
# Check unpack status
if os.environ['NZBPP_UNPACKSTATUS'] == '1':
logger.warning("Unpack failed, setting status \"failed\"")
status = 1
if os.environ['NZBPP_UNPACKSTATUS'] == '0' and os.environ['NZBPP_PARSTATUS'] == '0':
# Unpack was skipped due to nzb-file properties or due to errors during par-check
if os.environ['NZBPP_HEALTH'] < 1000:
logger.warning(
"Download health is compromised and Par-check/repair disabled or no .par2 files found. Setting status \"failed\"")
logger.info("Please check your Par-check/repair settings for future downloads.")
status = 1
else:
logger.info(
"Par-check/repair disabled or no .par2 files found, and Unpack not required. Health is ok so handle as though download successful")
logger.info("Please check your Par-check/repair settings for future downloads.")
# Check for download_id to pass to CouchPotato
download_id = ""
failureLink = None
if os.environ.has_key('NZBPR_COUCHPOTATO'):
download_id = os.environ['NZBPR_COUCHPOTATO']
elif os.environ.has_key('NZBPR_DRONE'):
download_id = os.environ['NZBPR_DRONE']
elif os.environ.has_key('NZBPR_SONARR'):
download_id = os.environ['NZBPR_SONARR']
if os.environ.has_key('NZBPR__DNZB_FAILURE'):
failureLink = os.environ['NZBPR__DNZB_FAILURE']
# All checks done, now launching the script.
clientAgent = 'nzbget'
result = process(os.environ['NZBPP_DIRECTORY'], inputName=os.environ['NZBPP_NZBNAME'], status=status,
clientAgent=clientAgent, download_id=download_id, inputCategory=os.environ['NZBPP_CATEGORY'],
failureLink=failureLink)
# SABnzbd Pre 0.7.17
elif len(args) == core.SABNZB_NO_OF_ARGUMENTS:
# SABnzbd argv:
# 1 The final directory of the job (full path)
# 2 The original name of the NZB file
# 3 Clean version of the job name (no path info and ".nzb" removed)
# 4 Indexer's report number (if supported)
# 5 User-defined category
# 6 Group that the NZB was posted in e.g. alt.binaries.x
# 7 Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2
clientAgent = 'sabnzbd'
logger.info("Script triggered from SABnzbd")
result = process(args[1], inputName=args[2], status=args[7], inputCategory=args[5], clientAgent=clientAgent,
download_id='')
# SABnzbd 0.7.17+
elif len(args) >= core.SABNZB_0717_NO_OF_ARGUMENTS:
# SABnzbd argv:
# 1 The final directory of the job (full path)
# 2 The original name of the NZB file
# 3 Clean version of the job name (no path info and ".nzb" removed)
# 4 Indexer's report number (if supported)
# 5 User-defined category
# 6 Group that the NZB was posted in e.g. alt.binaries.x
# 7 Status of post processing. 0 = OK, 1=failed verification, 2=failed unpack, 3=1+2
# 8 Failure URL
clientAgent = 'sabnzbd'
logger.info("Script triggered from SABnzbd 0.7.17+")
result = process(args[1], inputName=args[2], status=args[7], inputCategory=args[5], clientAgent=clientAgent,
download_id='', failureLink=''.join(args[8:]))
else:
# Perform Manual Post-Processing
logger.warning("Invalid number of arguments received from client, Switching to manual run mode ...")
for section, subsections in core.SECTIONS.items():
for subsection in subsections:
if not core.CFG[section][subsection].isenabled():
continue
for dirName in getDirs(section, subsection, link = 'move'):
logger.info("Starting manual run for %s:%s - Folder:%s" % (section, subsection, dirName))
logger.info("Checking database for download info for %s ..." % (os.path.basename(dirName)))
core.DOWNLOADINFO = get_downloadInfo(os.path.basename(dirName), 0)
if core.DOWNLOADINFO:
logger.info(
"Found download info for %s, setting variables now ..." % (os.path.basename(dirName)))
else:
logger.info(
'Unable to locate download info for %s, continuing to try and process this release ...' % (
os.path.basename(dirName))
)
try:
clientAgent = str(core.DOWNLOADINFO[0]['client_agent'])
except:
clientAgent = 'manual'
try:
download_id = str(core.DOWNLOADINFO[0]['input_id'])
except:
download_id = None
if clientAgent.lower() not in core.NZB_CLIENTS and clientAgent != 'manual':
continue
try:
dirName = dirName.encode(core.SYS_ENCODING)
except: pass
inputName = os.path.basename(dirName)
try:
inputName = inputName.encode(core.SYS_ENCODING)
except: pass
results = process(dirName, inputName, 0, clientAgent=clientAgent,
download_id=download_id, inputCategory=subsection)
if results[0] != 0:
logger.error("A problem was reported when trying to perform a manual run for %s:%s." % (
section, subsection))
result = results
if result[0] == 0:
logger.info("The %s script completed successfully." % args[0])
if result[1]:
print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del core.MYAPP
return (core.NZBGET_POSTPROCESS_SUCCESS)
else:
logger.error("A problem was reported in the %s script." % args[0])
if result[1]:
print result[1] + "!" # For SABnzbd Status display.
if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11
del core.MYAPP
return (core.NZBGET_POSTPROCESS_ERROR)
del core.MYAPP
return (result[0])
if __name__ == '__main__':
exit(main(sys.argv))
so i am a bit confused where to edit this...
i was hoping to find a solution without editing the script as it auto updates each time it is executed so any changes i make it would be wiped out...
is there no way for the .app to get the environmental variables from my .bash_profile or /etc/paths ?