PEP8 Variable in function should be lowercase

This commit is contained in:
Labrys of Knossos 2018-12-16 20:00:13 -05:00
commit 97e1ed71b3
15 changed files with 977 additions and 953 deletions

View file

@ -12,64 +12,68 @@ from libs.six import text_type
def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, clientAgent):
input_directory = inputDirectory
input_name = inputName
input_category = inputCategory
input_hash = inputHash
status = 1 # 1 = failed | 0 = success
root = 0
foundFile = 0
found_file = 0
if clientAgent != 'manual' and not core.DOWNLOADINFO:
logger.debug('Adding TORRENT download info for directory {0} to database'.format(inputDirectory))
logger.debug('Adding TORRENT download info for directory {0} to database'.format(input_directory))
myDB = nzbToMediaDB.DBConnection()
my_db = nzbToMediaDB.DBConnection()
inputDirectory1 = inputDirectory
inputName1 = inputName
input_directory1 = input_directory
input_name1 = input_name
try:
encoded, inputDirectory1 = CharReplace(inputDirectory)
encoded, inputName1 = CharReplace(inputName)
encoded, input_directory1 = CharReplace(input_directory)
encoded, input_name1 = CharReplace(input_name)
except:
pass
controlValueDict = {"input_directory": text_type(inputDirectory1)}
newValueDict = {"input_name": text_type(inputName1),
"input_hash": text_type(inputHash),
control_value_dict = {"input_directory": text_type(input_directory1)}
new_value_dict = {"input_name": text_type(input_name1),
"input_hash": text_type(input_hash),
"input_id": text_type(inputID),
"client_agent": text_type(clientAgent),
"status": 0,
"last_update": datetime.date.today().toordinal()
}
myDB.upsert("downloads", newValueDict, controlValueDict)
my_db.upsert("downloads", new_value_dict, control_value_dict)
logger.debug("Received Directory: {0} | Name: {1} | Category: {2}".format(inputDirectory, inputName, inputCategory))
logger.debug("Received Directory: {0} | Name: {1} | Category: {2}".format(input_directory, input_name, input_category))
# Confirm the category by parsing directory structure
inputDirectory, inputName, inputCategory, root = core.category_search(inputDirectory, inputName, inputCategory,
root, core.CATEGORIES)
if inputCategory == "":
inputCategory = "UNCAT"
input_directory, input_name, input_category, root = core.category_search(input_directory, input_name, input_category,
root, core.CATEGORIES)
if input_category == "":
input_category = "UNCAT"
usercat = inputCategory
usercat = input_category
try:
inputName = inputName.encode(core.SYS_ENCODING)
input_name = input_name.encode(core.SYS_ENCODING)
except UnicodeError:
pass
try:
inputDirectory = inputDirectory.encode(core.SYS_ENCODING)
input_directory = input_directory.encode(core.SYS_ENCODING)
except UnicodeError:
pass
logger.debug("Determined Directory: {0} | Name: {1} | Category: {2}".format
(inputDirectory, inputName, inputCategory))
(input_directory, input_name, input_category))
# auto-detect section
section = core.CFG.findsection(inputCategory).isenabled()
section = core.CFG.findsection(input_category).isenabled()
if section is None:
section = core.CFG.findsection("ALL").isenabled()
if section is None:
logger.error('Category:[{0}] 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.'.format
(inputCategory))
(input_category))
return [-1, ""]
else:
usercat = "ALL"
@ -82,95 +86,95 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
return [-1, ""]
if section:
sectionName = section.keys()[0]
logger.info('Auto-detected SECTION:{0}'.format(sectionName))
section_name = section.keys()[0]
logger.info('Auto-detected SECTION:{0}'.format(section_name))
else:
logger.error("Unable to locate a section with subsection:{0} "
"enabled in your autoProcessMedia.cfg, exiting!".format
(inputCategory))
(input_category))
return [-1, ""]
section = dict(section[sectionName][usercat]) # Type cast to dict() to allow effective usage of .get()
section = dict(section[section_name][usercat]) # Type cast to dict() to allow effective usage of .get()
Torrent_NoLink = int(section.get("Torrent_NoLink", 0))
torrent_no_link = int(section.get("Torrent_NoLink", 0))
keep_archive = int(section.get("keep_archive", 0))
extract = int(section.get('extract', 0))
extensions = section.get('user_script_mediaExtensions', "").lower().split(',')
uniquePath = int(section.get("unique_path", 1))
unique_path = int(section.get("unique_path", 1))
if clientAgent != 'manual':
core.pause_torrent(clientAgent, inputHash, inputID, inputName)
core.pause_torrent(clientAgent, input_hash, inputID, input_name)
# In case input is not directory, make sure to create one.
# This way Processing is isolated.
if not os.path.isdir(os.path.join(inputDirectory, inputName)):
basename = os.path.basename(inputDirectory)
basename = core.sanitizeName(inputName) \
if inputName == basename else os.path.splitext(core.sanitizeName(inputName))[0]
outputDestination = os.path.join(core.OUTPUTDIRECTORY, inputCategory, basename)
elif uniquePath:
outputDestination = os.path.normpath(
core.os.path.join(core.OUTPUTDIRECTORY, inputCategory, core.sanitizeName(inputName).replace(" ",".")))
if not os.path.isdir(os.path.join(input_directory, input_name)):
basename = os.path.basename(input_directory)
basename = core.sanitizeName(input_name) \
if input_name == basename else os.path.splitext(core.sanitizeName(input_name))[0]
output_destination = os.path.join(core.OUTPUTDIRECTORY, input_category, basename)
elif unique_path:
output_destination = os.path.normpath(
core.os.path.join(core.OUTPUTDIRECTORY, input_category, core.sanitizeName(input_name).replace(" ",".")))
else:
outputDestination = os.path.normpath(
core.os.path.join(core.OUTPUTDIRECTORY, inputCategory))
output_destination = os.path.normpath(
core.os.path.join(core.OUTPUTDIRECTORY, input_category))
try:
outputDestination = outputDestination.encode(core.SYS_ENCODING)
output_destination = output_destination.encode(core.SYS_ENCODING)
except UnicodeError:
pass
if outputDestination in inputDirectory:
outputDestination = inputDirectory
if output_destination in input_directory:
output_destination = input_directory
logger.info("Output directory set to: {0}".format(outputDestination))
logger.info("Output directory set to: {0}".format(output_destination))
if core.SAFE_MODE and outputDestination == core.TORRENT_DEFAULTDIR:
if core.SAFE_MODE and output_destination == core.TORRENT_DEFAULTDIR:
logger.error('The output directory:[{0}] is the Download Directory. '
'Edit outputDirectory in autoProcessMedia.cfg. Exiting'.format
(inputDirectory))
(input_directory))
return [-1, ""]
logger.debug("Scanning files in directory: {0}".format(inputDirectory))
logger.debug("Scanning files in directory: {0}".format(input_directory))
if sectionName in ['HeadPhones', 'Lidarr']:
if section_name in ['HeadPhones', 'Lidarr']:
core.NOFLATTEN.extend(
inputCategory) # Make sure we preserve folder structure for HeadPhones.
input_category) # Make sure we preserve folder structure for HeadPhones.
now = datetime.datetime.now()
if extract == 1:
inputFiles = core.listMediaFiles(inputDirectory, archives=False, other=True, otherext=extensions)
input_files = core.listMediaFiles(input_directory, archives=False, other=True, otherext=extensions)
else:
inputFiles = core.listMediaFiles(inputDirectory, other=True, otherext=extensions)
if len(inputFiles) == 0 and os.path.isfile(inputDirectory):
inputFiles = [inputDirectory]
logger.debug("Found 1 file to process: {0}".format(inputDirectory))
input_files = core.listMediaFiles(input_directory, other=True, otherext=extensions)
if len(input_files) == 0 and os.path.isfile(input_directory):
input_files = [input_directory]
logger.debug("Found 1 file to process: {0}".format(input_directory))
else:
logger.debug("Found {0} files in {1}".format(len(inputFiles), inputDirectory))
for inputFile in inputFiles:
filePath = os.path.dirname(inputFile)
fileName, fileExt = os.path.splitext(os.path.basename(inputFile))
fullFileName = os.path.basename(inputFile)
logger.debug("Found {0} files in {1}".format(len(input_files), input_directory))
for inputFile in input_files:
file_path = os.path.dirname(inputFile)
file_name, file_ext = os.path.splitext(os.path.basename(inputFile))
full_file_name = os.path.basename(inputFile)
targetFile = core.os.path.join(outputDestination, fullFileName)
if inputCategory in core.NOFLATTEN:
if not os.path.basename(filePath) in outputDestination:
targetFile = core.os.path.join(
core.os.path.join(outputDestination, os.path.basename(filePath)), fullFileName)
target_file = core.os.path.join(output_destination, full_file_name)
if input_category in core.NOFLATTEN:
if not os.path.basename(file_path) in output_destination:
target_file = core.os.path.join(
core.os.path.join(output_destination, os.path.basename(file_path)), full_file_name)
logger.debug("Setting outputDestination to {0} to preserve folder structure".format
(os.path.dirname(targetFile)))
(os.path.dirname(target_file)))
try:
targetFile = targetFile.encode(core.SYS_ENCODING)
target_file = target_file.encode(core.SYS_ENCODING)
except UnicodeError:
pass
if root == 1:
if not foundFile:
logger.debug("Looking for {0} in: {1}".format(inputName, inputFile))
if any([core.sanitizeName(inputName) in core.sanitizeName(inputFile),
core.sanitizeName(fileName) in core.sanitizeName(inputName)]):
foundFile = True
if not found_file:
logger.debug("Looking for {0} in: {1}".format(input_name, inputFile))
if any([core.sanitizeName(input_name) in core.sanitizeName(inputFile),
core.sanitizeName(file_name) in core.sanitizeName(input_name)]):
found_file = True
logger.debug("Found file {0} that matches Torrent Name {1}".format
(fullFileName, inputName))
(full_file_name, input_name))
else:
continue
@ -178,78 +182,78 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
mtime_lapse = now - datetime.datetime.fromtimestamp(os.path.getmtime(inputFile))
ctime_lapse = now - datetime.datetime.fromtimestamp(os.path.getctime(inputFile))
if not foundFile:
if not found_file:
logger.debug("Looking for files with modified/created dates less than 5 minutes old.")
if (mtime_lapse < datetime.timedelta(minutes=5)) or (ctime_lapse < datetime.timedelta(minutes=5)):
foundFile = True
found_file = True
logger.debug("Found file {0} with date modified/created less than 5 minutes ago.".format
(fullFileName))
(full_file_name))
else:
continue # This file has not been recently moved or created, skip it
if Torrent_NoLink == 0:
if torrent_no_link == 0:
try:
core.copy_link(inputFile, targetFile, core.USELINK)
core.rmReadOnly(targetFile)
core.copy_link(inputFile, target_file, core.USELINK)
core.rmReadOnly(target_file)
except:
logger.error("Failed to link: {0} to {1}".format(inputFile, targetFile))
logger.error("Failed to link: {0} to {1}".format(inputFile, target_file))
inputName, outputDestination = convert_to_ascii(inputName, outputDestination)
input_name, output_destination = convert_to_ascii(input_name, output_destination)
if extract == 1:
logger.debug('Checking for archives to extract in directory: {0}'.format(inputDirectory))
core.extractFiles(inputDirectory, outputDestination, keep_archive)
logger.debug('Checking for archives to extract in directory: {0}'.format(input_directory))
core.extractFiles(input_directory, output_destination, keep_archive)
if inputCategory not in core.NOFLATTEN:
if input_category not in core.NOFLATTEN:
# don't flatten hp in case multi cd albums, and we need to copy this back later.
core.flatten(outputDestination)
core.flatten(output_destination)
# Now check if video files exist in destination:
if sectionName in ["SickBeard", "NzbDrone", "Sonarr", "CouchPotato", "Radarr"]:
numVideos = len(
core.listMediaFiles(outputDestination, media=True, audio=False, meta=False, archives=False))
if numVideos > 0:
logger.info("Found {0} media files in {1}".format(numVideos, outputDestination))
if section_name in ["SickBeard", "NzbDrone", "Sonarr", "CouchPotato", "Radarr"]:
num_videos = len(
core.listMediaFiles(output_destination, media=True, audio=False, meta=False, archives=False))
if num_videos > 0:
logger.info("Found {0} media files in {1}".format(num_videos, output_destination))
status = 0
elif extract != 1:
logger.info("Found no media files in {0}. Sending to {1} to process".format(outputDestination, sectionName))
logger.info("Found no media files in {0}. Sending to {1} to process".format(output_destination, section_name))
status = 0
else:
logger.warning("Found no media files in {0}".format(outputDestination))
logger.warning("Found no media files in {0}".format(output_destination))
# Only these sections can handling failed downloads
# so make sure everything else gets through without the check for failed
if sectionName not in ['CouchPotato', 'Radarr', 'SickBeard', 'NzbDrone', 'Sonarr']:
if section_name not in ['CouchPotato', 'Radarr', 'SickBeard', 'NzbDrone', 'Sonarr']:
status = 0
logger.info("Calling {0}:{1} to post-process:{2}".format(sectionName, usercat, inputName))
logger.info("Calling {0}:{1} to post-process:{2}".format(section_name, usercat, input_name))
if core.TORRENT_CHMOD_DIRECTORY:
core.rchmod(outputDestination, core.TORRENT_CHMOD_DIRECTORY)
core.rchmod(output_destination, core.TORRENT_CHMOD_DIRECTORY)
result = [0, ""]
if sectionName == 'UserScript':
result = external_script(outputDestination, inputName, inputCategory, section)
if section_name == 'UserScript':
result = external_script(output_destination, input_name, input_category, section)
elif sectionName in ['CouchPotato', 'Radarr']:
result = core.autoProcessMovie().process(sectionName, outputDestination, inputName,
status, clientAgent, inputHash, inputCategory)
elif sectionName in ['SickBeard', 'NzbDrone', 'Sonarr']:
if inputHash:
inputHash = inputHash.upper()
result = core.autoProcessTV().processEpisode(sectionName, outputDestination, inputName,
status, clientAgent, inputHash, inputCategory)
elif sectionName in ['HeadPhones', 'Lidarr']:
result = core.autoProcessMusic().process(sectionName, outputDestination, inputName,
status, clientAgent, inputCategory)
elif sectionName == 'Mylar':
result = core.autoProcessComics().processEpisode(sectionName, outputDestination, inputName,
status, clientAgent, inputCategory)
elif sectionName == 'Gamez':
result = core.autoProcessGames().process(sectionName, outputDestination, inputName,
status, clientAgent, inputCategory)
elif section_name in ['CouchPotato', 'Radarr']:
result = core.autoProcessMovie().process(section_name, output_destination, input_name,
status, clientAgent, input_hash, input_category)
elif section_name in ['SickBeard', 'NzbDrone', 'Sonarr']:
if input_hash:
input_hash = input_hash.upper()
result = core.autoProcessTV().processEpisode(section_name, output_destination, input_name,
status, clientAgent, input_hash, input_category)
elif section_name in ['HeadPhones', 'Lidarr']:
result = core.autoProcessMusic().process(section_name, output_destination, input_name,
status, clientAgent, input_category)
elif section_name == 'Mylar':
result = core.autoProcessComics().processEpisode(section_name, output_destination, input_name,
status, clientAgent, input_category)
elif section_name == 'Gamez':
result = core.autoProcessGames().process(section_name, output_destination, input_name,
status, clientAgent, input_category)
plex_update(inputCategory)
plex_update(input_category)
if result[0] != 0:
if not core.TORRENT_RESUME_ON_FAILURE:
@ -258,26 +262,26 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID,
elif clientAgent != 'manual':
logger.error("A problem was reported in the autoProcess* script. "
"If torrent was paused we will resume seeding")
core.resume_torrent(clientAgent, inputHash, inputID, inputName)
core.resume_torrent(clientAgent, input_hash, inputID, input_name)
else:
if clientAgent != 'manual':
# update download status in our DB
core.update_downloadInfoStatus(inputName, 1)
core.update_downloadInfoStatus(input_name, 1)
# remove torrent
if core.USELINK == 'move-sym' and not core.DELETE_ORIGINAL == 1:
logger.debug('Checking for sym-links to re-direct in: {0}'.format(inputDirectory))
for dirpath, dirs, files in os.walk(inputDirectory):
logger.debug('Checking for sym-links to re-direct in: {0}'.format(input_directory))
for dirpath, dirs, files in os.walk(input_directory):
for file in files:
logger.debug('Checking symlink: {0}'.format(os.path.join(dirpath, file)))
replace_links(os.path.join(dirpath, file))
core.remove_torrent(clientAgent, inputHash, inputID, inputName)
core.remove_torrent(clientAgent, input_hash, inputID, input_name)
if not sectionName == 'UserScript':
if not section_name == 'UserScript':
# for user script, we assume this is cleaned by the script or option USER_SCRIPT_CLEAN
# cleanup our processing folders of any misc unwanted files and empty directories
core.cleanDir(outputDestination, sectionName, inputCategory)
core.cleanDir(output_destination, section_name, input_category)
return result
@ -287,7 +291,7 @@ def main(args):
core.initialize()
# clientAgent for Torrents
clientAgent = core.TORRENT_CLIENTAGENT
client_agent = core.TORRENT_CLIENTAGENT
logger.info("#########################################################")
logger.info("## ..::[{0}]::.. ##".format(os.path.basename(__file__)))
@ -300,13 +304,13 @@ def main(args):
result = [0, ""]
try:
inputDirectory, inputName, inputCategory, inputHash, inputID = core.parse_args(clientAgent, args)
input_directory, input_name, input_category, input_hash, input_id = core.parse_args(client_agent, args)
except:
logger.error("There was a problem loading variables")
return -1
if inputDirectory and inputName and inputHash and inputID:
result = processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, clientAgent)
if input_directory and input_name and input_hash and input_id:
result = processTorrent(input_directory, input_name, input_category, input_hash, input_id, client_agent)
else:
# Perform Manual Post-Processing
logger.warning("Invalid number of arguments received from client, Switching to manual run mode ...")
@ -315,42 +319,42 @@ def main(args):
for subsection in subsections:
if not core.CFG[section][subsection].isenabled():
continue
for dirName in core.getDirs(section, subsection, link='hard'):
for dir_name in core.getDirs(section, subsection, link='hard'):
logger.info("Starting manual run for {0}:{1} - Folder:{2}".format
(section, subsection, dirName))
(section, subsection, dir_name))
logger.info("Checking database for download info for {0} ...".format
(os.path.basename(dirName)))
core.DOWNLOADINFO = core.get_downloadInfo(os.path.basename(dirName), 0)
(os.path.basename(dir_name)))
core.DOWNLOADINFO = core.get_downloadInfo(os.path.basename(dir_name), 0)
if core.DOWNLOADINFO:
clientAgent = text_type(core.DOWNLOADINFO[0].get('client_agent', 'manual'))
inputHash = text_type(core.DOWNLOADINFO[0].get('input_hash', ''))
inputID = text_type(core.DOWNLOADINFO[0].get('input_id', ''))
client_agent = text_type(core.DOWNLOADINFO[0].get('client_agent', 'manual'))
input_hash = text_type(core.DOWNLOADINFO[0].get('input_hash', ''))
input_id = text_type(core.DOWNLOADINFO[0].get('input_id', ''))
logger.info("Found download info for {0}, "
"setting variables now ...".format(os.path.basename(dirName)))
"setting variables now ...".format(os.path.basename(dir_name)))
else:
logger.info('Unable to locate download info for {0}, '
'continuing to try and process this release ...'.format
(os.path.basename(dirName)))
clientAgent = 'manual'
inputHash = ''
inputID = ''
(os.path.basename(dir_name)))
client_agent = 'manual'
input_hash = ''
input_id = ''
if clientAgent.lower() not in core.TORRENT_CLIENTS:
if client_agent.lower() not in core.TORRENT_CLIENTS:
continue
try:
dirName = dirName.encode(core.SYS_ENCODING)
dir_name = dir_name.encode(core.SYS_ENCODING)
except UnicodeError:
pass
inputName = os.path.basename(dirName)
input_name = os.path.basename(dir_name)
try:
inputName = inputName.encode(core.SYS_ENCODING)
input_name = input_name.encode(core.SYS_ENCODING)
except UnicodeError:
pass
results = processTorrent(dirName, inputName, subsection, inputHash or None, inputID or None,
clientAgent)
results = processTorrent(dir_name, input_name, subsection, input_hash or None, input_id or None,
client_agent)
if results[0] != 0:
logger.error("A problem was reported when trying to perform a manual run for {0}:{1}.".format
(section, subsection))