From 1a3b1ce4b6548f3e27f9e28d19768525bcad425e Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:12:02 -0400 Subject: [PATCH 01/10] Add encoding declaration --- TorrentToMedia.py | 1 + nzbToCouchPotato.py | 1 + nzbToGamez.py | 1 + nzbToHeadPhones.py | 1 + nzbToMedia.py | 1 + nzbToMylar.py | 1 + nzbToNzbDrone.py | 1 + nzbToSickBeard.py | 1 + 8 files changed, 8 insertions(+) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index b1a317ae..9d19b945 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 import datetime import os import time diff --git a/nzbToCouchPotato.py b/nzbToCouchPotato.py index c9957d4c..9bb81473 100755 --- a/nzbToCouchPotato.py +++ b/nzbToCouchPotato.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToGamez.py b/nzbToGamez.py index d85c2961..b6bca420 100755 --- a/nzbToGamez.py +++ b/nzbToGamez.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToHeadPhones.py b/nzbToHeadPhones.py index 9f24faf4..30be1dcc 100755 --- a/nzbToHeadPhones.py +++ b/nzbToHeadPhones.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToMedia.py b/nzbToMedia.py index c599e217..d4c819b2 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToMylar.py b/nzbToMylar.py index 21d7e183..71f88bab 100755 --- a/nzbToMylar.py +++ b/nzbToMylar.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToNzbDrone.py b/nzbToNzbDrone.py index 8d4f3a49..63c64864 100755 --- a/nzbToNzbDrone.py +++ b/nzbToNzbDrone.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### diff --git a/nzbToSickBeard.py b/nzbToSickBeard.py index 69ff5397..73fefbfe 100755 --- a/nzbToSickBeard.py +++ b/nzbToSickBeard.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2 +# coding=utf-8 # ############################################################################## ### NZBGET POST-PROCESSING SCRIPT ### From 58d439f3eb75397c576b35adf4e16436cb43ded0 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:11:38 -0400 Subject: [PATCH 02/10] Remove unused imports, variables, and redundant parentheses --- TorrentToMedia.py | 3 --- nzbToMedia.py | 10 +++------- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 9d19b945..20b78771 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -2,12 +2,9 @@ # coding=utf-8 import datetime import os -import time -import shutil import sys import core -from subprocess import Popen from core import logger, nzbToMediaDB from core.nzbToMediaUtil import convert_to_ascii, CharReplace, plex_update from core.nzbToMediaUserScript import external_script diff --git a/nzbToMedia.py b/nzbToMedia.py index d4c819b2..833215b4 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -527,7 +527,6 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down myDB = nzbToMediaDB.DBConnection() - encoded = False inputDirectory1 = inputDirectory inputName1 = inputName @@ -633,9 +632,6 @@ def main(args, section=None): # Initialize the config core.initialize(section) - # clientAgent for NZBs - clientAgent = core.NZB_CLIENTAGENT - logger.info("#########################################################") logger.info("## ..::[{0}]::.. ##".format(os.path.basename(__file__))) logger.info("#########################################################") @@ -792,16 +788,16 @@ def main(args, section=None): 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) + return core.NZBGET_POSTPROCESS_SUCCESS else: logger.error("A problem was reported in the {0} script.".format(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) + return core.NZBGET_POSTPROCESS_ERROR del core.MYAPP - return (result[0]) + return result[0] if __name__ == '__main__': From c2bf14f775aedbe486e74c5f53e87d3c06e89f25 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:25:06 -0400 Subject: [PATCH 03/10] PEP8: Fix formatting * Remove redundant backslash between brackets * Fix multiple statements on one line * Fix missing/excess whitespace * Fix comments not starting with a single # and a space --- TorrentToMedia.py | 59 +++++---- nzbToCouchPotato.py | 151 +++++++++++------------ nzbToGamez.py | 57 ++++----- nzbToHeadPhones.py | 65 +++++----- nzbToMedia.py | 291 ++++++++++++++++++++++---------------------- nzbToMylar.py | 67 +++++----- nzbToNzbDrone.py | 141 ++++++++++----------- nzbToSickBeard.py | 153 +++++++++++------------ 8 files changed, 501 insertions(+), 483 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 20b78771..b3f4e719 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -9,6 +9,7 @@ from core import logger, nzbToMediaDB from core.nzbToMediaUtil import convert_to_ascii, CharReplace, plex_update from core.nzbToMediaUserScript import external_script + def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, clientAgent): status = 1 # 1 = failed | 0 = success root = 0 @@ -37,24 +38,26 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, "client_agent": unicode(clientAgent), "status": 0, "last_update": datetime.date.today().toordinal() - } + } myDB.upsert("downloads", newValueDict, controlValueDict) logger.debug("Received Directory: {0} | Name: {1} | Category: {2}".format(inputDirectory, inputName, inputCategory)) inputDirectory, inputName, inputCategory, root = core.category_search(inputDirectory, inputName, - inputCategory, root, - core.CATEGORIES) # Confirm the category by parsing directory structure + inputCategory, root, + core.CATEGORIES) # Confirm the category by parsing directory structure if inputCategory == "": inputCategory = "UNCAT" usercat = inputCategory try: inputName = inputName.encode(core.SYS_ENCODING) - except: pass + except: + pass try: inputDirectory = inputDirectory.encode(core.SYS_ENCODING) - except: pass + except: + pass logger.debug("Determined Directory: {0} | Name: {1} | Category: {2}".format(inputDirectory, inputName, inputCategory)) @@ -122,7 +125,8 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, core.os.path.join(core.OUTPUTDIRECTORY, inputCategory)) try: outputDestination = outputDestination.encode(core.SYS_ENCODING) - except: pass + except: + pass if outputDestination in inputDirectory: outputDestination = inputDirectory @@ -132,7 +136,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, if core.SAFE_MODE and outputDestination == core.TORRENT_DEFAULTDIR: logger.error( 'The output directory:[{0}] is the Download Directory. Edit outputDirectory in autoProcessMedia.cfg. Exiting'.format( - inputDirectory)) + inputDirectory)) return [-1, ""] logger.debug("Scanning files in directory: {0}".format(inputDirectory)) @@ -162,12 +166,13 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, "Setting outputDestination to {0} to preserve folder structure".format(os.path.dirname(targetFile))) try: targetFile = targetFile.encode(core.SYS_ENCODING) - except: pass + except: + pass if root == 1: if not foundFile: logger.debug("Looking for {0} in: {1}".format(inputName, inputFile)) - if (core.sanitizeName(inputName) in core.sanitizeName(inputFile)) or ( - core.sanitizeName(fileName) in core.sanitizeName(inputName)): + if any([core.sanitizeName(inputName) in core.sanitizeName(inputFile), + core.sanitizeName(fileName) in core.sanitizeName(inputName)]): foundFile = True logger.debug("Found file {0} that matches Torrent Name {1}".format(fullFileName, inputName)) else: @@ -198,7 +203,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, logger.debug('Checking for archives to extract in directory: {0}'.format(inputDirectory)) core.extractFiles(inputDirectory, outputDestination, keep_archive) - if not inputCategory in core.NOFLATTEN: #don't flatten hp in case multi cd albums, and we need to copy this back later. + if not inputCategory in core.NOFLATTEN: # don't flatten hp in case multi cd albums, and we need to copy this back later. core.flatten(outputDestination) # Now check if video files exist in destination: @@ -223,25 +228,25 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, if core.TORRENT_CHMOD_DIRECTORY: core.rchmod(outputDestination, core.TORRENT_CHMOD_DIRECTORY) - result = [ 0, "" ] + result = [0, ""] if sectionName == 'UserScript': result = external_script(outputDestination, inputName, inputCategory, section[usercat]) elif sectionName == 'CouchPotato': - result = core.autoProcessMovie().process(sectionName,outputDestination, inputName, status, clientAgent, inputHash, - inputCategory) - elif sectionName in ['SickBeard','NzbDrone']: + result = core.autoProcessMovie().process(sectionName, outputDestination, inputName, status, clientAgent, inputHash, + inputCategory) + elif sectionName in ['SickBeard', 'NzbDrone']: if inputHash: inputHash = inputHash.upper() - result = core.autoProcessTV().processEpisode(sectionName,outputDestination, inputName, status, clientAgent, - inputHash, inputCategory) + result = core.autoProcessTV().processEpisode(sectionName, outputDestination, inputName, status, clientAgent, + inputHash, inputCategory) elif sectionName == 'HeadPhones': - result = core.autoProcessMusic().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory) + result = core.autoProcessMusic().process(sectionName, outputDestination, inputName, status, clientAgent, inputCategory) elif sectionName == 'Mylar': - result = core.autoProcessComics().processEpisode(sectionName,outputDestination, inputName, status, clientAgent, - inputCategory) + result = core.autoProcessComics().processEpisode(sectionName, outputDestination, inputName, status, clientAgent, + inputCategory) elif sectionName == 'Gamez': - result = core.autoProcessGames().process(sectionName,outputDestination, inputName, status, clientAgent, inputCategory) + result = core.autoProcessGames().process(sectionName, outputDestination, inputName, status, clientAgent, inputCategory) plex_update(inputCategory) @@ -263,8 +268,8 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, logger.debug('Checking for sym-links to re-direct in: {0}'.format(inputDirectory)) for dirpath, dirs, files in os.walk(inputDirectory): for file in files: - logger.debug('Checking symlink: {0}'.format(os.path.join(dirpath,file))) - core.replace_links(os.path.join(dirpath,file)) + logger.debug('Checking symlink: {0}'.format(os.path.join(dirpath, file))) + core.replace_links(os.path.join(dirpath, file)) core.remove_torrent(clientAgent, inputHash, inputID, inputName) if not sectionName == 'UserScript': # for user script, we assume this is cleaned by the script or option USER_SCRIPT_CLEAN @@ -289,7 +294,7 @@ def main(args): logger.debug("Options passed into TorrentToMedia: {0}".format(args)) # Post-Processing Result - result = [ 0, "" ] + result = [0, ""] try: inputDirectory, inputName, inputCategory, inputHash, inputID = core.parse_args(clientAgent, args) @@ -339,11 +344,13 @@ def main(args): try: dirName = dirName.encode(core.SYS_ENCODING) - except: pass + except: + pass inputName = os.path.basename(dirName) try: inputName = inputName.encode(core.SYS_ENCODING) - except: pass + except: + pass results = processTorrent(dirName, inputName, subsection, inputHash, inputID, clientAgent) diff --git a/nzbToCouchPotato.py b/nzbToCouchPotato.py index 9bb81473..8b8f7b46 100755 --- a/nzbToCouchPotato.py +++ b/nzbToCouchPotato.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 -# -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### + +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to CouchPotato, SickBeard, NzbDrone, Mylar, Gamez, HeadPhones. # @@ -10,242 +10,243 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## -### OPTIONS ### +# ############################################################################## +# ### OPTIONS ### -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Check Media for corruption (0, 1). # # Enable/Disable media file checking using ffprobe. -#check_media=1 +# check_media=1 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## CouchPotato +# ## CouchPotato # CouchPotato script category. # # category that gets called for post-processing with CouchPotatoServer. -#cpsCategory=movie +# cpsCategory=movie # CouchPotato api key. -#cpsapikey= +# cpsapikey= # CouchPotato host. # # The ipaddress for your CouchPotato server. e.g For the Same system use localhost or 127.0.0.1 -#cpshost=localhost +# cpshost=localhost # CouchPotato port. -#cpsport=5050 +# cpsport=5050 # CouchPotato uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#cpsssl=0 +# cpsssl=0 # CouchPotato URL_Base # # set this if using a reverse proxy. -#cpsweb_root= +# cpsweb_root= # CouchPotato watch directory. # # set this to where your CouchPotato completed downloads are. -#cpswatch_dir= +# cpswatch_dir= # CouchPotato Postprocess Method (renamer, manage). # # use "renamer" for CPS renamer (default) or "manage" to call a manage update. -#cpsmethod=renamer +# cpsmethod=renamer # CouchPotato Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#cpsdelete_failed=0 +# cpsdelete_failed=0 # CouchPotato wait_for # # Set the number of minutes to wait after calling the renamer, to check the movie has changed status. -#cpswait_for=2 +# cpswait_for=2 # CouchPotatoServer and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#cpsremote_path=0 +# cpsremote_path=0 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## Extensions +# ## Extensions # Media Extensions # # This is a list of media extensions that are used to verify that the download does contain valid media. -#mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts +# mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Transcoder +# ## Transcoder # getSubs (0, 1). # # set to 1 to download subtitles. -#getSubs=0 +# getSubs=0 # subLanguages. # # subLanguages. create a list of languages in the order you want them in your subtitles. -#subLanguages=eng,spa,fra +# subLanguages=eng,spa,fra # Transcode (0, 1). # # set to 1 to transcode, otherwise set to 0. -#transcode=0 +# transcode=0 # create a duplicate, or replace the original (0, 1). # # set to 1 to cretae a new file or 0 to replace the original -#duplicate=1 +# duplicate=1 # ignore extensions. # # list of extensions that won't be transcoded. -#ignoreExtensions=.avi,.mkv +# ignoreExtensions=.avi,.mkv # outputFastStart (0,1). # # outputFastStart. 1 will use -movflags + faststart. 0 will disable this from being used. -#outputFastStart=0 +# outputFastStart=0 # outputVideoPath. # # outputVideoPath. Set path you want transcoded videos moved to. Leave blank to disable. -#outputVideoPath= +# outputVideoPath= # processOutput (0,1). # # processOutput. 1 will send the outputVideoPath to SickBeard/CouchPotato. 0 will send original files. -#processOutput=0 +# processOutput=0 # audioLanguage. # # audioLanguage. set the 3 letter language code you want as your primary audio track. -#audioLanguage=eng +# audioLanguage=eng # allAudioLanguages (0,1). # # allAudioLanguages. 1 will keep all audio tracks (uses AudioCodec3) where available. -#allAudioLanguages=0 +# allAudioLanguages=0 # allSubLanguages (0,1). # # allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. -#allSubLanguages=0 +# allSubLanguages=0 # embedSubs (0,1). # # embedSubs. 1 will embded external sub/srt subs into your video if this is supported. -#embedSubs=1 +# embedSubs=1 # burnInSubtitle (0,1). # # burnInSubtitle. burns the default sub language into your video (needed for players that don't support subs) -#burnInSubtitle=0 +# burnInSubtitle=0 # extractSubs (0,1). # # extractSubs. 1 will extract subs from the video file and save these as external srt files. -#extractSubs=0 +# extractSubs=0 # externalSubDir. # # externalSubDir. set the directory where subs should be saved (if not the same directory as the video) -#externalSubDir= +# externalSubDir= # outputDefault (None, iPad, iPad-1080p, iPad-720p, Apple-TV2, iPod, iPhone, PS3, xbox, Roku-1080p, Roku-720p, Roku-480p, mkv, mp4-scene-release). # # outputDefault. Loads default configs for the selected device. The remaining options below are ignored. # If you want to use your own profile, set None and set the remaining options below. -#outputDefault=None +# outputDefault=None # hwAccel (0,1). # # hwAccel. 1 will set ffmpeg to enable hardware acceleration (this requires a recent ffmpeg). -#hwAccel=0 +# hwAccel=0 # ffmpeg output settings. -#outputVideoExtension=.mp4 -#outputVideoCodec=libx264 -#VideoCodecAllow= -#outputVideoPreset=medium -#outputVideoFramerate=24 -#outputVideoBitrate=800k -#outputAudioCodec=ac3 -#AudioCodecAllow= -#outputAudioChannels=6 -#outputAudioBitrate=640k -#outputQualityPercent= -#outputAudioTrack2Codec=libfaac -#AudioCodec2Allow= -#outputAudioTrack2Channels=2 -#outputAudioTrack2Bitrate=160k -#outputAudioOtherCodec=libmp3lame -#AudioOtherCodecAllow= -#outputAudioOtherChannels=2 -#outputAudioOtherBitrate=128k -#outputSubtitleCodec= +# outputVideoExtension=.mp4 +# outputVideoCodec=libx264 +# VideoCodecAllow= +# outputVideoPreset=medium +# outputVideoFramerate=24 +# outputVideoBitrate=800k +# outputAudioCodec=ac3 +# AudioCodecAllow= +# outputAudioChannels=6 +# outputAudioBitrate=640k +# outputQualityPercent= +# outputAudioTrack2Codec=libfaac +# AudioCodec2Allow= +# outputAudioTrack2Channels=2 +# outputAudioTrack2Bitrate=160k +# outputAudioOtherCodec=libmp3lame +# AudioOtherCodecAllow= +# outputAudioOtherChannels=2 +# outputAudioOtherBitrate=128k +# outputSubtitleCodec= -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "CouchPotato" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) diff --git a/nzbToGamez.py b/nzbToGamez.py index b6bca420..9b1cb355 100755 --- a/nzbToGamez.py +++ b/nzbToGamez.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 # -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to CouchPotato, SickBeard, NzbDrone, Mylar, Gamez, HeadPhones. # @@ -10,98 +10,99 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## +# ############################################################################## # -### OPTIONS ### +# ### OPTIONS ### -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## Gamez +# ## Gamez # Gamez script category. # # category that gets called for post-processing with Gamez. -#gzCategory=games +# gzCategory=games # Gamez api key. -#gzapikey= +# gzapikey= # Gamez host. # # The ipaddress for your Gamez server. e.g For the Same system use localhost or 127.0.0.1 -#gzhost=localhost +# gzhost=localhost # Gamez port. -#gzport=8085 +# gzport=8085 # Gamez uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#gzssl=0 +# gzssl=0 # Gamez library # # move downloaded games here. -#gzlibrary +# gzlibrary # Gamez web_root # # set this if using a reverse proxy. -#gzweb_root= +# gzweb_root= # Gamez watch directory. # # set this to where your Gamez completed downloads are. -#gzwatch_dir= +# gzwatch_dir= -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "Gamez" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) diff --git a/nzbToHeadPhones.py b/nzbToHeadPhones.py index 30be1dcc..26cf2e3e 100755 --- a/nzbToHeadPhones.py +++ b/nzbToHeadPhones.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 -# -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### + +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to HeadPhones. # @@ -10,110 +10,111 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## -### OPTIONS +# ############################################################################## +# ### OPTIONS -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## HeadPhones +# ## HeadPhones # HeadPhones script category. # # category that gets called for post-processing with HeadHones. -#hpCategory=music +# hpCategory=music # HeadPhones api key. -#hpapikey= +# hpapikey= # HeadPhones host. # # The ipaddress for your HeadPhones server. e.g For the Same system use localhost or 127.0.0.1 -#hphost=localhost +# hphost=localhost # HeadPhones port. -#hpport=8181 +# hpport=8181 # HeadPhones uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#hpssl=0 +# hpssl=0 # HeadPhones web_root # # set this if using a reverse proxy. -#hpweb_root= +# hpweb_root= # HeadPhones watch directory. # # set this to where your HeadPhones completed downloads are. -#hpwatch_dir= +# hpwatch_dir= # HeadPhones wait_for # # Set the number of minutes to wait after initiating HeadPhones post-processing to check if the album status has changed. -#hpwait_for=2 +# hpwait_for=2 # HeadPhones and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#hpremote_path=0 +# hpremote_path=0 -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "HeadPhones" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) diff --git a/nzbToMedia.py b/nzbToMedia.py index 833215b4..5e344fa8 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 # -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to CouchPotato, SickBeard, NzbDrone, Mylar, Gamez, HeadPhones. # @@ -10,494 +10,495 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## -### OPTIONS ### +# ############################################################################## +# ### OPTIONS ### -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Check Media for corruption (0, 1). # # Enable/Disable media file checking using ffprobe. -#check_media=1 +# check_media=1 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## CouchPotato +# ## CouchPotato # CouchPotato script category. # # category that gets called for post-processing with CouchPotatoServer. -#cpsCategory=movie +# cpsCategory=movie # CouchPotato api key. -#cpsapikey= +# cpsapikey= # CouchPotato host. # # The ipaddress for your CouchPotato server. e.g For the Same system use localhost or 127.0.0.1 -#cpshost=localhost +# cpshost=localhost # CouchPotato port. -#cpsport=5050 +# cpsport=5050 # CouchPotato uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#cpsssl=0 +# cpsssl=0 # CouchPotato URL_Base # # set this if using a reverse proxy. -#cpsweb_root= +# cpsweb_root= # CouchPotato Postprocess Method (renamer, manage). # # use "renamer" for CPS renamer (default) or "manage" to call a manage update. -#cpsmethod=renamer +# cpsmethod=renamer # CouchPotato Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#cpsdelete_failed=0 +# cpsdelete_failed=0 # CouchPotato wait_for # # Set the number of minutes to wait after calling the renamer, to check the movie has changed status. -#cpswait_for=2 +# cpswait_for=2 # Couchpotato and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#cpsremote_path=0 +# cpsremote_path=0 -## SickBeard +# ## SickBeard # SickBeard script category. # # category that gets called for post-processing with SickBeard. -#sbCategory=tv +# sbCategory=tv # SickBeard host. # # The ipaddress for your SickBeard/SickRage server. e.g For the Same system use localhost or 127.0.0.1 -#sbhost=localhost +# sbhost=localhost # SickBeard port. -#sbport=8081 +# sbport=8081 # SickBeard username. -#sbusername= +# sbusername= # SickBeard password. -#sbpassword= +# sbpassword= # SickBeard uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#sbssl=0 +# sbssl=0 # SickBeard web_root # # set this if using a reverse proxy. -#sbweb_root= +# sbweb_root= # SickBeard watch directory. # # set this if SickBeard and nzbGet are on different systems. -#sbwatch_dir= +# sbwatch_dir= # SickBeard fork. # # set to default or auto to auto-detect the custom fork type. -#sbfork=auto +# sbfork=auto # SickBeard Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#sbdelete_failed=0 +# sbdelete_failed=0 # SickBeard process method. # # set this to move, copy, hardlink, symlink as appropriate if you want to over-ride SB defaults. Leave blank to use SB default. -#sbprocess_method= +# sbprocess_method= # SickBeard and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#sbremote_path=0 +# sbremote_path=0 -## NzbDrone +# ## NzbDrone # NzbDrone script category. # # category that gets called for post-processing with NzbDrone. -#ndCategory=tv2 +# ndCategory=tv2 # NzbDrone host. # # The ipaddress for your NzbDrone/Sonarr server. e.g For the Same system use localhost or 127.0.0.1 -#ndhost=localhost +# ndhost=localhost # NzbDrone port. -#ndport=8989 +# ndport=8989 # NzbDrone API key. -#ndapikey= +# ndapikey= # NzbDrone uses SSL (0, 1). # # Set to 1 if using SSL, else set to 0. -#ndssl=0 +# ndssl=0 # NzbDrone web root. # # set this if using a reverse proxy. -#ndweb_root= +# ndweb_root= # NzbDrone wait_for # # Set the number of minutes to wait after calling the renamer, to check the episode has changed status. -#ndwait_for=2 +# ndwait_for=2 # NzbDrone Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#nddelete_failed=0 +# nddelete_failed=0 # NzbDrone and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#ndremote_path=0 +# ndremote_path=0 -## HeadPhones +# ## HeadPhones # HeadPhones script category. # # category that gets called for post-processing with HeadHones. -#hpCategory=music +# hpCategory=music # HeadPhones api key. -#hpapikey= +# hpapikey= # HeadPhones host. # # The ipaddress for your HeadPhones server. e.g For the Same system use localhost or 127.0.0.1 -#hphost=localhost +# hphost=localhost # HeadPhones port. -#hpport=8181 +# hpport=8181 # HeadPhones uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#hpssl=0 +# hpssl=0 # HeadPhones web_root # # set this if using a reverse proxy. -#hpweb_root= +# hpweb_root= # HeadPhones and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#hpremote_path=0 +# hpremote_path=0 -## Mylar +# ## Mylar # Mylar script category. # # category that gets called for post-processing with Mylar. -#myCategory=comics +# myCategory=comics # Mylar host. # # The ipaddress for your Mylar server. e.g For the Same system use localhost or 127.0.0.1 -#myhost=localhost +# myhost=localhost # Mylar port. -#myport=8090 +# myport=8090 # Mylar username. -#myusername= +# myusername= # Mylar password. -#mypassword= +# mypassword= # Mylar uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#myssl=0 +# myssl=0 # Mylar web_root # # set this if using a reverse proxy. -#myweb_root= +# myweb_root= # Mylar wait_for # # Set the number of minutes to wait after calling the force process, to check the issue has changed status. -#myswait_for=1 +# myswait_for=1 # Mylar and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#myremote_path=0 +# myremote_path=0 -## Gamez +# ## Gamez # Gamez script category. # # category that gets called for post-processing with Gamez. -#gzCategory=games +# gzCategory=games # Gamez api key. -#gzapikey= +# gzapikey= # Gamez host. # # The ipaddress for your Gamez server. e.g For the Same system use localhost or 127.0.0.1 -#gzhost=localhost +# gzhost=localhost # Gamez port. -#gzport=8085 +# gzport=8085 # Gamez uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#gzssl=0 +# gzssl=0 # Gamez library # # move downloaded games here. -#gzlibrary +# gzlibrary # Gamez web_root # # set this if using a reverse proxy. -#gzweb_root= +# gzweb_root= # Gamez and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#gzremote_path=0 +# gzremote_path=0 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## Extensions +# ## Extensions # Media Extensions # # This is a list of media extensions that are used to verify that the download does contain valid media. -#mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts +# mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Transcoder +# ## Transcoder # getSubs (0, 1). # # set to 1 to download subtitles. -#getSubs=0 +# getSubs=0 # subLanguages. # # subLanguages. create a list of languages in the order you want them in your subtitles. -#subLanguages=eng,spa,fra +# subLanguages=eng,spa,fra # Transcode (0, 1). # # set to 1 to transcode, otherwise set to 0. -#transcode=0 +# transcode=0 # create a duplicate, or replace the original (0, 1). # # set to 1 to cretae a new file or 0 to replace the original -#duplicate=1 +# duplicate=1 # ignore extensions. # # list of extensions that won't be transcoded. -#ignoreExtensions=.avi,.mkv +# ignoreExtensions=.avi,.mkv # outputFastStart (0,1). # # outputFastStart. 1 will use -movflags + faststart. 0 will disable this from being used. -#outputFastStart=0 +# outputFastStart=0 # outputVideoPath. # # outputVideoPath. Set path you want transcoded videos moved to. Leave blank to disable. -#outputVideoPath= +# outputVideoPath= # processOutput (0,1). # # processOutput. 1 will send the outputVideoPath to SickBeard/CouchPotato. 0 will send original files. -#processOutput=0 +# processOutput=0 # audioLanguage. # # audioLanguage. set the 3 letter language code you want as your primary audio track. -#audioLanguage=eng +# audioLanguage=eng # allAudioLanguages (0,1). # # allAudioLanguages. 1 will keep all audio tracks (uses AudioCodec3) where available. -#allAudioLanguages=0 +# allAudioLanguages=0 # allSubLanguages (0,1). # # allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. -#allSubLanguages=0 +# allSubLanguages=0 # embedSubs (0,1). # # embedSubs. 1 will embded external sub/srt subs into your video if this is supported. -#embedSubs=1 +# embedSubs=1 # burnInSubtitle (0,1). # # burnInSubtitle. burns the default sub language into your video (needed for players that don't support subs) -#burnInSubtitle=0 +# burnInSubtitle=0 # extractSubs (0,1). # # extractSubs. 1 will extract subs from the video file and save these as external srt files. -#extractSubs=0 +# extractSubs=0 # externalSubDir. # # externalSubDir. set the directory where subs should be saved (if not the same directory as the video) -#externalSubDir= +# externalSubDir= # outputDefault (None, iPad, iPad-1080p, iPad-720p, Apple-TV2, iPod, iPhone, PS3, xbox, Roku-1080p, Roku-720p, Roku-480p, mkv, mp4-scene-release). # # outputDefault. Loads default configs for the selected device. The remaining options below are ignored. # If you want to use your own profile, set None and set the remaining options below. -#outputDefault=None +# outputDefault=None # hwAccel (0,1). # # hwAccel. 1 will set ffmpeg to enable hardware acceleration (this requires a recent ffmpeg). -#hwAccel=0 +# hwAccel=0 # ffmpeg output settings. -#outputVideoExtension=.mp4 -#outputVideoCodec=libx264 -#VideoCodecAllow= -#outputVideoPreset=medium -#outputVideoFramerate=24 -#outputVideoBitrate=800k -#outputAudioCodec=ac3 -#AudioCodecAllow= -#outputAudioChannels=6 -#outputAudioBitrate=640k -#outputQualityPercent= -#outputAudioTrack2Codec=libfaac -#AudioCodec2Allow= -#outputAudioTrack2Channels=2 -#outputAudioTrack2Bitrate=160k -#outputAudioOtherCodec=libmp3lame -#AudioOtherCodecAllow= -#outputAudioOtherChannels=2 -#outputAudioOtherBitrate=128k -#outputSubtitleCodec= +# outputVideoExtension=.mp4 +# outputVideoCodec=libx264 +# VideoCodecAllow= +# outputVideoPreset=medium +# outputVideoFramerate=24 +# outputVideoBitrate=800k +# outputAudioCodec=ac3 +# AudioCodecAllow= +# outputAudioChannels=6 +# outputAudioBitrate=640k +# outputQualityPercent= +# outputAudioTrack2Codec=libfaac +# AudioCodec2Allow= +# outputAudioTrack2Channels=2 +# outputAudioTrack2Bitrate=160k +# outputAudioOtherCodec=libmp3lame +# AudioOtherCodecAllow= +# outputAudioOtherChannels=2 +# outputAudioOtherBitrate=128k +# outputSubtitleCodec= -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 -## UserScript +# ## UserScript # User Script category. # # category that gets called for post-processing with user script (accepts "UNCAT", "ALL", or a defined category). -#usCategory=mine +# usCategory=mine # User Script Remote Path (0,1). # # Script calls commands on another system. -#usremote_path=0 +# usremote_path=0 # User Script extensions. # # What extension do you want to process? Specify all the extension, or use "ALL" to process all files. -#user_script_mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg +# user_script_mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg # User Script Path # # Specify the path to your custom script. -#user_script_path=/nzbToMedia/userscripts/script.sh +# user_script_path=/nzbToMedia/userscripts/script.sh # User Script arguments. # # Specify the argument(s) passed to script, comma separated in order. # for example FP,FN,DN, TN, TL for file path (absolute file name with path), file name, absolute directory name (with path), Torrent Name, Torrent Label/Category. # So the result is /media/test/script/script.sh FP FN DN TN TL. Add other arguments as needed eg -f, -r -#user_script_param=FN +# user_script_param=FN # User Script Run Once (0,1). # # Set user_script_runOnce = 0 to run for each file, or 1 to only run once (presumably on teh entire directory). -#user_script_runOnce=0 +# user_script_runOnce=0 # User Script Success Codes. # # Specify the successcodes returned by the user script as a comma separated list. Linux default is 0 -#user_script_successCodes=0 +# user_script_successCodes=0 # User Script Clean After (0,1). # # Clean after? Note that delay function is used to prevent possible mistake :) Delay is intended as seconds -#user_script_clean=1 +# user_script_clean=1 # User Script Delay. # # Delay in seconds after processing. -#usdelay=120 +# usdelay=120 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import os import sys import datetime @@ -510,17 +511,19 @@ 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 +from six import text_type + # 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:[{0}] is the Default Download Directory. Please configure category directories to prevent processing of other media.'.format( - inputDirectory)) + inputDirectory)) return [-1, ""] if not download_id and clientAgent == 'sabnzbd': - download_id = get_nzoid(inputName) + download_id = get_nzoid(inputName) if clientAgent != 'manual' and not core.DOWNLOADINFO: logger.debug('Adding NZB download info for directory {0} to database'.format(inputDirectory)) @@ -543,7 +546,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down "client_agent": unicode(clientAgent), "status": 0, "last_update": datetime.date.today().toordinal() - } + } myDB.upsert("downloads", newValueDict, controlValueDict) # auto-detect section @@ -556,7 +559,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down 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)) + inputCategory)) return [-1, ""] else: usercat = "ALL" @@ -564,7 +567,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down if len(section) > 1: logger.error( 'Category:[{0}] is not unique, {1} are using it. Please rename it or disable all other sections using the same category name in your autoProcessMedia.cfg and try again.'.format( - inputCategory, section.keys())) + inputCategory, section.keys())) return [-1, ""] if section: @@ -728,7 +731,7 @@ def main(args, section=None): 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:])) + download_id='', failureLink=''.join(args[8:])) # Generic program elif len(args) > 5 and args[5] == 'generic': logger.info("Script triggered from generic program") @@ -741,7 +744,7 @@ def main(args, section=None): for subsection in subsections: if not core.CFG[section][subsection].isenabled(): continue - for dirName in getDirs(section, subsection, link = 'move'): + for dirName in getDirs(section, subsection, link='move'): logger.info("Starting manual run for {0}:{1} - Folder:{2}".format(section, subsection, dirName)) logger.info("Checking database for download info for {0} ...".format(os.path.basename(dirName))) @@ -769,17 +772,19 @@ def main(args, section=None): try: dirName = dirName.encode(core.SYS_ENCODING) - except: pass + except: + pass inputName = os.path.basename(dirName) try: inputName = inputName.encode(core.SYS_ENCODING) - except: pass + 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 {0}:{1}.".format( - section, subsection)) + logger.error("A problem was reported when trying to perform a manual run for {0}:{1}.".format + (section, subsection)) result = results if result[0] == 0: diff --git a/nzbToMylar.py b/nzbToMylar.py index 71f88bab..eba87a71 100755 --- a/nzbToMylar.py +++ b/nzbToMylar.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 -# -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### + +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to Mylar. # @@ -10,114 +10,115 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## +# ############################################################################## # -### OPTIONS +# ### OPTIONS -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## Mylar +# ## Mylar # Mylar script category. # # category that gets called for post-processing with Mylar. -#myCategory=comics +# myCategory=comics # Mylar host. # # The ipaddress for your Mylar server. e.g For the Same system use localhost or 127.0.0.1 -#myhost=localhost +# myhost=localhost # Mylar port. -#myport=8090 +# myport=8090 # Mylar username. -#myusername= +# myusername= # Mylar password. -#mypassword= +# mypassword= # Mylar uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#myssl=0 +# myssl=0 # Mylar web_root # # set this if using a reverse proxy. -#myweb_root= +# myweb_root= # Mylar wait_for # # Set the number of minutes to wait after calling the force process, to check the issue has changed status. -#myswait_for=1 +# myswait_for=1 # Mylar watch directory. # # set this to where your Mylar completed downloads are. -#mywatch_dir= +# mywatch_dir= # Mylar and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#myremote_path=0 +# myremote_path=0 -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "Mylar" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) diff --git a/nzbToNzbDrone.py b/nzbToNzbDrone.py index 63c64864..ac2e6d5f 100755 --- a/nzbToNzbDrone.py +++ b/nzbToNzbDrone.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 -# -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### + +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to NzbDrone. # @@ -10,229 +10,230 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## -### OPTIONS ### +# ############################################################################## +# ### OPTIONS ### -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Check Media for corruption (0, 1). # # Enable/Disable media file checking using ffprobe. -#check_media=1 +# check_media=1 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## NzbDrone +# ## NzbDrone # NzbDrone script category. # # category that gets called for post-processing with NzbDrone. -#ndCategory=tv2 +# ndCategory=tv2 # NzbDrone host. # # The ipaddress for your NzbDrone/Sonarr server. e.g For the Same system use localhost or 127.0.0.1 -#ndhost=localhost +# ndhost=localhost # NzbDrone port. -#ndport=8989 +# ndport=8989 # NzbDrone API key. -#ndapikey= +# ndapikey= # NzbDrone uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#ndssl=0 +# ndssl=0 # NzbDrone web_root # # set this if using a reverse proxy. -#ndweb_root= +# ndweb_root= # NzbDrone wait_for # # Set the number of minutes to wait after calling the renamer, to check the episode has changed status. -#ndwait_for=2 +# ndwait_for=2 # NzbDrone Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#nddelete_failed=0 +# nddelete_failed=0 # NzbDrone and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#ndremote_path=0 +# ndremote_path=0 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## Extensions +# ## Extensions # Media Extensions # # This is a list of media extensions that are used to verify that the download does contain valid media. -#mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts +# mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Transcoder +# ## Transcoder # getSubs (0, 1). # # set to 1 to download subtitles. -#getSubs = 0 +# getSubs = 0 # subLanguages. # # subLanguages. create a list of languages in the order you want them in your subtitles. -#subLanguages = eng,spa,fra +# subLanguages = eng,spa,fra # Transcode (0, 1). # # set to 1 to transcode, otherwise set to 0. -#transcode=0 +# transcode=0 # create a duplicate, or replace the original (0, 1). # # set to 1 to cretae a new file or 0 to replace the original -#duplicate=1 +# duplicate=1 # ignore extensions. # # list of extensions that won't be transcoded. -#ignoreExtensions=.avi,.mkv +# ignoreExtensions=.avi,.mkv # outputFastStart (0,1). # # outputFastStart. 1 will use -movflags + faststart. 0 will disable this from being used. -#outputFastStart = 0 +# outputFastStart = 0 # outputVideoPath. # # outputVideoPath. Set path you want transcoded videos moved to. Leave blank to disable. -#outputVideoPath = +# outputVideoPath = # processOutput (0,1). # # processOutput. 1 will send the outputVideoPath to SickBeard/CouchPotato. 0 will send original files. -#processOutput = 0 +# processOutput = 0 # audioLanguage. # # audioLanguage. set the 3 letter language code you want as your primary audio track. -#audioLanguage = eng +# audioLanguage = eng # allAudioLanguages (0,1). # # allAudioLanguages. 1 will keep all audio tracks (uses AudioCodec3) where available. -#allAudioLanguages = 0 +# allAudioLanguages = 0 # allSubLanguages (0,1). # # allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. -#allSubLanguages = 0 +# allSubLanguages = 0 # embedSubs (0,1). # # embedSubs. 1 will embded external sub/srt subs into your video if this is supported. -#embedSubs = 1 +# embedSubs = 1 # burnInSubtitle (0,1). # # burnInSubtitle. burns the default sub language into your video (needed for players that don't support subs) -#burnInSubtitle = 0 +# burnInSubtitle = 0 # extractSubs (0,1). # # extractSubs. 1 will extract subs from the video file and save these as external srt files. -#extractSubs = 0 +# extractSubs = 0 # externalSubDir. # # externalSubDir. set the directory where subs should be saved (if not the same directory as the video) -#externalSubDir = +# externalSubDir = # outputDefault (None, iPad, iPad-1080p, iPad-720p, Apple-TV2, iPod, iPhone, PS3, xbox, Roku-1080p, Roku-720p, Roku-480p, mkv, mp4-scene-release). # # outputDefault. Loads default configs for the selected device. The remaining options below are ignored. # If you want to use your own profile, set None and set the remaining options below. -#outputDefault = None +# outputDefault = None # hwAccel (0,1). # # hwAccel. 1 will set ffmpeg to enable hardware acceleration (this requires a recent ffmpeg). -#hwAccel=0 +# hwAccel=0 # ffmpeg output settings. -#outputVideoExtension=.mp4 -#outputVideoCodec=libx264 -#VideoCodecAllow = -#outputVideoPreset=medium -#outputVideoFramerate=24 -#outputVideoBitrate=800k -#outputAudioCodec=libmp3lame -#AudioCodecAllow = -#outputAudioBitrate=128k -#outputQualityPercent = 0 -#outputAudioTrack2Codec = libfaac -#AudioCodec2Allow = -#outputAudioTrack2Bitrate = 128k -#outputAudioOtherCodec = libmp3lame -#AudioOtherCodecAllow = -#outputAudioOtherBitrate = 128k -#outputSubtitleCodec = +# outputVideoExtension=.mp4 +# outputVideoCodec=libx264 +# VideoCodecAllow = +# outputVideoPreset=medium +# outputVideoFramerate=24 +# outputVideoBitrate=800k +# outputAudioCodec=libmp3lame +# AudioCodecAllow = +# outputAudioBitrate=128k +# outputQualityPercent = 0 +# outputAudioTrack2Codec = libfaac +# AudioCodec2Allow = +# outputAudioTrack2Bitrate = 128k +# outputAudioOtherCodec = libmp3lame +# AudioOtherCodecAllow = +# outputAudioOtherBitrate = 128k +# outputSubtitleCodec = -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "NzbDrone" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) diff --git a/nzbToSickBeard.py b/nzbToSickBeard.py index 73fefbfe..92474ea5 100755 --- a/nzbToSickBeard.py +++ b/nzbToSickBeard.py @@ -1,8 +1,8 @@ #!/usr/bin/env python2 # coding=utf-8 -# -############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### + +# ############################################################################## +# ### NZBGET POST-PROCESSING SCRIPT ### # Post-Process to SickBeard. # @@ -10,245 +10,246 @@ # # NOTE: This script requires Python to be installed on your system. -############################################################################## -### OPTIONS ### +# ############################################################################## +# ### OPTIONS ### -## General +# ## General # Auto Update nzbToMedia (0, 1). # # Set to 1 if you want nzbToMedia to automatically check for and update to the latest version -#auto_update=0 +# auto_update=0 # Check Media for corruption (0, 1). # # Enable/Disable media file checking using ffprobe. -#check_media=1 +# check_media=1 # Safe Mode protection of DestDir (0, 1). # # Enable/Disable a safety check to ensure we don't process all downloads in the default_downloadDirectory by mistake. -#safe_mode=1 +# safe_mode=1 -## SickBeard +# ## SickBeard # SickBeard script category. # # category that gets called for post-processing with SickBeard. -#sbCategory=tv +# sbCategory=tv # SickBeard host. # # The ipaddress for your SickBeard/SickRage server. e.g For the Same system use localhost or 127.0.0.1 -#sbhost=localhost +# sbhost=localhost # SickBeard port. -#sbport=8081 +# sbport=8081 # SickBeard username. -#sbusername= +# sbusername= # SickBeard password. -#sbpassword= +# sbpassword= # SickBeard uses ssl (0, 1). # # Set to 1 if using ssl, else set to 0. -#sbssl=0 +# sbssl=0 # SickBeard web_root # # set this if using a reverse proxy. -#sbweb_root= +# sbweb_root= # SickBeard watch directory. # # set this to where your SickBeard completed downloads are. -#sbwatch_dir= +# sbwatch_dir= # SickBeard fork. # # set to default or auto to auto-detect the custom fork type. -#sbfork=auto +# sbfork=auto # SickBeard Delete Failed Downloads (0, 1). # # set to 1 to delete failed, or 0 to leave files in place. -#sbdelete_failed=0 +# sbdelete_failed=0 # SickBeard process method. # # set this to move, copy, hardlink, symlink as appropriate if you want to over-ride SB defaults. Leave blank to use SB default. -#sbprocess_method= +# sbprocess_method= # SickBeard and NZBGet are a different system (0, 1). # # Enable to replace local path with the path as per the mountPoints below. -#sbremote_path=0 +# sbremote_path=0 -## Network +# ## Network # Network Mount Points (Needed for remote path above) # # Enter Mount points as LocalPath,RemotePath and separate each pair with '|' # e.g. mountPoints=/volume1/Public/,E:\|/volume2/share/,\\NAS\ -#mountPoints= +# mountPoints= -## Extensions +# ## Extensions # Media Extensions # # This is a list of media extensions that are used to verify that the download does contain valid media. -#mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts +# mediaExtensions=.mkv,.avi,.divx,.xvid,.mov,.wmv,.mp4,.mpg,.mpeg,.vob,.iso,.ts -## Posix +# ## Posix # Niceness for external tasks Extractor and Transcoder. # # Set the Niceness value for the nice command. These range from -20 (most favorable to the process) to 19 (least favorable to the process). -#niceness=10 +# niceness=10 # ionice scheduling class (0, 1, 2, 3). # # Set the ionice scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle. -#ionice_class=2 +# ionice_class=2 # ionice scheduling class data. # # Set the ionice scheduling class data. This defines the class data, if the class accepts an argument. For real time and best-effort, 0-7 is valid data. -#ionice_classdata=4 +# ionice_classdata=4 -## Transcoder +# ## Transcoder # getSubs (0, 1). # # set to 1 to download subtitles. -#getSubs=0 +# getSubs=0 # subLanguages. # # subLanguages. create a list of languages in the order you want them in your subtitles. -#subLanguages=eng,spa,fra +# subLanguages=eng,spa,fra # Transcode (0, 1). # # set to 1 to transcode, otherwise set to 0. -#transcode=0 +# transcode=0 # create a duplicate, or replace the original (0, 1). # # set to 1 to cretae a new file or 0 to replace the original -#duplicate=1 +# duplicate=1 # ignore extensions. # # list of extensions that won't be transcoded. -#ignoreExtensions=.avi,.mkv +# ignoreExtensions=.avi,.mkv # outputFastStart (0,1). # # outputFastStart. 1 will use -movflags + faststart. 0 will disable this from being used. -#outputFastStart=0 +# outputFastStart=0 # outputVideoPath. # # outputVideoPath. Set path you want transcoded videos moved to. Leave blank to disable. -#outputVideoPath= +# outputVideoPath= # processOutput (0,1). # # processOutput. 1 will send the outputVideoPath to SickBeard/CouchPotato. 0 will send original files. -#processOutput=0 +# processOutput=0 # audioLanguage. # # audioLanguage. set the 3 letter language code you want as your primary audio track. -#audioLanguage=eng +# audioLanguage=eng # allAudioLanguages (0,1). # # allAudioLanguages. 1 will keep all audio tracks (uses AudioCodec3) where available. -#allAudioLanguages=0 +# allAudioLanguages=0 # allSubLanguages (0,1). # # allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. -#allSubLanguages=0 +# allSubLanguages=0 # embedSubs (0,1). # # embedSubs. 1 will embded external sub/srt subs into your video if this is supported. -#embedSubs=1 +# embedSubs=1 # burnInSubtitle (0,1). # # burnInSubtitle. burns the default sub language into your video (needed for players that don't support subs) -#burnInSubtitle=0 +# burnInSubtitle=0 # extractSubs (0,1). # # extractSubs. 1 will extract subs from the video file and save these as external srt files. -#extractSubs=0 +# extractSubs=0 # externalSubDir. # # externalSubDir. set the directory where subs should be saved (if not the same directory as the video) -#externalSubDir= +# externalSubDir= # outputDefault (None, iPad, iPad-1080p, iPad-720p, Apple-TV2, iPod, iPhone, PS3, xbox, Roku-1080p, Roku-720p, Roku-480p, mkv, mp4-scene-release). # # outputDefault. Loads default configs for the selected device. The remaining options below are ignored. # If you want to use your own profile, set None and set the remaining options below. -#outputDefault=None +# outputDefault=None # hwAccel (0,1). # # hwAccel. 1 will set ffmpeg to enable hardware acceleration (this requires a recent ffmpeg). -#hwAccel=0 +# hwAccel=0 # ffmpeg output settings. -#outputVideoExtension=.mp4 -#outputVideoCodec=libx264 -#VideoCodecAllow= -#outputVideoPreset=medium -#outputVideoFramerate=24 -#outputVideoBitrate=800k -#outputAudioCodec=ac3 -#AudioCodecAllow= -#outputAudioChannels=6 -#outputAudioBitrate=640k -#outputQualityPercent= -#outputAudioTrack2Codec=libfaac -#AudioCodec2Allow= -#outputAudioTrack2Channels=2 -#outputAudioTrack2Bitrate=160k -#outputAudioOtherCodec=libmp3lame -#AudioOtherCodecAllow= -#outputAudioOtherChannels=2 -#outputAudioOtherBitrate=128k -#outputSubtitleCodec= +# outputVideoExtension=.mp4 +# outputVideoCodec=libx264 +# VideoCodecAllow= +# outputVideoPreset=medium +# outputVideoFramerate=24 +# outputVideoBitrate=800k +# outputAudioCodec=ac3 +# AudioCodecAllow= +# outputAudioChannels=6 +# outputAudioBitrate=640k +# outputQualityPercent= +# outputAudioTrack2Codec=libfaac +# AudioCodec2Allow= +# outputAudioTrack2Channels=2 +# outputAudioTrack2Bitrate=160k +# outputAudioOtherCodec=libmp3lame +# AudioOtherCodecAllow= +# outputAudioOtherChannels=2 +# outputAudioOtherBitrate=128k +# outputSubtitleCodec= -## WakeOnLan +# ## WakeOnLan # use WOL (0, 1). # # set to 1 to send WOL broadcast to the mac and test the server (e.g. xbmc) on the host and port specified. -#wolwake=0 +# wolwake=0 # WOL MAC # # enter the mac address of the system to be woken. -#wolmac=00:01:2e:2D:64:e1 +# wolmac=00:01:2e:2D:64:e1 # Set the Host and Port of a server to verify system has woken. -#wolhost=192.168.1.37 -#wolport=80 +# wolhost=192.168.1.37 +# wolport=80 + +# ### NZBGET POST-PROCESSING SCRIPT ### +# ############################################################################## -### NZBGET POST-PROCESSING SCRIPT ### -############################################################################## import sys import nzbToMedia section = "SickBeard" result = nzbToMedia.main(sys.argv, section) -sys.exit(result) \ No newline at end of file +sys.exit(result) From 84a89c62d5f3504babc7f9fc9e18fcebec52e0d3 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:25:34 -0400 Subject: [PATCH 04/10] PEP8: Tests for membership should use in/not in PEP8: .has_key() is deprecated, use in --- TorrentToMedia.py | 4 ++-- nzbToMedia.py | 18 +++++++++--------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index b3f4e719..55138674 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -203,7 +203,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, logger.debug('Checking for archives to extract in directory: {0}'.format(inputDirectory)) core.extractFiles(inputDirectory, outputDestination, keep_archive) - if not inputCategory in core.NOFLATTEN: # don't flatten hp in case multi cd albums, and we need to copy this back later. + if inputCategory not in core.NOFLATTEN: # don't flatten hp in case multi cd albums, and we need to copy this back later. core.flatten(outputDestination) # Now check if video files exist in destination: @@ -220,7 +220,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, logger.warning("Found no media files in {0}".format(outputDestination)) # Only these sections can handling failed downloads so make sure everything else gets through without the check for failed - if not sectionName in ['CouchPotato', 'SickBeard', 'NzbDrone']: + if sectionName not in ['CouchPotato', 'SickBeard', 'NzbDrone']: status = 0 logger.info("Calling {0}:{1} to post-process:{2}".format(sectionName, usercat, inputName)) diff --git a/nzbToMedia.py b/nzbToMedia.py index 5e344fa8..4997116b 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -624,7 +624,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down if clientAgent != 'manual': # update download status in our DB update_downloadInfoStatus(inputName, 1) - if not sectionName in ['UserScript', 'NzbDrone']: + if sectionName not in ['UserScript', 'NzbDrone']: # cleanup our processing folders of any misc unwanted files and empty directories cleanDir(inputDirectory, sectionName, inputCategory) @@ -647,7 +647,7 @@ def main(args, section=None): status = 0 # NZBGet - if os.environ.has_key('NZBOP_SCRIPTDIR'): + if 'NZBOP_SCRIPTDIR' in os.environ: # 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 {0} is not supported. Please update NZBGet.".format(os.environ['NZBOP_VERSION'])) @@ -656,7 +656,7 @@ def main(args, section=None): logger.info("Script triggered from NZBGet Version {0}.".format(os.environ['NZBOP_VERSION'])) # Check if the script is called from nzbget 13.0 or later - if os.environ.has_key('NZBPP_TOTALSTATUS'): + if 'NZBPP_TOTALSTATUS' in os.environ: if not os.environ['NZBPP_TOTALSTATUS'] == 'SUCCESS': logger.info("Download failed with status {0}.".format(os.environ['NZBPP_STATUS'])) status = 1 @@ -689,13 +689,13 @@ def main(args, section=None): # Check for download_id to pass to CouchPotato download_id = "" failureLink = None - if os.environ.has_key('NZBPR_COUCHPOTATO'): + if 'NZBPR_COUCHPOTATO' in os.environ: download_id = os.environ['NZBPR_COUCHPOTATO'] - elif os.environ.has_key('NZBPR_DRONE'): + elif 'NZBPR_DRONE' in os.environ: download_id = os.environ['NZBPR_DRONE'] - elif os.environ.has_key('NZBPR_SONARR'): + elif 'NZBPR_SONARR' in os.environ: download_id = os.environ['NZBPR_SONARR'] - if os.environ.has_key('NZBPR__DNZB_FAILURE'): + if 'NZBPR__DNZB_FAILURE' in os.environ: failureLink = os.environ['NZBPR__DNZB_FAILURE'] # All checks done, now launching the script. @@ -791,14 +791,14 @@ def main(args, section=None): logger.info("The {0} script completed successfully.".format(args[0])) if result[1]: print result[1] + "!" # For SABnzbd Status display. - if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11 + if 'NZBOP_SCRIPTDIR' in os.environ: # return code for nzbget v11 del core.MYAPP return core.NZBGET_POSTPROCESS_SUCCESS else: logger.error("A problem was reported in the {0} script.".format(args[0])) if result[1]: print result[1] + "!" # For SABnzbd Status display. - if os.environ.has_key('NZBOP_SCRIPTDIR'): # return code for nzbget v11 + if 'NZBOP_SCRIPTDIR' in os.environ: # return code for nzbget v11 del core.MYAPP return core.NZBGET_POSTPROCESS_ERROR del core.MYAPP From 2671becddeb19cac47383404bea5facf48f1bba9 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:44:32 -0400 Subject: [PATCH 05/10] Use six.text_type to standardize unicode function --- TorrentToMedia.py | 11 ++++++----- nzbToMedia.py | 12 +++++++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 55138674..1d0d1f87 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -5,6 +5,7 @@ import os import sys import core +from libs.six import text_type from core import logger, nzbToMediaDB from core.nzbToMediaUtil import convert_to_ascii, CharReplace, plex_update from core.nzbToMediaUserScript import external_script @@ -31,11 +32,11 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, except: pass - controlValueDict = {"input_directory": unicode(inputDirectory1)} - newValueDict = {"input_name": unicode(inputName1), - "input_hash": unicode(inputHash), - "input_id": unicode(inputID), - "client_agent": unicode(clientAgent), + controlValueDict = {"input_directory": text_type(inputDirectory1)} + newValueDict = {"input_name": text_type(inputName1), + "input_hash": text_type(inputHash), + "input_id": text_type(inputID), + "client_agent": text_type(clientAgent), "status": 0, "last_update": datetime.date.today().toordinal() } diff --git a/nzbToMedia.py b/nzbToMedia.py index 4997116b..7efa244f 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -502,6 +502,8 @@ import os import sys import datetime +from libs.six import text_type + import core from core.autoProcess.autoProcessComics import autoProcessComics from core.autoProcess.autoProcessGames import autoProcessGames @@ -539,11 +541,11 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down except: pass - controlValueDict = {"input_directory": unicode(inputDirectory1)} - newValueDict = {"input_name": unicode(inputName1), - "input_hash": unicode(download_id), - "input_id": unicode(download_id), - "client_agent": unicode(clientAgent), + controlValueDict = {"input_directory": text_type(inputDirectory1)} + newValueDict = {"input_name": text_type(inputName1), + "input_hash": text_type(download_id), + "input_id": text_type(download_id), + "client_agent": text_type(clientAgent), "status": 0, "last_update": datetime.date.today().toordinal() } From 9f6ca4eaadfb95229351f062fa7df397233761df Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 04:20:58 -0400 Subject: [PATCH 06/10] Fix unresolved reference to replace_links --- TorrentToMedia.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 1d0d1f87..6afbc984 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -7,7 +7,7 @@ import core from libs.six import text_type from core import logger, nzbToMediaDB -from core.nzbToMediaUtil import convert_to_ascii, CharReplace, plex_update +from core.nzbToMediaUtil import convert_to_ascii, CharReplace, plex_update, replace_links from core.nzbToMediaUserScript import external_script @@ -270,7 +270,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, for dirpath, dirs, files in os.walk(inputDirectory): for file in files: logger.debug('Checking symlink: {0}'.format(os.path.join(dirpath, file))) - core.replace_links(os.path.join(dirpath, file)) + replace_links(os.path.join(dirpath, file)) core.remove_torrent(clientAgent, inputHash, inputID, inputName) if not sectionName == 'UserScript': # for user script, we assume this is cleaned by the script or option USER_SCRIPT_CLEAN From ccdad818fd939a2a3b8529769dcc42bf45093e58 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 03:47:27 -0400 Subject: [PATCH 07/10] Use print_function to standardize printing --- nzbToMedia.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/nzbToMedia.py b/nzbToMedia.py index 7efa244f..cd42cf18 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -499,6 +499,8 @@ # ### NZBGET POST-PROCESSING SCRIPT ### # ############################################################################## +from __future__ import print_function + import os import sys import datetime @@ -513,7 +515,6 @@ 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 -from six import text_type # post-processing @@ -792,14 +793,14 @@ def main(args, section=None): if result[0] == 0: logger.info("The {0} script completed successfully.".format(args[0])) if result[1]: - print result[1] + "!" # For SABnzbd Status display. + print(result[1] + "!") if 'NZBOP_SCRIPTDIR' in os.environ: # return code for nzbget v11 del core.MYAPP return core.NZBGET_POSTPROCESS_SUCCESS else: logger.error("A problem was reported in the {0} script.".format(args[0])) if result[1]: - print result[1] + "!" # For SABnzbd Status display. + print(result[1] + "!") if 'NZBOP_SCRIPTDIR' in os.environ: # return code for nzbget v11 del core.MYAPP return core.NZBGET_POSTPROCESS_ERROR From a3a59af3f880394ee32382f7a512d868a16c4617 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 04:03:14 -0400 Subject: [PATCH 08/10] Too broad exceptions: * Use .get() with default value instead. * Use UnicodeError to catch .encode exceptions --- TorrentToMedia.py | 58 +++++++++++++---------------------------------- nzbToMedia.py | 25 +++++++------------- 2 files changed, 24 insertions(+), 59 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 6afbc984..6fa16974 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -15,14 +15,12 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, status = 1 # 1 = failed | 0 = success root = 0 foundFile = 0 - uniquePath = 1 if clientAgent != 'manual' and not core.DOWNLOADINFO: logger.debug('Adding TORRENT download info for directory {0} to database'.format(inputDirectory)) myDB = nzbToMediaDB.DBConnection() - encoded = False inputDirectory1 = inputDirectory inputName1 = inputName @@ -53,11 +51,11 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, usercat = inputCategory try: inputName = inputName.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass try: inputDirectory = inputDirectory.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass logger.debug("Determined Directory: {0} | Name: {1} | Category: {2}".format(inputDirectory, inputName, inputCategory)) @@ -88,25 +86,10 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, inputCategory)) return [-1, ""] - try: - Torrent_NoLink = int(section[usercat]["Torrent_NoLink"]) - except: - Torrent_NoLink = 0 - - try: - keep_archive = int(section[usercat]["keep_archive"]) - except: - keep_archive = 0 - - try: - extract = int(section[usercat]['extract']) - except: - extract = 0 - - try: - uniquePath = int(section[usercat]["unique_path"]) - except: - uniquePath = 1 + Torrent_NoLink = int(section[usercat].get("Torrent_NoLink", 0)) + keep_archive = int(section[usercat].get("keep_archive", 0)) + extract = int(section[usercat].get('extract', 0)) + uniquePath = int(section[usercat].get("unique_path", 1)) if clientAgent != 'manual': core.pause_torrent(clientAgent, inputHash, inputID, inputName) @@ -126,7 +109,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, core.os.path.join(core.OUTPUTDIRECTORY, inputCategory)) try: outputDestination = outputDestination.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass if outputDestination in inputDirectory: @@ -167,7 +150,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, "Setting outputDestination to {0} to preserve folder structure".format(os.path.dirname(targetFile))) try: targetFile = targetFile.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass if root == 1: if not foundFile: @@ -327,34 +310,25 @@ def main(args): os.path.basename(dirName)) ) - try: - clientAgent = str(core.DOWNLOADINFO[0]['client_agent']) - except: - clientAgent = 'manual' - try: - inputHash = str(core.DOWNLOADINFO[0]['input_hash']) - except: - inputHash = None - try: - inputID = str(core.DOWNLOADINFO[0]['input_id']) - except: - inputID = None + clientAgent = str(core.DOWNLOADINFO[0].get('client_agent', '')) + inputHash = str(core.DOWNLOADINFO[0].get('input_hash', '')) + inputID = str(core.DOWNLOADINFO[0].get('input_id', '')) - if clientAgent.lower() not in core.TORRENT_CLIENTS and clientAgent != 'manual': + if clientAgent and clientAgent.lower() not in core.TORRENT_CLIENTS: continue try: dirName = dirName.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass inputName = os.path.basename(dirName) try: inputName = inputName.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass - results = processTorrent(dirName, inputName, subsection, inputHash, inputID, - clientAgent) + results = processTorrent(dirName, inputName, subsection, inputHash or None, inputID or None, + clientAgent or 'manual') if results[0] != 0: logger.error("A problem was reported when trying to perform a manual run for {0}:{1}.".format( section, subsection)) diff --git a/nzbToMedia.py b/nzbToMedia.py index cd42cf18..a3e6363c 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -581,10 +581,7 @@ def process(inputDirectory, inputName=None, status=0, clientAgent='manual', down inputCategory)) return [-1, ""] - try: - extract = int(section[usercat]['extract']) - except: - extract = 0 + extract = int(section[usercat].get('extract', 0)) try: if int(section[usercat]['remote_path']) and not core.REMOTEPATHS: @@ -761,30 +758,24 @@ def main(args, section=None): 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 + clientAgent = str(core.DOWNLOADINFO[0].get('client_agent', '')) + download_id = str(core.DOWNLOADINFO[0].get('input_id', '')) - if clientAgent.lower() not in core.NZB_CLIENTS and clientAgent != 'manual': + if clientAgent and clientAgent.lower() not in core.NZB_CLIENTS: continue try: dirName = dirName.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass inputName = os.path.basename(dirName) try: inputName = inputName.encode(core.SYS_ENCODING) - except: + except UnicodeError: pass - results = process(dirName, inputName, 0, clientAgent=clientAgent, - download_id=download_id, inputCategory=subsection) + results = process(dirName, inputName, 0, clientAgent=clientAgent or 'manual', + download_id=download_id or None, inputCategory=subsection) if results[0] != 0: logger.error("A problem was reported when trying to perform a manual run for {0}:{1}.".format (section, subsection)) From 2ad9f2e35f9294cd70381bd4df43d1f80bf2d1d7 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 05:45:42 -0400 Subject: [PATCH 09/10] Standardize string formatting to use .format instead of concat --- TorrentToMedia.py | 6 +- core/__init__.py | 12 ++- core/autoProcess/autoProcessMovie.py | 4 +- core/databases/mainDB.py | 19 ++-- core/extractor/extractor.py | 4 +- core/gh_api.py | 8 +- core/logger.py | 8 +- core/nzbToMediaConfig.py | 28 +++--- core/nzbToMediaDB.py | 94 +++++++++++------- core/nzbToMediaUserScript.py | 4 +- core/nzbToMediaUtil.py | 35 +++---- core/transcoder/transcoder.py | 109 ++++++++++---------- core/transmissionrpc/client.py | 13 ++- core/transmissionrpc/utils.py | 2 +- core/utorrent/client.py | 2 +- core/utorrent/upload.py | 4 +- core/versionCheck.py | 142 +++++++++++++-------------- nzbToMedia.py | 4 +- 18 files changed, 259 insertions(+), 239 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index 6fa16974..ad61a6a2 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -310,9 +310,9 @@ def main(args): os.path.basename(dirName)) ) - clientAgent = str(core.DOWNLOADINFO[0].get('client_agent', '')) - inputHash = str(core.DOWNLOADINFO[0].get('input_hash', '')) - inputID = str(core.DOWNLOADINFO[0].get('input_id', '')) + clientAgent = text_type(core.DOWNLOADINFO[0].get('client_agent', '')) + inputHash = text_type(core.DOWNLOADINFO[0].get('input_hash', '')) + inputID = text_type(core.DOWNLOADINFO[0].get('input_id', '')) if clientAgent and clientAgent.lower() not in core.TORRENT_CLIENTS: continue diff --git a/core/__init__.py b/core/__init__.py index 80444fea..39b6500d 100644 --- a/core/__init__.py +++ b/core/__init__.py @@ -265,8 +265,9 @@ def initialize(section=None): # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(SYS_ENCODING) except: - print('Sorry, you MUST add the nzbToMedia folder to the PYTHONPATH environment variable') - print('or find another way to force Python to use ' + SYS_ENCODING + ' for string encoding.') + print('Sorry, you MUST add the nzbToMedia folder to the PYTHONPATH environment variable' + '\nor find another way to force Python to use {codec} for string encoding.'.format + (codec=SYS_ENCODING)) if 'NZBOP_SCRIPTDIR' in os.environ: sys.exit(NZBGET_POSTPROCESS_ERROR) else: @@ -333,8 +334,9 @@ def initialize(section=None): logger.error("Update wasn't successful, not restarting. Check your log for more information.") # Set Current Version - logger.info( - 'nzbToMedia Version:' + NZBTOMEDIA_VERSION + ' Branch:' + GIT_BRANCH + ' (' + platform.system() + ' ' + platform.release() + ')') + logger.info('nzbToMedia Version:{version} Branch:{branch} ({system} {release})'.format + (version=NZBTOMEDIA_VERSION, branch=GIT_BRANCH, + system=platform.system(), release=platform.release())) if int(CFG["WakeOnLan"]["wake"]) == 1: WakeUp() @@ -842,7 +844,7 @@ def restart(): if popen_list: popen_list += SYS_ARGV - logger.log(u"Restarting nzbToMedia with " + str(popen_list)) + logger.log(u"Restarting nzbToMedia with {args}".format(args=popen_list)) logger.close() p = subprocess.Popen(popen_list, cwd=os.getcwd()) p.wait() diff --git a/core/autoProcess/autoProcessMovie.py b/core/autoProcess/autoProcessMovie.py index a4e4b0ba..7b89e40f 100644 --- a/core/autoProcess/autoProcessMovie.py +++ b/core/autoProcess/autoProcessMovie.py @@ -46,7 +46,7 @@ class autoProcessMovie(object): if not result['success']: if 'error' in result: - logger.error(str(result['error'])) + logger.error('{0}'.format(result['error'])) else: logger.error("no media found for id {0}".format(params['id'])) return results @@ -262,7 +262,7 @@ class autoProcessMovie(object): if release_id: logger.postprocess("Setting failed release {0} to ignored ...".format(inputName), section) - url = baseURL + "/release.ignore" + url = "{url}/release.ignore".format(url=baseURL) params = {'id': release_id} logger.debug("Opening URL: {0} with PARAMS: {1}".format(url, params), section) diff --git a/core/databases/mainDB.py b/core/databases/mainDB.py index e32e6dae..d79033db 100644 --- a/core/databases/mainDB.py +++ b/core/databases/mainDB.py @@ -42,18 +42,17 @@ class InitialSchema(nzbToMediaDB.SchemaUpgrade): cur_db_version = self.checkDBVersion() if cur_db_version < MIN_DB_VERSION: - logger.log_error_and_exit("Your database version (" + str( - cur_db_version) + ") is too old to migrate from what this version of nzbToMedia supports (" + \ - str(MIN_DB_VERSION) + ").\n" + \ - "Please remove nzbtomedia.db file to begin fresh." - ) + logger.log_error_and_exit(u"Your database version ({current}) is too old to migrate " + u"from what this version of nzbToMedia supports ({min})." + u"\nPlease remove nzbtomedia.db file to begin fresh.".format + (current=cur_db_version, min=MIN_DB_VERSION)) if cur_db_version > MAX_DB_VERSION: - logger.log_error_and_exit("Your database version (" + str( - cur_db_version) + ") has been incremented past what this version of nzbToMedia supports (" + \ - str(MAX_DB_VERSION) + ").\n" + \ - "If you have used other forks of nzbToMedia, your database may be unusable due to their modifications." - ) + logger.log_error_and_exit(u"Your database version ({current}) has been incremented " + u"past what this version of nzbToMedia supports ({max})." + u"\nIf you have used other forks of nzbToMedia, your database " + u"may be unusable due to their modifications.".format + (current=cur_db_version, max=MAX_DB_VERSION)) if cur_db_version < MAX_DB_VERSION: # We need to upgrade. queries = [ "CREATE TABLE downloads2 (input_directory TEXT, input_name TEXT, input_hash TEXT, input_id TEXT, client_agent TEXT, status INTEGER, last_update NUMERIC, CONSTRAINT pk_downloadID PRIMARY KEY (input_directory, input_name));", diff --git a/core/extractor/extractor.py b/core/extractor/extractor.py index 08011706..7cbd34b9 100644 --- a/core/extractor/extractor.py +++ b/core/extractor/extractor.py @@ -70,7 +70,7 @@ def extract(filePath, outputDestination): if ext[1] in (".gz", ".bz2", ".lzma"): # Check if this is a tar if os.path.splitext(ext[0])[1] == ".tar": - cmd = EXTRACT_COMMANDS[".tar" + ext[1]] + cmd = EXTRACT_COMMANDS[".tar{ext}".format(ext=ext[1])] elif ext[1] in (".1", ".01", ".001") and os.path.splitext(ext[0])[1] in (".rar", ".zip", ".7z"): cmd = EXTRACT_COMMANDS[os.path.splitext(ext[0])[1]] elif ext[1] in (".cb7", ".cba", ".cbr", ".cbt", ".cbz"): # don't extract these comic book archives. @@ -131,7 +131,7 @@ def extract(filePath, outputDestination): continue cmd2 = cmd # append password here. - passcmd = "-p" + password + passcmd = "-p{pwd}".format(pwd=password) cmd2.append(passcmd) p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine. res = p.wait() diff --git a/core/gh_api.py b/core/gh_api.py index 1db7faf7..f1264c09 100644 --- a/core/gh_api.py +++ b/core/gh_api.py @@ -1,6 +1,7 @@ # coding=utf-8 import requests +from six import iteritems class GitHub(object): @@ -19,10 +20,11 @@ class GitHub(object): Access the API at the path given and with the optional params given. """ - url = 'https://api.github.com/' + '/'.join(path) + url = 'https://api.github.com/{path}'.format(path='/'.join(path)) if params and type(params) is dict: - url += '?' + '&'.join([str(x) + '=' + str(params[x]) for x in params.keys()]) + url += '?{params}'.format(params='&'.join(['{key}={value}'.format(key=k, value=v) + for k, v in iteritems(params)])) data = requests.get(url, verify=False) @@ -59,6 +61,6 @@ class GitHub(object): Returns a deserialized json object containing the compare info. See http://developer.github.com/v3/repos/commits/ """ access_API = self._access_API( - ['repos', self.github_repo_user, self.github_repo, 'compare', base + '...' + head], + ['repos', self.github_repo_user, self.github_repo, 'compare', '{base}...{head}'.format(base=base, head=head)], params={'per_page': per_page}) return access_API diff --git a/core/logger.py b/core/logger.py index 94d1764f..5a555bf2 100644 --- a/core/logger.py +++ b/core/logger.py @@ -136,7 +136,7 @@ class NTMRotatingLogHandler(object): i: Log number to ues """ - return self.log_file_path + ('.' + str(i) if i else '') + return self.log_file_path + ('.{0}'.format(i) if i else '') def _num_logs(self): """ @@ -193,9 +193,9 @@ class NTMRotatingLogHandler(object): self.writes_since_check += 1 try: - message = u"{0}: {1}".format(str(section).upper(), toLog) - except: - message = u"{0}: Message contains non-utf-8 string".format(str(section).upper()) + message = u"{0}: {1}".format(section.upper(), toLog) + except UnicodeError: + message = u"{0}: Message contains non-utf-8 string".format(section.upper()) out_line = message diff --git a/core/nzbToMediaConfig.py b/core/nzbToMediaConfig.py index 00aed989..b40b1cf8 100644 --- a/core/nzbToMediaConfig.py +++ b/core/nzbToMediaConfig.py @@ -238,7 +238,7 @@ class ConfigObj(configobj.ConfigObj, Section): process_section(section, subsection) # create a backup of our old config - CFG_OLD.filename = core.CONFIG_FILE + ".old" + CFG_OLD.filename ="{config}.old".format(config=core.CONFIG_FILE) CFG_OLD.write() # write our new config to autoProcessMedia.cfg @@ -270,7 +270,7 @@ class ConfigObj(configobj.ConfigObj, Section): envKeys = ['AUTO_UPDATE', 'CHECK_MEDIA', 'SAFE_MODE'] cfgKeys = ['auto_update', 'check_media', 'safe_mode'] for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -280,7 +280,7 @@ class ConfigObj(configobj.ConfigObj, Section): envKeys = ['MOUNTPOINTS'] cfgKeys = ['mount_points'] for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -294,7 +294,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'wait_for', 'watch_dir'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_CPS' + envKeys[index] + key = 'NZBPO_CPS{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -311,7 +311,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'delete_failed', 'Torrent_NoLink', 'nzbExtractionBy', 'remote_path', 'process_method'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_SB' + envKeys[index] + key = 'NZBPO_SB{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -328,7 +328,7 @@ class ConfigObj(configobj.ConfigObj, Section): cfgKeys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'wait_for', 'watch_dir', 'remote_path'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_HP' + envKeys[index] + key = 'NZBPO_HP{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -345,7 +345,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'remote_path'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_MY' + envKeys[index] + key = 'NZBPO_MY{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -360,7 +360,7 @@ class ConfigObj(configobj.ConfigObj, Section): cfgKeys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'watch_dir', 'library', 'remote_path'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_GZ' + envKeys[index] + key = 'NZBPO_GZ{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -377,7 +377,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'Torrent_NoLink', 'nzbExtractionBy', 'wait_for', 'delete_failed', 'remote_path'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_ND' + envKeys[index] + key = 'NZBPO_ND{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -392,7 +392,7 @@ class ConfigObj(configobj.ConfigObj, Section): envKeys = ['COMPRESSEDEXTENSIONS', 'MEDIAEXTENSIONS', 'METAEXTENSIONS'] cfgKeys = ['compressedExtensions', 'mediaExtensions', 'metaExtensions'] for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -402,7 +402,7 @@ class ConfigObj(configobj.ConfigObj, Section): envKeys = ['NICENESS', 'IONICE_CLASS', 'IONICE_CLASSDATA'] cfgKeys = ['niceness', 'ionice_class', 'ionice_classdata'] for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -430,7 +430,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'outputSubtitleCodec', 'outputAudioChannels', 'outputAudioTrack2Channels', 'outputAudioOtherChannels'] for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -440,7 +440,7 @@ class ConfigObj(configobj.ConfigObj, Section): envKeys = ['WAKE', 'HOST', 'PORT', 'MAC'] cfgKeys = ['wake', 'host', 'port', 'mac'] for index in range(len(envKeys)): - key = 'NZBPO_WOL' + envKeys[index] + key = 'NZBPO_WOL{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] @@ -454,7 +454,7 @@ class ConfigObj(configobj.ConfigObj, Section): 'user_script_successCodes', 'user_script_clean', 'delay', 'remote_path'] if envCatKey in os.environ: for index in range(len(envKeys)): - key = 'NZBPO_' + envKeys[index] + key = 'NZBPO_{index}'.format(index=envKeys[index]) if key in os.environ: option = cfgKeys[index] value = os.environ[key] diff --git a/core/nzbToMediaDB.py b/core/nzbToMediaDB.py index de7fd825..de9e3c91 100644 --- a/core/nzbToMediaDB.py +++ b/core/nzbToMediaDB.py @@ -56,28 +56,29 @@ class DBConnection(object): while attempt < 5: try: if args is None: - logger.log(self.filename + ": " + query, logger.DB) + logger.log("{name}: {query}".format(name=self.filename, query=query), logger.DB) cursor = self.connection.cursor() cursor.execute(query) sqlResult = cursor.fetchone()[0] else: - logger.log(self.filename + ": " + query + " with args " + str(args), logger.DB) + logger.log("{name}: {query} with args {args}".format + (name=self.filename, query=query, args=args), logger.DB) cursor = self.connection.cursor() cursor.execute(query, args) sqlResult = cursor.fetchone()[0] # get out of the connection attempt loop since we were successful break - except sqlite3.OperationalError as e: - if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]: - logger.log(u"DB error: " + str(e), logger.WARNING) + except sqlite3.OperationalError as error: + if "unable to open database file" in error.args[0] or "database is locked" in error.args[0]: + logger.log(u"DB error: {msg}".format(msg=error), logger.WARNING) attempt += 1 time.sleep(1) else: - logger.log(u"DB error: " + str(e), logger.ERROR) + logger.log(u"DB error: {msg}".format(msg=error), logger.ERROR) raise - except sqlite3.DatabaseError as e: - logger.log(u"Fatal error executing query: " + str(e), logger.ERROR) + except sqlite3.DatabaseError as error: + logger.log(u"Fatal error executing query: {msg}".format(msg=error), logger.ERROR) raise return sqlResult @@ -98,26 +99,26 @@ class DBConnection(object): sqlResult.append(self.connection.execute(qu[0])) elif len(qu) > 1: if logTransaction: - logger.log(qu[0] + " with args " + str(qu[1]), logger.DEBUG) + logger.log(u"{query} with args {args}".format(query=qu[0], args=qu[1]), logger.DEBUG) sqlResult.append(self.connection.execute(qu[0], qu[1])) self.connection.commit() - logger.log(u"Transaction with " + str(len(querylist)) + u" query's executed", logger.DEBUG) + logger.log(u"Transaction with {x} query's executed".format(x=len(querylist)), logger.DEBUG) return sqlResult - except sqlite3.OperationalError as e: + except sqlite3.OperationalError as error: sqlResult = [] if self.connection: self.connection.rollback() - if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]: - logger.log(u"DB error: " + str(e), logger.WARNING) + if "unable to open database file" in error.args[0] or "database is locked" in error.args[0]: + logger.log(u"DB error: {msg}".format(msg=error), logger.WARNING) attempt += 1 time.sleep(1) else: - logger.log(u"DB error: " + str(e), logger.ERROR) + logger.log(u"DB error: {msg}".format(msg=error), logger.ERROR) raise - except sqlite3.DatabaseError as e: + except sqlite3.DatabaseError as error: if self.connection: self.connection.rollback() - logger.log(u"Fatal error executing query: " + str(e), logger.ERROR) + logger.log(u"Fatal error executing query: {msg}".format(msg=error), logger.ERROR) raise return sqlResult @@ -132,24 +133,25 @@ class DBConnection(object): while attempt < 5: try: if args is None: - logger.log(self.filename + ": " + query, logger.DB) + logger.log(u"{name}: {query}".format(name=self.filename, query=query), logger.DB) sqlResult = self.connection.execute(query) else: - logger.log(self.filename + ": " + query + " with args " + str(args), logger.DB) + logger.log(u"{name}: {query} with args {args}".format + (name=self.filename, query=query, args=args), logger.DB) sqlResult = self.connection.execute(query, args) self.connection.commit() # get out of the connection attempt loop since we were successful break - except sqlite3.OperationalError as e: - if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]: - logger.log(u"DB error: " + str(e), logger.WARNING) + except sqlite3.OperationalError as error: + if "unable to open database file" in error.args[0] or "database is locked" in error.args[0]: + logger.log(u"DB error: {msg}".format(msg=error), logger.WARNING) attempt += 1 time.sleep(1) else: - logger.log(u"DB error: " + str(e), logger.ERROR) + logger.log(u"DB error: {msg}".format(msg=error), logger.ERROR) raise - except sqlite3.DatabaseError as e: - logger.log(u"Fatal error executing query: " + str(e), logger.ERROR) + except sqlite3.DatabaseError as error: + logger.log(u"Fatal error executing query: {msg}".format(msg=error), logger.ERROR) raise return sqlResult @@ -167,17 +169,28 @@ class DBConnection(object): changesBefore = self.connection.total_changes - genParams = lambda myDict: [x + " = ?" for x in myDict.keys()] + genParams = lambda myDict: ["{key} = ?".format(key=k) for k in myDict.keys()] - query = "UPDATE " + tableName + " SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join( - genParams(keyDict)) - - self.action(query, valueDict.values() + keyDict.values()) + self.action( + "UPDATE {table} " + "SET {params} " + "WHERE {conditions}".format( + table=tableName, + params=", ".join(genParams(valueDict)), + conditions=" AND ".join(genParams(keyDict))), + valueDict.values() + keyDict.values() + ) if self.connection.total_changes == changesBefore: - query = "INSERT OR IGNORE INTO " + tableName + " (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \ - " VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")" - self.action(query, valueDict.values() + keyDict.values()) + self.action( + "INSERT OR IGNORE INTO {table} ({columns}) " + "VALUES ({values})".format( + table=tableName, + columns=", ".join(valueDict.keys() + keyDict.keys()), + values=", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ) + , valueDict.values() + keyDict.values() + ) def tableInfo(self, tableName): # FIXME ? binding is not supported here, but I cannot find a way to escape a string manually @@ -222,17 +235,22 @@ def prettyName(class_name): def _processUpgrade(connection, upgradeClass): instance = upgradeClass(connection) - logger.log(u"Checking " + prettyName(upgradeClass.__name__) + " database upgrade", logger.DEBUG) + logger.log(u"Checking {name} database upgrade".format + (name=prettyName(upgradeClass.__name__)), logger.DEBUG) if not instance.test(): - logger.log(u"Database upgrade required: " + prettyName(upgradeClass.__name__), logger.MESSAGE) + logger.log(u"Database upgrade required: {name}".format + (name=prettyName(upgradeClass.__name__)), logger.MESSAGE) try: instance.execute() - except sqlite3.DatabaseError as e: - print("Error in " + str(upgradeClass.__name__) + ": " + str(e)) + except sqlite3.DatabaseError as error: + print(u"Error in {name}: {msg}".format + (name=upgradeClass.__name__, msg=error)) raise - logger.log(upgradeClass.__name__ + " upgrade completed", logger.DEBUG) + logger.log(u"{name} upgrade completed".format + (name=upgradeClass.__name__), logger.DEBUG) else: - logger.log(upgradeClass.__name__ + " upgrade not required", logger.DEBUG) + logger.log(u"{name} upgrade not required".format + (name=upgradeClass.__name__), logger.DEBUG) for upgradeSubClass in upgradeClass.__subclasses__(): _processUpgrade(connection, upgradeSubClass) diff --git a/core/nzbToMediaUserScript.py b/core/nzbToMediaUserScript.py index a3a75dac..028a396e 100644 --- a/core/nzbToMediaUserScript.py +++ b/core/nzbToMediaUserScript.py @@ -80,8 +80,8 @@ def external_script(outputDestination, torrentName, torrentLabel, settings): continue cmd = "" for item in command: - cmd = cmd + " " + item - logger.info("Running script {0} on file {1}.".format(cmd, filePath), "USERSCRIPT") + cmd = "{cmd} {item}".format(cmd=cmd, item=item) + logger.info("Running script {cmd} on file {path}.".format(cmd=cmd, path=filePath), "USERSCRIPT") try: p = Popen(command) res = p.wait() diff --git a/core/nzbToMediaUtil.py b/core/nzbToMediaUtil.py index d600eceb..204766a3 100644 --- a/core/nzbToMediaUtil.py +++ b/core/nzbToMediaUtil.py @@ -342,11 +342,12 @@ def rmReadOnly(filename): file_attribute = os.stat(filename)[0] if not file_attribute & stat.S_IWRITE: # File is read-only, so make it writeable - logger.debug('Read only mode on file ' + filename + ' Will try to make it writeable') + logger.debug('Read only mode on file {name}. Attempting to make it writeable'.format + (name=filename)) try: os.chmod(filename, stat.S_IWRITE) except: - logger.warning('Cannot change permissions of ' + filename, logger.WARNING) + logger.warning('Cannot change permissions of {file}'.format(file=filename), logger.WARNING) # Wake function @@ -1156,11 +1157,11 @@ def server_responding(baseURL): def plex_update(category): if core.FAILED: return - if core.PLEXSSL: - url = "https://" - else: - url = "http://" - url = url + core.PLEXHOST + ':' + core.PLEXPORT + '/library/sections/' + url = '{scheme}://{host}:{port}/library/sections/'.format( + scheme='https' if core.PLEXSSL else 'http', + host=core.PLEXHOST, + port=core.PLEXPORT, + ) section = None if not core.PLEXSEC: return @@ -1170,7 +1171,7 @@ def plex_update(category): section = item[1] if section: - url = url + section + '/refresh?X-Plex-Token=' + core.PLEXTOKEN + url = '{url}{section}/refresh?X-Plex-Token={token}'.format(url=url, section=section, token=core.PLEXTOKEN) requests.get(url, timeout=(60, 120), verify=False) logger.debug("Plex Library has been refreshed.", 'PLEX') else: @@ -1180,27 +1181,27 @@ def plex_update(category): def backupVersionedFile(old_file, version): numTries = 0 - new_file = old_file + '.' + 'v' + str(version) + new_file = '{old}.v{version}'.format(old=old_file, version=version) while not os.path.isfile(new_file): if not os.path.isfile(old_file): - logger.log(u"Not creating backup, " + old_file + " doesn't exist", logger.DEBUG) + logger.log(u"Not creating backup, {file} doesn't exist".format(file=old_file), logger.DEBUG) break try: - logger.log(u"Trying to back up " + old_file + " to " + new_file, logger.DEBUG) + logger.log(u"Trying to back up {old} to {new]".format(old=old_file, new=new_file), logger.DEBUG) shutil.copy(old_file, new_file) logger.log(u"Backup done", logger.DEBUG) break - except Exception as e: - logger.log(u"Error while trying to back up " + old_file + " to " + new_file + " : " + str(e), - logger.WARNING) + except Exception as error: + logger.log(u"Error while trying to back up {old} to {new} : {msg}".format + (old=old_file, new=new_file, msg=error), logger.WARNING) numTries += 1 time.sleep(1) logger.log(u"Trying again.", logger.DEBUG) if numTries >= 10: - logger.log(u"Unable to back up " + old_file + " to " + new_file + " please do it manually.", logger.ERROR) + logger.log(u"Unable to back up {old} to {new} please do it manually.".format(old=old_file, new=new_file), logger.ERROR) return False return True @@ -1242,7 +1243,7 @@ class RunningProcess(object): class WindowsProcess(object): def __init__(self): - self.mutexname = "nzbtomedia_" + core.PID_FILE.replace('\\', '/') # {D0E858DF-985E-4907-B7FB-8D732C3FC3B9}" + self.mutexname = "nzbtomedia_{pid}".format(pid=core.PID_FILE.replace('\\', '/')) # {D0E858DF-985E-4907-B7FB-8D732C3FC3B9}" if platform.system() == 'Windows': from win32event import CreateMutex from win32api import CloseHandle, GetLastError @@ -1274,7 +1275,7 @@ class PosixProcess(object): def alreadyrunning(self): try: self.lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) - self.lock_socket.bind('\0' + self.pidpath) + self.lock_socket.bind('\0{path}'.format(path=self.pidpath)) self.lasterror = False return self.lasterror except socket.error as e: diff --git a/core/transcoder/transcoder.py b/core/transcoder/transcoder.py index c5cb43a6..807516f4 100644 --- a/core/transcoder/transcoder.py +++ b/core/transcoder/transcoder.py @@ -129,7 +129,7 @@ def buildCommands(file, newDir, movieName, bitbucket): elif core.CONCAT and re.match("(.+)[cC][dD][0-9]", name): name = re.sub("([\ \.\-\_\=\:]+[cC][dD][0-9])", "", name) if ext == core.VEXTENSION and newDir == dir: # we need to change the name to prevent overwriting itself. - core.VEXTENSION = '-transcoded' + core.VEXTENSION # adds '-transcoded.ext' + core.VEXTENSION = '-transcoded{ext}'.format(ext=core.VEXTENSION) # adds '-transcoded.ext' else: img, data = iteritems(file).next() name = data['name'] @@ -165,7 +165,7 @@ def buildCommands(file, newDir, movieName, bitbucket): if core.VBITRATE: video_cmd.extend(['-b:v', str(core.VBITRATE)]) if core.VRESOLUTION: - video_cmd.extend(['-vf', 'scale=' + core.VRESOLUTION]) + video_cmd.extend(['-vf', 'scale={vres}'.format(vres=core.VRESOLUTION)]) if core.VPRESET: video_cmd.extend(['-preset', core.VPRESET]) if core.VCRF: @@ -222,13 +222,19 @@ def buildCommands(file, newDir, movieName, bitbucket): w_scale = width / float(scale.split(':')[0]) h_scale = height / float(scale.split(':')[1]) if w_scale > h_scale: # widescreen, Scale by width only. - scale = scale.split(':')[0] + ":" + str(int((height / w_scale) / 2) * 2) + scale = "{width}:{height}".format( + width=scale.split(':')[0], + height=int((height / w_scale) / 2) * 2, + ) if w_scale > 1: - video_cmd.extend(['-vf', 'scale=' + scale]) + video_cmd.extend(['-vf', 'scale={width}'.format(width=scale)]) else: # lower or mathcing ratio, scale by height only. - scale = str(int((width / h_scale) / 2) * 2) + ":" + scale.split(':')[1] + scale = "{width}:{height}".format( + width=int((width / h_scale) / 2) * 2, + height=scale.split(':')[1], + ) if h_scale > 1: - video_cmd.extend(['-vf', 'scale=' + scale]) + video_cmd.extend(['-vf', 'scale={height}'.format(height=scale)]) if core.VBITRATE: video_cmd.extend(['-b:v', str(core.VBITRATE)]) if core.VPRESET: @@ -242,7 +248,7 @@ def buildCommands(file, newDir, movieName, bitbucket): video_cmd[1] = core.VCODEC if core.VCODEC == 'copy': # force copy. therefore ignore all other video transcoding. video_cmd = ['-c:v', 'copy'] - map_cmd.extend(['-map', '0:' + str(video["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=video["index"])]) break # Only one video needed used_audio = 0 @@ -259,40 +265,34 @@ def buildCommands(file, newDir, movieName, bitbucket): audio3 = [] if audio2: # right language and codec... - map_cmd.extend(['-map', '0:' + str(audio2[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio2[0]["index"])]) a_mapped.extend([audio2[0]["index"]]) bitrate = int(audio2[0].get("bit_rate", 0)) / 1000 channels = int(audio2[0].get("channels", 0)) - audio_cmd.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd.extend(['-c:a:{0}'.format(used_audio), 'copy']) elif audio1: # right language wrong codec. - map_cmd.extend(['-map', '0:' + str(audio1[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio1[0]["index"])]) a_mapped.extend([audio1[0]["index"]]) bitrate = int(audio1[0].get("bit_rate", 0)) / 1000 channels = int(audio1[0].get("channels", 0)) - if core.ACODEC: - audio_cmd.extend(['-c:a:' + str(used_audio), core.ACODEC]) - else: - audio_cmd.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd.extend(['-c:a:{0}'.format(used_audio), core.ACODEC if core.ACODEC else 'copy']) elif audio3: # just pick the default audio track - map_cmd.extend(['-map', '0:' + str(audio3[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio3[0]["index"])]) a_mapped.extend([audio3[0]["index"]]) bitrate = int(audio3[0].get("bit_rate", 0)) / 1000 channels = int(audio3[0].get("channels", 0)) - if core.ACODEC: - audio_cmd.extend(['-c:a:' + str(used_audio), core.ACODEC]) - else: - audio_cmd.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd.extend(['-c:a:{0}'.format(used_audio), core.ACODEC if core.ACODEC else 'copy']) if core.ACHANNELS and channels and channels > core.ACHANNELS: - audio_cmd.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS)]) + audio_cmd.extend(['-ac:a:{0}'.format(used_audio), str(core.ACHANNELS)]) if audio_cmd[1] == 'copy': audio_cmd[1] = core.ACODEC if core.ABITRATE and not (core.ABITRATE * 0.9 < bitrate < core.ABITRATE * 1.1): - audio_cmd.extend(['-b:a:' + str(used_audio), str(core.ABITRATE)]) + audio_cmd.extend(['-b:a:{0}'.format(used_audio), str(core.ABITRATE)]) if audio_cmd[1] == 'copy': audio_cmd[1] = core.ACODEC if core.OUTPUTQUALITYPERCENT: - audio_cmd.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)]) + audio_cmd.extend(['-q:a:{0}'.format(used_audio), str(core.OUTPUTQUALITYPERCENT)]) if audio_cmd[1] == 'copy': audio_cmd[1] = core.ACODEC if audio_cmd[1] in ['aac', 'dts']: @@ -302,40 +302,40 @@ def buildCommands(file, newDir, movieName, bitbucket): used_audio += 1 audio4 = [item for item in audio1 if item["codec_name"] in core.ACODEC2_ALLOW] if audio4: # right language and codec. - map_cmd.extend(['-map', '0:' + str(audio4[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio4[0]["index"])]) a_mapped.extend([audio4[0]["index"]]) bitrate = int(audio4[0].get("bit_rate", 0)) / 1000 channels = int(audio4[0].get("channels", 0)) - audio_cmd2.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd2.extend(['-c:a:{0}'.format(used_audio), 'copy']) elif audio1: # right language wrong codec. - map_cmd.extend(['-map', '0:' + str(audio1[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio1[0]["index"])]) a_mapped.extend([audio1[0]["index"]]) bitrate = int(audio1[0].get("bit_rate", 0)) / 1000 channels = int(audio1[0].get("channels", 0)) if core.ACODEC2: - audio_cmd2.extend(['-c:a:' + str(used_audio), core.ACODEC2]) + audio_cmd2.extend(['-c:a:{0}'.format(used_audio), core.ACODEC2]) else: - audio_cmd2.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd2.extend(['-c:a:{0}'.format(used_audio), 'copy']) elif audio3: # just pick the default audio track - map_cmd.extend(['-map', '0:' + str(audio3[0]["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio3[0]["index"])]) a_mapped.extend([audio3[0]["index"]]) bitrate = int(audio3[0].get("bit_rate", 0)) / 1000 channels = int(audio3[0].get("channels", 0)) if core.ACODEC2: - audio_cmd2.extend(['-c:a:' + str(used_audio), core.ACODEC2]) + audio_cmd2.extend(['-c:a:{0}'.format(used_audio), core.ACODEC2]) else: - audio_cmd2.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd2.extend(['-c:a:{0}'.format(used_audio), 'copy']) if core.ACHANNELS2 and channels and channels > core.ACHANNELS2: - audio_cmd2.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS2)]) + audio_cmd2.extend(['-ac:a:{0}'.format(used_audio), str(core.ACHANNELS2)]) if audio_cmd2[1] == 'copy': audio_cmd2[1] = core.ACODEC2 if core.ABITRATE2 and not (core.ABITRATE2 * 0.9 < bitrate < core.ABITRATE2 * 1.1): - audio_cmd2.extend(['-b:a:' + str(used_audio), str(core.ABITRATE2)]) + audio_cmd2.extend(['-b:a:{0}'.format(used_audio), str(core.ABITRATE2)]) if audio_cmd2[1] == 'copy': audio_cmd2[1] = core.ACODEC2 if core.OUTPUTQUALITYPERCENT: - audio_cmd2.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)]) + audio_cmd2.extend(['-q:a:{0}'.format(used_audio), str(core.OUTPUTQUALITYPERCENT)]) if audio_cmd2[1] == 'copy': audio_cmd2[1] = core.ACODEC2 if audio_cmd2[1] in ['aac', 'dts']: @@ -347,28 +347,28 @@ def buildCommands(file, newDir, movieName, bitbucket): if audio["index"] in a_mapped: continue used_audio += 1 - map_cmd.extend(['-map', '0:' + str(audio["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=audio["index"])]) audio_cmd3 = [] bitrate = int(audio.get("bit_rate", 0)) / 1000 channels = int(audio.get("channels", 0)) if audio["codec_name"] in core.ACODEC3_ALLOW: - audio_cmd3.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd3.extend(['-c:a:{0}'.format(used_audio), 'copy']) else: if core.ACODEC3: - audio_cmd3.extend(['-c:a:' + str(used_audio), core.ACODEC3]) + audio_cmd3.extend(['-c:a:{0}'.format(used_audio), core.ACODEC3]) else: - audio_cmd3.extend(['-c:a:' + str(used_audio), 'copy']) + audio_cmd3.extend(['-c:a:{0}'.format(used_audio), 'copy']) if core.ACHANNELS3 and channels and channels > core.ACHANNELS3: - audio_cmd3.extend(['-ac:a:' + str(used_audio), str(core.ACHANNELS3)]) + audio_cmd3.extend(['-ac:a:{0}'.format(used_audio), str(core.ACHANNELS3)]) if audio_cmd3[1] == 'copy': audio_cmd3[1] = core.ACODEC3 if core.ABITRATE3 and not (core.ABITRATE3 * 0.9 < bitrate < core.ABITRATE3 * 1.1): - audio_cmd3.extend(['-b:a:' + str(used_audio), str(core.ABITRATE3)]) + audio_cmd3.extend(['-b:a:{0}'.format(used_audio), str(core.ABITRATE3)]) if audio_cmd3[1] == 'copy': audio_cmd3[1] = core.ACODEC3 if core.OUTPUTQUALITYPERCENT > 0: - audio_cmd3.extend(['-q:a:' + str(used_audio), str(core.OUTPUTQUALITYPERCENT)]) + audio_cmd3.extend(['-q:a:{0}'.format(used_audio), str(core.OUTPUTQUALITYPERCENT)]) if audio_cmd3[1] == 'copy': audio_cmd3[1] = core.ACODEC3 if audio_cmd3[1] in ['aac', 'dts']: @@ -386,7 +386,7 @@ def buildCommands(file, newDir, movieName, bitbucket): if core.BURN and not subs1 and not burnt and os.path.isfile(file): for subfile in get_subs(file): if lan in os.path.split(subfile)[1]: - video_cmd.extend(['-vf', 'subtitles=' + subfile]) + video_cmd.extend(['-vf', 'subtitles={subs}'.format(subs=subfile)]) burnt = 1 for sub in subs1: if core.BURN and not burnt and os.path.isfile(inputFile): @@ -395,11 +395,11 @@ def buildCommands(file, newDir, movieName, bitbucket): if subStreams[index]["index"] == sub["index"]: subloc = index break - video_cmd.extend(['-vf', 'subtitles=' + inputFile + ':si=' + str(subloc)]) + video_cmd.extend(['-vf', 'subtitles={sub}:si={loc}'.format(sub=inputFile, loc=subloc)]) burnt = 1 if not core.ALLOWSUBS: break - map_cmd.extend(['-map', '0:' + str(sub["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=sub["index"])]) s_mapped.extend([sub["index"]]) if core.SINCLUDE: @@ -408,7 +408,7 @@ def buildCommands(file, newDir, movieName, bitbucket): break if sub["index"] in s_mapped: continue - map_cmd.extend(['-map', '0:' + str(sub["index"])]) + map_cmd.extend(['-map', '0:{index}'.format(index=sub["index"])]) s_mapped.extend([sub["index"]]) if core.OUTPUTFASTSTART: @@ -430,9 +430,10 @@ def buildCommands(file, newDir, movieName, bitbucket): continue lan = os.path.splitext(os.path.splitext(subfile)[0])[1] command.extend(['-i', subfile]) - meta_cmd.extend(['-metadata:s:s:' + str(len(s_mapped) + n), 'language=' + lan[1:]]) + meta_cmd.extend(['-metadata:s:s:{x}'.format(x=len(s_mapped) + n), + 'language={lang}'.format(lang=lan[1:])]) n += 1 - map_cmd.extend(['-map', str(n) + ':0']) + map_cmd.extend(['-map', '{x}:0'.format(x=n)]) if not core.ALLOWSUBS or (not s_mapped and not n): sub_cmd.extend(['-sn']) @@ -500,8 +501,8 @@ def extract_subs(file, newfilePath, bitbucket): if os.path.isfile(outputFile): outputFile = os.path.join(subdir, "{0}.{1}.{2}.srt".format(name, lan, n)) - command = [core.FFMPEG, '-loglevel', 'warning', '-i', file, '-vn', '-an', '-codec:' + str(idx), 'srt', - outputFile] + command = [core.FFMPEG, '-loglevel', 'warning', '-i', file, '-vn', '-an', + '-codec:{index}'.format(index=idx), 'srt', outputFile] if platform.system() != 'Windows': command = core.NICENESS + command @@ -604,7 +605,9 @@ def ripISO(item, newDir, bitbucket): if core.CONCAT: combined.extend(concat) continue - name = '{0}.cd{1}'.format(os.path.splitext(os.path.split(item)[1])[0], str(n + 1)) + name = '{name}.cd{x}'.format( + name=os.path.splitext(os.path.split(item)[1])[0], x=n + 1 + ) newFiles.append({item: {'name': name, 'files': concat}}) if core.CONCAT: name = os.path.splitext(os.path.split(item)[1])[0] @@ -627,14 +630,14 @@ def combineVTS(vtsPath): while True: vtsName = 'VTS_{0:02d}_{1:d}.VOB'.format(n + 1, m) if os.path.isfile(os.path.join(vtsPath, vtsName)): - concat = concat + os.path.join(vtsPath, vtsName) + '|' + concat += '{file}|'.format(file=os.path.join(vtsPath, vtsName)) m += 1 else: break if not concat: break if core.CONCAT: - combined = combined + concat + '|' + combined += '{files}|'.format(files=concat) continue newFiles.append('concat:{0}'.format(concat[:-1])) if core.CONCAT: @@ -650,7 +653,7 @@ def combineCD(combine): files = [file for file in combine if n + 1 == int(re.match(".+[cC][dD]([0-9]+).", file).groups()[0]) and item in file] if files: - concat = concat + files[0] + '|' + concat += '{file}|'.format(file=files[0]) else: break if concat: @@ -661,7 +664,7 @@ def combineCD(combine): def print_cmd(command): cmd = "" for item in command: - cmd = cmd + " " + str(item) + cmd = "{cmd} {item}".format(cmd=cmd, item=item) logger.debug("calling command:{0}".format(cmd)) diff --git a/core/transmissionrpc/client.py b/core/transmissionrpc/client.py index 04c85ac0..66353762 100644 --- a/core/transmissionrpc/client.py +++ b/core/transmissionrpc/client.py @@ -141,15 +141,14 @@ class Client(object): else: self._query_timeout = DEFAULT_TIMEOUT urlo = urlparse(address) - if urlo.scheme == '': - base_url = 'http://' + address + ':' + str(port) - self.url = base_url + '/transmission/rpc/' + if not urlo.scheme: + self.url = 'http://{host}:{port}/transmission/rpc/'.format(host=address, port=port) else: if urlo.port: - self.url = urlo.scheme + '://' + urlo.hostname + ':' + str(urlo.port) + urlo.path + self.url = '{url.scheme}://{url.hostname}:{url.port}{url.path}'.format(url=urlo) else: - self.url = urlo.scheme + '://' + urlo.hostname + urlo.path - LOGGER.info('Using custom URL "' + self.url + '".') + self.url = '{url.scheme}://{url.hostname}{url.path}'.format(url=urlo) + LOGGER.info('Using custom URL {url!r}.'.format(url=self.url)) if urlo.username and urlo.password: user = urlo.username password = urlo.password @@ -256,7 +255,7 @@ class Client(object): try: data = json.loads(http_data) except ValueError as error: - LOGGER.error('Error: ' + str(error)) + LOGGER.error('Error: {msg}'.format(msg=error)) LOGGER.error('Request: {request!r}'.format(request=query)) LOGGER.error('HTTP data: {data!r}'.format(data=http_data)) raise diff --git a/core/transmissionrpc/utils.py b/core/transmissionrpc/utils.py index 9381edac..cff602ee 100644 --- a/core/transmissionrpc/utils.py +++ b/core/transmissionrpc/utils.py @@ -31,7 +31,7 @@ def format_speed(size): Format bytes per second speed into IEC prefixes, B/s, KiB/s, MiB/s ... """ (size, unit) = format_size(size) - return size, unit + '/s' + return size, '{unit}/s'.format(unit=unit) def format_timedelta(delta): diff --git a/core/utorrent/client.py b/core/utorrent/client.py index f8ddc80d..02c29583 100644 --- a/core/utorrent/client.py +++ b/core/utorrent/client.py @@ -127,7 +127,7 @@ class UTorrentClient(object): def _action(self, params, body=None, content_type=None): # about token, see https://github.com/bittorrent/webui/wiki/TokenSystem - url = self.base_url + '?token=' + self.token + '&' + urlencode(params) + url = '{url}?token={token}&{params}'.format(url=self.url, token=self.token, params=urlencode(params)) request = Request(url) if body: diff --git a/core/utorrent/upload.py b/core/utorrent/upload.py index f8db659c..948e5491 100644 --- a/core/utorrent/upload.py +++ b/core/utorrent/upload.py @@ -38,7 +38,7 @@ class MultiPartForm(object): # Once the list is built, return a string where each # line is separated by '\r\n'. parts = [] - part_boundary = '--' + self.boundary + part_boundary = '--{boundary}'.format(boundary=self.boundary) # Add the form fields parts.extend( @@ -64,6 +64,6 @@ class MultiPartForm(object): # Flatten the list and add closing boundary marker, # then return CR+LF separated data flattened = list(itertools.chain(*parts)) - flattened.append('--' + self.boundary + '--') + flattened.append('--{boundary}--'.format(boundary=self.boundary)) flattened.append('') return '\r\n'.join(flattened) diff --git a/core/versionCheck.py b/core/versionCheck.py index 84e14947..79824df6 100644 --- a/core/versionCheck.py +++ b/core/versionCheck.py @@ -68,7 +68,7 @@ class CheckVersion(object): logger.log(u"Version checking is disabled, not checking for the newest version") return False - logger.log(u"Checking if " + self.install_type + " needs an update") + logger.log(u"Checking if {install} needs an update".format(install=self.install_type)) if not self.updater.need_update(): core.NEWEST_VERSION_STRING = None logger.log(u"No update needed") @@ -113,18 +113,19 @@ class GitUpdateManager(UpdateManager): test_cmd = 'version' if core.GIT_PATH: - main_git = '"' + core.GIT_PATH + '"' + main_git = '"{git}"'.format(git=core.GIT_PATH) else: main_git = 'git' - logger.log(u"Checking if we can use git commands: " + main_git + ' ' + test_cmd, logger.DEBUG) + logger.log(u"Checking if we can use git commands: {git} {cmd}".format + (git=main_git, cmd=test_cmd), logger.DEBUG) output, err, exit_status = self._run_git(main_git, test_cmd) if exit_status == 0: - logger.log(u"Using: " + main_git, logger.DEBUG) + logger.log(u"Using: {git}".format(git=main_git), logger.DEBUG) return main_git else: - logger.log(u"Not using: " + main_git, logger.DEBUG) + logger.log(u"Not using: {git}".format(git=main_git), logger.DEBUG) # trying alternatives @@ -142,18 +143,20 @@ class GitUpdateManager(UpdateManager): logger.log(u"Trying known alternative git locations", logger.DEBUG) for cur_git in alternative_git: - logger.log(u"Checking if we can use git commands: " + cur_git + ' ' + test_cmd, logger.DEBUG) + logger.log(u"Checking if we can use git commands: {git} {cmd}".format + (git=cur_git, cmd=test_cmd), logger.DEBUG) output, err, exit_status = self._run_git(cur_git, test_cmd) if exit_status == 0: - logger.log(u"Using: " + cur_git, logger.DEBUG) + logger.log(u"Using: {git}".format(git=cur_git), logger.DEBUG) return cur_git else: - logger.log(u"Not using: " + cur_git, logger.DEBUG) + logger.log(u"Not using: {git}".format(git=cur_git), logger.DEBUG) # Still haven't found a working git - logger.debug( - 'Unable to find your git executable - Set git_path in your autoProcessMedia.cfg OR delete your .git folder and run from source to enable updates.') + logger.debug('Unable to find your git executable - ' + 'Set git_path in your autoProcessMedia.cfg OR ' + 'delete your .git folder and run from source to enable updates.') return None @@ -167,10 +170,11 @@ class GitUpdateManager(UpdateManager): exit_status = 1 return output, err, exit_status - cmd = git_path + ' ' + args + cmd = '{git} {args}'.format(git=git_path, args=args) try: - logger.log(u"Executing " + cmd + " with your shell in " + core.PROGRAM_DIR, logger.DEBUG) + logger.log(u"Executing {cmd} with your shell in {directory}".format + (cmd=cmd, directory=core.PROGRAM_DIR), logger.DEBUG) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=core.PROGRAM_DIR) output, err = p.communicate() @@ -179,29 +183,23 @@ class GitUpdateManager(UpdateManager): if output: output = output.strip() if core.LOG_GIT: - logger.log(u"git output: " + output, logger.DEBUG) + logger.log(u"git output: {output}".format(output=output), logger.DEBUG) except OSError: - logger.log(u"Command " + cmd + " didn't work") + logger.log(u"Command {cmd} didn't work".format(cmd=cmd)) exit_status = 1 + exit_status = 128 if ('fatal:' in output) or err else exit_status if exit_status == 0: - logger.log(cmd + u" : returned successful", logger.DEBUG) + logger.log(u"{cmd} : returned successful".format(cmd=cmd), logger.DEBUG) exit_status = 0 - - elif exit_status == 1: - if core.LOG_GIT: - logger.log(cmd + u" returned : " + output, logger.DEBUG) - exit_status = 1 - - elif exit_status == 128 or 'fatal:' in output or err: - if core.LOG_GIT: - logger.log(cmd + u" returned : " + output, logger.DEBUG) - exit_status = 128 - + elif core.LOG_GIT and exit_status in (1, 128): + logger.log(u"{cmd} returned : {output}".format + (cmd=cmd, output=output), logger.DEBUG) else: if core.LOG_GIT: - logger.log(cmd + u" returned : " + output + u", treat as error for now", logger.DEBUG) + logger.log(u"{cmd} returned : {output}, treat as error for now".format + (cmd=cmd, output=output), logger.DEBUG) exit_status = 1 return output, err, exit_status @@ -285,21 +283,18 @@ class GitUpdateManager(UpdateManager): logger.log(u"git didn't return numbers for behind and ahead, not using it", logger.DEBUG) return - logger.log( - u"cur_commit = " + str(self._cur_commit_hash) + u" % (newest_commit)= " + str(self._newest_commit_hash) + - u", num_commits_behind = " + str(self._num_commits_behind) + u", num_commits_ahead = " + - str(self._num_commits_ahead), logger.DEBUG) + logger.log(u"cur_commit = {current} % (newest_commit)= {new}, " + u"num_commits_behind = {x}, num_commits_ahead = {y}".format + (current=self._cur_commit_hash, new=self._newest_commit_hash, + x=self._num_commits_behind, y=self._num_commits_ahead), logger.DEBUG) def set_newest_text(self): if self._num_commits_ahead: - logger.log(u"Local branch is ahead of " + self.branch + ". Automatic update not possible.", logger.ERROR) - elif self._num_commits_behind > 0: - newest_text = 'There is a newer version available ' - newest_text += " (you're " + str(self._num_commits_behind) + " commit" - if self._num_commits_behind > 1: - newest_text += 's' - newest_text += ' behind)' - logger.log(newest_text, logger.MESSAGE) + logger.log(u"Local branch is ahead of {branch}. Automatic update not possible.".format + (branch=self.branch), logger.ERROR) + elif self._num_commits_behind: + logger.log(u"There is a newer version available (you're {x} commit{s} behind)".format + (x=self._num_commits_behind, s=u's' if self._num_commits_behind > 1 else u''), logger.MESSAGE) else: return @@ -313,8 +308,8 @@ class GitUpdateManager(UpdateManager): else: try: self._check_github_for_update() - except Exception as e: - logger.log(u"Unable to contact github, can't check for update: " + repr(e), logger.ERROR) + except Exception as error: + logger.log(u"Unable to contact github, can't check for update: {msg!r}".format(msg=error), logger.ERROR) return False if self._num_commits_behind > 0: @@ -328,7 +323,7 @@ class GitUpdateManager(UpdateManager): on the call's success. """ - output, err, exit_status = self._run_git(self._git_path, 'pull origin ' + self.branch) # @UnusedVariable + output, err, exit_status = self._run_git(self._git_path, 'pull origin {branch}'.format(branch=self.branch)) # @UnusedVariable if exit_status == 0: return True @@ -357,8 +352,8 @@ class SourceUpdateManager(UpdateManager): try: with open(version_file, 'r') as fp: self._cur_commit_hash = fp.read().strip(' \n\r') - except EnvironmentError as e: - logger.log(u"Unable to open 'version.txt': " + str(e), logger.DEBUG) + except EnvironmentError as error: + logger.log(u"Unable to open 'version.txt': {msg}".format(msg=error), logger.DEBUG) if not self._cur_commit_hash: self._cur_commit_hash = None @@ -371,8 +366,8 @@ class SourceUpdateManager(UpdateManager): try: self._check_github_for_update() - except Exception as e: - logger.log(u"Unable to contact github, can't check for update: " + repr(e), logger.ERROR) + except Exception as error: + logger.log(u"Unable to contact github, can't check for update: {msg!r}".format(msg=error), logger.ERROR) return False if not self._cur_commit_hash or self._num_commits_behind > 0: @@ -418,9 +413,8 @@ class SourceUpdateManager(UpdateManager): # when _cur_commit_hash doesn't match anything _num_commits_behind == 100 self._num_commits_behind += 1 - logger.log( - u"cur_commit = " + str(self._cur_commit_hash) + u" % (newest_commit)= " + str(self._newest_commit_hash) + - u", num_commits_behind = " + str(self._num_commits_behind), logger.DEBUG) + logger.log(u"cur_commit = {current} % (newest_commit)= {new}, num_commits_behind = {x}".format + (current=self._cur_commit_hash, new=self._newest_commit_hash, x=self._num_commits_behind), logger.DEBUG) def set_newest_text(self): @@ -430,12 +424,8 @@ class SourceUpdateManager(UpdateManager): if not self._cur_commit_hash: logger.log(u"Unknown current version number, don't know if we should update or not", logger.ERROR) elif self._num_commits_behind > 0: - newest_text = 'There is a newer version available' - newest_text += " (you're " + str(self._num_commits_behind) + " commit" - if self._num_commits_behind > 1: - newest_text += "s" - newest_text += " behind)" - logger.log(newest_text, logger.MESSAGE) + logger.log(u"There is a newer version available (you're {x} commit{s} behind)".format + (x=self._num_commits_behind, s=u's' if self._num_commits_behind > 1 else u''), logger.MESSAGE) else: return @@ -443,8 +433,8 @@ class SourceUpdateManager(UpdateManager): """ Downloads the latest source tarball from github and installs it over the existing version. """ - base_url = 'https://github.com/' + self.github_repo_user + '/' + self.github_repo - tar_download_url = base_url + '/tarball/' + self.branch + tar_download_url = 'https://github.com/{org}/{repo}/tarball/{branch}'.format( + org=self.github_repo_user, repo=self.github_repo, branch=self.branch) version_path = os.path.join(core.PROGRAM_DIR, u'version.txt') try: @@ -452,45 +442,48 @@ class SourceUpdateManager(UpdateManager): sb_update_dir = os.path.join(core.PROGRAM_DIR, u'sb-update') if os.path.isdir(sb_update_dir): - logger.log(u"Clearing out update folder " + sb_update_dir + " before extracting") + logger.log(u"Clearing out update folder {dir} before extracting".format(dir=sb_update_dir)) shutil.rmtree(sb_update_dir) - logger.log(u"Creating update folder " + sb_update_dir + " before extracting") + logger.log(u"Creating update folder {dir} before extracting".format(dir=sb_update_dir)) os.makedirs(sb_update_dir) # retrieve file - logger.log(u"Downloading update from " + repr(tar_download_url)) + logger.log(u"Downloading update from {url!r}".format(url=tar_download_url)) tar_download_path = os.path.join(sb_update_dir, u'nzbtomedia-update.tar') urllib.urlretrieve(tar_download_url, tar_download_path) if not os.path.isfile(tar_download_path): - logger.log(u"Unable to retrieve new version from " + tar_download_url + ", can't update", logger.ERROR) + logger.log(u"Unable to retrieve new version from {url}, can't update".format + (url=tar_download_url), logger.ERROR) return False if not tarfile.is_tarfile(tar_download_path): - logger.log(u"Retrieved version from " + tar_download_url + " is corrupt, can't update", logger.ERROR) + logger.log(u"Retrieved version from {url} is corrupt, can't update".format + (url=tar_download_url), logger.ERROR) return False # extract to sb-update dir - logger.log(u"Extracting file " + tar_download_path) + logger.log(u"Extracting file {path}".format(path=tar_download_path)) tar = tarfile.open(tar_download_path) tar.extractall(sb_update_dir) tar.close() # delete .tar.gz - logger.log(u"Deleting file " + tar_download_path) + logger.log(u"Deleting file {path}".format(path=tar_download_path)) os.remove(tar_download_path) # find update dir name update_dir_contents = [x for x in os.listdir(sb_update_dir) if os.path.isdir(os.path.join(sb_update_dir, x))] if len(update_dir_contents) != 1: - logger.log(u"Invalid update data, update failed: " + str(update_dir_contents), logger.ERROR) + logger.log(u"Invalid update data, update failed: {0}".format(update_dir_contents), logger.ERROR) return False content_dir = os.path.join(sb_update_dir, update_dir_contents[0]) # walk temp folder and move files to main folder - logger.log(u"Moving files from " + content_dir + " to " + core.PROGRAM_DIR) + logger.log(u"Moving files from {source} to {destination}".format + (source=content_dir, destination=core.PROGRAM_DIR)) for dirname, dirnames, filenames in os.walk(content_dir): # @UnusedVariable dirname = dirname[len(content_dir) + 1:] for curfile in filenames: @@ -505,8 +498,9 @@ class SourceUpdateManager(UpdateManager): os.chmod(new_path, stat.S_IWRITE) os.remove(new_path) os.renames(old_path, new_path) - except Exception as e: - logger.log(u"Unable to update " + new_path + ': ' + str(e), logger.DEBUG) + except Exception as error: + logger.log(u"Unable to update {path}: {msg}".format + (path=new_path, msg=error), logger.DEBUG) os.remove(old_path) # Trash the updated file without moving in new path continue @@ -518,13 +512,15 @@ class SourceUpdateManager(UpdateManager): try: with open(version_path, 'w') as ver_file: ver_file.write(self._newest_commit_hash) - except EnvironmentError as e: - logger.log(u"Unable to write version file, update not complete: " + str(e), logger.ERROR) + except EnvironmentError as error: + logger.log(u"Unable to write version file, update not complete: {msg}".format + (msg=error), logger.ERROR) return False - except Exception as e: - logger.log(u"Error while trying to update: " + str(e), logger.ERROR) - logger.log(u"Traceback: " + traceback.format_exc(), logger.DEBUG) + except Exception as error: + logger.log(u"Error while trying to update: {msg}".format + (msg=error), logger.ERROR) + logger.log(u"Traceback: {error}".format(error=traceback.format_exc()), logger.DEBUG) return False return True diff --git a/nzbToMedia.py b/nzbToMedia.py index a3e6363c..8be0110b 100755 --- a/nzbToMedia.py +++ b/nzbToMedia.py @@ -758,8 +758,8 @@ def main(args, section=None): os.path.basename(dirName)) ) - clientAgent = str(core.DOWNLOADINFO[0].get('client_agent', '')) - download_id = str(core.DOWNLOADINFO[0].get('input_id', '')) + clientAgent = text_type(core.DOWNLOADINFO[0].get('client_agent', '')) + download_id = text_type(core.DOWNLOADINFO[0].get('input_id', '')) if clientAgent and clientAgent.lower() not in core.NZB_CLIENTS: continue From c5b60adb33d091a57dd9bb7139baaeb0929ddb86 Mon Sep 17 00:00:00 2001 From: labrys Date: Mon, 6 Jun 2016 04:22:38 -0400 Subject: [PATCH 10/10] Fix spelling --- TorrentToMedia.py | 4 ++-- core/transcoder/transcoder.py | 2 +- nzbToCouchPotato.py | 6 +++--- nzbToMylar.py | 2 +- nzbToNzbDrone.py | 8 ++++---- nzbToSickBeard.py | 8 ++++---- 6 files changed, 15 insertions(+), 15 deletions(-) diff --git a/TorrentToMedia.py b/TorrentToMedia.py index ad61a6a2..2b0ef0c7 100755 --- a/TorrentToMedia.py +++ b/TorrentToMedia.py @@ -94,7 +94,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, if clientAgent != 'manual': core.pause_torrent(clientAgent, inputHash, inputID, inputName) - # Incase input is not directory, make sure to create one. + # 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) @@ -170,7 +170,7 @@ def processTorrent(inputDirectory, inputName, inputCategory, inputHash, inputID, 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 - logger.debug("Found file {0} with date modifed/created less than 5 minutes ago.".format(fullFileName)) + logger.debug("Found file {0} with date modified/created less than 5 minutes ago.".format(fullFileName)) else: continue # This file has not been recently moved or created, skip it diff --git a/core/transcoder/transcoder.py b/core/transcoder/transcoder.py index 807516f4..3356c6ef 100644 --- a/core/transcoder/transcoder.py +++ b/core/transcoder/transcoder.py @@ -228,7 +228,7 @@ def buildCommands(file, newDir, movieName, bitbucket): ) if w_scale > 1: video_cmd.extend(['-vf', 'scale={width}'.format(width=scale)]) - else: # lower or mathcing ratio, scale by height only. + else: # lower or matching ratio, scale by height only. scale = "{width}:{height}".format( width=int((width / h_scale) / 2) * 2, height=scale.split(':')[1], diff --git a/nzbToCouchPotato.py b/nzbToCouchPotato.py index 8b8f7b46..32416471 100755 --- a/nzbToCouchPotato.py +++ b/nzbToCouchPotato.py @@ -134,7 +134,7 @@ # create a duplicate, or replace the original (0, 1). # -# set to 1 to cretae a new file or 0 to replace the original +# set to 1 to create a new file or 0 to replace the original # duplicate=1 # ignore extensions. @@ -169,12 +169,12 @@ # allSubLanguages (0,1). # -# allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. +# allSubLanguages. 1 will keep all existing sub languages. 0 will discard those not in your list above. # allSubLanguages=0 # embedSubs (0,1). # -# embedSubs. 1 will embded external sub/srt subs into your video if this is supported. +# embedSubs. 1 will embed external sub/srt subs into your video if this is supported. # embedSubs=1 # burnInSubtitle (0,1). diff --git a/nzbToMylar.py b/nzbToMylar.py index eba87a71..5d566123 100755 --- a/nzbToMylar.py +++ b/nzbToMylar.py @@ -35,7 +35,7 @@ # Mylar host. # -# The ipaddress for your Mylar server. e.g For the Same system use localhost or 127.0.0.1 +# The ip address for your Mylar server. e.g For the Same system use localhost or 127.0.0.1 # myhost=localhost # Mylar port. diff --git a/nzbToNzbDrone.py b/nzbToNzbDrone.py index ac2e6d5f..549bb9e3 100755 --- a/nzbToNzbDrone.py +++ b/nzbToNzbDrone.py @@ -39,7 +39,7 @@ # NzbDrone host. # -# The ipaddress for your NzbDrone/Sonarr server. e.g For the Same system use localhost or 127.0.0.1 +# The ip address for your NzbDrone/Sonarr server. e.g For the Same system use localhost or 127.0.0.1 # ndhost=localhost # NzbDrone port. @@ -124,7 +124,7 @@ # create a duplicate, or replace the original (0, 1). # -# set to 1 to cretae a new file or 0 to replace the original +# set to 1 to create a new file or 0 to replace the original # duplicate=1 # ignore extensions. @@ -159,12 +159,12 @@ # allSubLanguages (0,1). # -# allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. +# allSubLanguages. 1 will keep all existing sub languages. 0 will discard those not in your list above. # allSubLanguages = 0 # embedSubs (0,1). # -# embedSubs. 1 will embded external sub/srt subs into your video if this is supported. +# embedSubs. 1 will embed external sub/srt subs into your video if this is supported. # embedSubs = 1 # burnInSubtitle (0,1). diff --git a/nzbToSickBeard.py b/nzbToSickBeard.py index 92474ea5..5a0a03a6 100755 --- a/nzbToSickBeard.py +++ b/nzbToSickBeard.py @@ -39,7 +39,7 @@ # SickBeard host. # -# The ipaddress for your SickBeard/SickRage server. e.g For the Same system use localhost or 127.0.0.1 +# The ip address for your SickBeard/SickRage server. e.g For the Same system use localhost or 127.0.0.1 # sbhost=localhost # SickBeard port. @@ -137,7 +137,7 @@ # create a duplicate, or replace the original (0, 1). # -# set to 1 to cretae a new file or 0 to replace the original +# set to 1 to create a new file or 0 to replace the original # duplicate=1 # ignore extensions. @@ -172,12 +172,12 @@ # allSubLanguages (0,1). # -# allSubLanguages. 1 will keep all exisiting sub languages. 0 will discare those not in your list above. +# allSubLanguages. 1 will keep all existing sub languages. 0 will discard those not in your list above. # allSubLanguages=0 # embedSubs (0,1). # -# embedSubs. 1 will embded external sub/srt subs into your video if this is supported. +# embedSubs. 1 will embed external sub/srt subs into your video if this is supported. # embedSubs=1 # burnInSubtitle (0,1).