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