diff --git a/gui/slick/views/config_notifications.mako b/gui/slick/views/config_notifications.mako index e49efd49f2ede01d58fe12429980f02719034957..69f41f94d3ea1f41285f0afa1ca61469978525ea 100644 --- a/gui/slick/views/config_notifications.mako +++ b/gui/slick/views/config_notifications.mako @@ -409,7 +409,7 @@ <div class="field-pair"> <label for="nmj_database"> <span class="component-title">NMJ database</span> - <input type="text" name="nmj_database" id="nmj_database" value="${sickbeard.NMJ_DATABASE}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJ_DATABASE == True]}/> + <input type="text" name="nmj_database" id="nmj_database" value="${sickbeard.NMJ_DATABASE}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJ_DATABASE is True]}/> </label> <label> <span class="component-title"> </span> @@ -419,7 +419,7 @@ <div class="field-pair"> <label for="nmj_mount"> <span class="component-title">NMJ mount url</span> - <input type="text" name="nmj_mount" id="nmj_mount" value="${sickbeard.NMJ_MOUNT}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJ_MOUNT == True]}/> + <input type="text" name="nmj_mount" id="nmj_mount" value="${sickbeard.NMJ_MOUNT}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJ_MOUNT is True]}/> </label> <label> <span class="component-title"> </span> @@ -506,7 +506,7 @@ <div class="field-pair"> <label for="nmjv2_database"> <span class="component-title">NMJv2 database</span> - <input type="text" name="nmjv2_database" id="nmjv2_database" value="${sickbeard.NMJv2_DATABASE}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJv2_DATABASE == True]}/> + <input type="text" name="nmjv2_database" id="nmjv2_database" value="${sickbeard.NMJv2_DATABASE}" class="form-control input-sm input250" ${(' readonly="readonly"', '')[sickbeard.NMJv2_DATABASE is True]}/> </label> <label> <span class="component-title"> </span> diff --git a/gui/slick/views/config_providers.mako b/gui/slick/views/config_providers.mako index 9585ef0ab7ba865e29c61aa638ce5b1a91d2cc86..45d91fe3aa20435e354705587304c11d90150598 100644 --- a/gui/slick/views/config_providers.mako +++ b/gui/slick/views/config_providers.mako @@ -78,7 +78,7 @@ $('#config-components').tabs(); curName = curProvider.getID() %> <li class="ui-state-default ${('nzb-provider', 'torrent-provider')[bool(curProvider.providerType == "torrent")]}" id="${curName}"> - <input type="checkbox" id="enable_${curName}" class="provider_enabler" ${('', 'checked="checked"')[curProvider.isEnabled() == True]}/> + <input type="checkbox" id="enable_${curName}" class="provider_enabler" ${('', 'checked="checked"')[curProvider.isEnabled() is True]}/> <a href="${anon_url(curProvider.url)}" class="imgLink" rel="noreferrer" onclick="window.open(this.href, '_blank'); return false;"><img src="${srRoot}/images/providers/${curProvider.imageName()}" alt="${curProvider.name}" title="${curProvider.name}" width="16" height="16" style="vertical-align:middle;"/></a> <span style="vertical-align:middle;">${curProvider.name}</span> ${('*', '')[bool(curProvider.supportsBacklog)]} diff --git a/gui/slick/views/config_search.mako b/gui/slick/views/config_search.mako index 8beab44b50b58c03bfb4e521465188ef95c2a202..61e3054dfd68e15001d3933a3efe8f28235f4c52 100644 --- a/gui/slick/views/config_search.mako +++ b/gui/slick/views/config_search.mako @@ -318,7 +318,7 @@ </label> </div> - % if sickbeard.ALLOW_HIGH_PRIORITY == True: + % if sickbeard.ALLOW_HIGH_PRIORITY is True: <div class="field-pair"> <label for="sab_forced"> <span class="component-title">Use forced priority</span> diff --git a/gui/slick/views/config_subtitles.mako b/gui/slick/views/config_subtitles.mako index d18355fa469062f1e0019b15f844db836b41fcf0..3ac9a04d0896cc96cb02db269dd40aacb915b6f9 100644 --- a/gui/slick/views/config_subtitles.mako +++ b/gui/slick/views/config_subtitles.mako @@ -162,7 +162,7 @@ $('#subtitles_dir').fileBrowser({ title: 'Select Subtitles Download Directory' } <ul id="service_order_list"> % for curService in sickbeard.subtitles.sortedServiceList(): <li class="ui-state-default" id="${curService['name']}"> - <input type="checkbox" id="enable_${curService['name']}" class="service_enabler" ${('', 'checked="checked"')[curService['enabled'] == True]}/> + <input type="checkbox" id="enable_${curService['name']}" class="service_enabler" ${('', 'checked="checked"')[curService['enabled'] is True]}/> <a href="${anon_url(curService['url'])}" class="imgLink" target="_new"> <img src="${srRoot}/images/subtitles/${curService['image']}" alt="${curService['url']}" title="${curService['url']}" width="16" height="16" style="vertical-align:middle;"/> </a> diff --git a/gui/slick/views/displayShow.mako b/gui/slick/views/displayShow.mako index b8da99c0f5e6a59ac9ade423dcac79608dac2e51..23fd582196121cf9e83f8f05437af381a446130d 100644 --- a/gui/slick/views/displayShow.mako +++ b/gui/slick/views/displayShow.mako @@ -334,7 +334,7 @@ <tr style="height: 60px;"> <th class="row-seasonheader displayShowTable" colspan="13" style="vertical-align: bottom; width: auto;"> <h3 style="display: inline;"><a name="season-${epResult["season"]}"></a>${("Specials", "Season " + str(epResult["season"]))[int(epResult["season"]) > 0]}</h3> - % if sickbeard.DISPLAY_ALL_SEASONS == False: + % if sickbeard.DISPLAY_ALL_SEASONS is False: <button id="showseason-${epResult['season']}" type="button" class="btn btn-xs pull-right" data-toggle="collapse" data-target="#collapseSeason-${epResult['season']}">Show Episodes</button> <script type="text/javascript"> $(function() { @@ -374,7 +374,7 @@ <tr style="height: 60px;"> <th class="row-seasonheader displayShowTable" colspan="13" style="vertical-align: bottom; width: auto;"> <h3 style="display: inline;"><a name="season-${epResult["season"]}"></a>${("Specials", "Season " + str(epResult["season"]))[bool(int(epResult["season"]))]}</h3> - % if sickbeard.DISPLAY_ALL_SEASONS == False: + % if sickbeard.DISPLAY_ALL_SEASONS is False: <button id="showseason-${epResult['season']}" type="button" class="btn btn-xs pull-right" data-toggle="collapse" data-target="#collapseSeason-${epResult['season']}">Show Episodes</button> <script type="text/javascript"> $(function() { @@ -410,7 +410,7 @@ </tr> % endif </tbody> - % if sickbeard.DISPLAY_ALL_SEASONS == False: + % if sickbeard.DISPLAY_ALL_SEASONS is False: <tbody class="collapse${("", " in")[curSeason == -1]}" id="collapseSeason-${epResult['season']}"> % else: <tbody> @@ -428,7 +428,7 @@ <td align="center"> <% text = str(epResult['episode']) - if epLoc != '' and epLoc != None: + if epLoc != '' and epLoc is not None: text = '<span title="' + epLoc + '" class="addQTip">' + text + "</span>" %> ${text} @@ -459,7 +459,7 @@ style="padding: 0; text-align: center; max-width: 60px;" /> </td> <td class="col-name"> - % if epResult["description"] != "" and epResult["description"] != None: + % if epResult["description"] != "" and epResult["description"] is not None: <img src="${srRoot}/images/info32.png" width="16" height="16" class="plotInfo" alt="" id="plot_info_${str(show.indexerid)}_${str(epResult["season"])}_${str(epResult["episode"])}" /> % else: <img src="${srRoot}/images/info32.png" width="16" height="16" class="plotInfoNone" alt="" /> diff --git a/gui/slick/views/editShow.mako b/gui/slick/views/editShow.mako index b1901f664591d2fde71c109595223dd1e0fd51cd..299168570c6e184e613eb6e108dfe120d375dc2f 100644 --- a/gui/slick/views/editShow.mako +++ b/gui/slick/views/editShow.mako @@ -106,7 +106,7 @@ <label for="subtitles"> <span class="component-title">Subtitles</span> <span class="component-desc"> - <input type="checkbox" id="subtitles" name="subtitles" ${('', 'checked="checked"')[show.subtitles == 1 and sickbeard.USE_SUBTITLES == True]} ${('disabled="disabled"', '')[bool(sickbeard.USE_SUBTITLES)]}/> search for subtitles + <input type="checkbox" id="subtitles" name="subtitles" ${('', 'checked="checked"')[show.subtitles == 1 and sickbeard.USE_SUBTITLES is True]} ${('disabled="disabled"', '')[bool(sickbeard.USE_SUBTITLES)]}/> search for subtitles </span> </label> </div> diff --git a/gui/slick/views/history.mako b/gui/slick/views/history.mako index 8f9de80b3a77af59b13c1a3c22e72b6a34d08403..8895b5b044e84ddc132f883bc49daa0c6fe38929 100644 --- a/gui/slick/views/history.mako +++ b/gui/slick/views/history.mako @@ -87,7 +87,7 @@ % if hItem["provider"] > 0: % if curStatus in [SNATCHED, FAILED]: <% provider = providers.getProviderClass(generic.GenericProvider.makeID(hItem["provider"])) %> - % if provider != None: + % if provider is not None: <img src="${srRoot}/images/providers/${provider.imageName()}" width="16" height="16" style="vertical-align:middle;" /> <span style="vertical-align:middle;">${provider.name}</span> % else: <img src="${srRoot}/images/providers/missing.png" width="16" height="16" style="vertical-align:middle;" title="missing provider"/> <span style="vertical-align:middle;">Missing Provider</span> @@ -142,7 +142,7 @@ <% curStatus, curQuality = Quality.splitCompositeStatus(int(action["action"])) %> % if curStatus in [SNATCHED, FAILED]: <% provider = providers.getProviderClass(generic.GenericProvider.makeID(action["provider"])) %> - % if provider != None: + % if provider is not None: <img src="${srRoot}/images/providers/${provider.imageName()}" width="16" height="16" style="vertical-align:middle;" alt="${provider.name}" style="cursor: help;" title="${provider.name}: ${os.path.basename(action["resource"])}"/> % else: <img src="${srRoot}/images/providers/missing.png" width="16" height="16" style="vertical-align:middle;" alt="missing provider" title="missing provider"/> diff --git a/gui/slick/views/home.mako b/gui/slick/views/home.mako index cf048477e967e2936b383f92d7ad1c788939f3d3..431137155ad592f82290d61f807952451c1ea06e 100644 --- a/gui/slick/views/home.mako +++ b/gui/slick/views/home.mako @@ -72,7 +72,7 @@ <div id="${('container', 'container-anime')[curListType == 'Anime' and sickbeard.HOME_LAYOUT == 'poster']}" class="clearfix"> <div class="posterview"> % for curLoadingShow in sickbeard.showQueueScheduler.action.loadingShowList: - % if curLoadingShow.show == None: + % if curLoadingShow.show is None: <div class="show-container" data-name="0" data-date="010101" data-network="0" data-progress="101"> <img alt="" title="${curLoadingShow.show_name}" class="show-image" style="border-bottom: 1px solid #111;" src="${srRoot}/images/poster.png" /> <div class="show-details"> @@ -249,14 +249,14 @@ <tbody class="tablesorter-infoOnly"> % for curLoadingShow in sickbeard.showQueueScheduler.action.loadingShowList: - % if curLoadingShow.show != None and curLoadingShow.show in sickbeard.showList: + % if curLoadingShow.show is not None and curLoadingShow.show in sickbeard.showList: <% continue %> % endif <tr> <td align="center">(loading)</td> <td></td> <td> - % if curLoadingShow.show == None: + % if curLoadingShow.show is None: <span title="">Loading... (${curLoadingShow.show_name})</span> % else: <a href="displayShow?show=${curLoadingShow.show.indexerid}">${curLoadingShow.show.name}</a> diff --git a/gui/slick/views/home_addShows.mako b/gui/slick/views/home_addShows.mako index 16da9f75c1dac61cf22c99dbb32ae7c387ede771..a42f588421e63b2d443f5d2360babae47b8f3141 100644 --- a/gui/slick/views/home_addShows.mako +++ b/gui/slick/views/home_addShows.mako @@ -21,7 +21,7 @@ </a> <br><br> - % if sickbeard.USE_TRAKT == True: + % if sickbeard.USE_TRAKT is True: <a href="${srRoot}/home/addShows/trendingShows/" id="btnNewShow" class="btn btn-large"> <div class="button"><div class="icon-addtrendingshow"></div></div> <div class="buttontext"> diff --git a/gui/slick/views/inc_defs.mako b/gui/slick/views/inc_defs.mako index eaa54116836d691c2ff9eecc16cf25c501a2f502..f8ff29646e906f4cc13b9d163d4f77cec5711fe6 100644 --- a/gui/slick/views/inc_defs.mako +++ b/gui/slick/views/inc_defs.mako @@ -42,7 +42,7 @@ cssClass = "Custom" qualityString = "Custom" - if overrideClass == None: + if overrideClass is None: cssClass = "quality " + cssClass else: cssClass = overrideClass diff --git a/gui/slick/views/layouts/main.mako b/gui/slick/views/layouts/main.mako index 10e5c24fd70ef57636f3e748249078c8e6664059..19fcb9965b463ad3cd2721cec972f892edd7e1da 100644 --- a/gui/slick/views/layouts/main.mako +++ b/gui/slick/views/layouts/main.mako @@ -220,7 +220,7 @@ <li><a href="${srRoot}/home/updateCheck?pid=${sbPID}"><i class="menu-icon-update"></i> Check For Updates</a></li> <li><a href="${srRoot}/home/restart/?pid=${sbPID}" class="confirm restart"><i class="menu-icon-restart"></i> Restart</a></li> <li><a href="${srRoot}/home/shutdown/?pid=${sbPID}" class="confirm shutdown"><i class="menu-icon-shutdown"></i> Shutdown</a></li> - % if srLogin != True: + % if srLogin is not True: <li><a href="${srRoot}/logout" class="confirm logout"><i class="menu-icon-shutdown"></i> Logout</a></li> % endif <li role="separator" class="divider"></li> diff --git a/gui/slick/views/manage_failedDownloads.mako b/gui/slick/views/manage_failedDownloads.mako index bac45ec04062b86ec34972a6f6ae6754fe47775e..920e04f8a3054b4f2b94905664d58b7079af0821 100644 --- a/gui/slick/views/manage_failedDownloads.mako +++ b/gui/slick/views/manage_failedDownloads.mako @@ -54,7 +54,7 @@ </td> <td align="center"> <% provider = providers.getProviderClass(generic.GenericProvider.makeID(hItem["provider"])) %> - % if provider != None: + % if provider is not None: <img src="${srRoot}/images/providers/${provider.imageName()}" width="16" height="16" alt="${provider.name}" title="${provider.name}"/> % else: <img src="${srRoot}/images/providers/missing.png" width="16" height="16" alt="missing provider" title="missing provider"/> diff --git a/gui/slick/views/manage_massEdit.mako b/gui/slick/views/manage_massEdit.mako index 7d44bb7c46aeb6a570269ba9256007ffd17a8a80..0892016a97e75f1e78b853719456eb3d2fefc9cf 100644 --- a/gui/slick/views/manage_massEdit.mako +++ b/gui/slick/views/manage_massEdit.mako @@ -9,7 +9,7 @@ <%block name="scripts"> <% - if quality_value != None: + if quality_value is not None: initial_quality = int(quality_value) else: initial_quality = common.SD @@ -90,7 +90,7 @@ <span class="component-title">Preferred Quality</span> <span class="component-desc"> <% - if quality_value != None: + if quality_value is not None: initial_quality = int(quality_value) else: initial_quality = common.SD @@ -101,7 +101,7 @@ <select id="qualityPreset" name="quality_preset" class="form-control form-control-inline input-sm"> <option value="keep">< Keep ></option> <% selected = None %> - <option value="0" ${('', 'selected="selected"')[quality_value != None and quality_value not in common.qualityPresets]}>Custom</option> + <option value="0" ${('', 'selected="selected"')[quality_value is not None and quality_value not in common.qualityPresets]}>Custom</option> % for curPreset in sorted(common.qualityPresets): <option value="${curPreset}" ${('', 'selected="selected"')[quality_value == curPreset]}>${common.qualityPresetStrings[curPreset]}</option> % endfor @@ -137,9 +137,9 @@ <span class="component-title">Archive on first match</span> <span class="component-desc"> <select id="edit_archive_firstmatch" name="archive_firstmatch" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[archive_firstmatch_value == None]}>< Keep ></option> - <option value="enable" ${('', 'selected="selected"')[archive_firstmatch_value == 1]}>Yes</option> - <option value="disable" ${('', 'selected="selected"')[archive_firstmatch_value == 0]}>No</option> + <option value="keep" ${('', 'selected="selected"')[archive_firstmatch_value is None]}>< Keep ></option> + <option value="enable" ${('', 'selected="selected"')[archive_firstmatch_value is 1]}>Yes</option> + <option value="disable" ${('', 'selected="selected"')[archive_firstmatch_value is 0]}>No</option> </select><br> Archive episode after the first best match is found from your archive quality list. </span> @@ -151,7 +151,7 @@ <span class="component-title">Season folders (<span class="separator">*</span>)</span> <span class="component-desc"> <select id="" name="flatten_folders" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[flatten_folders_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[flatten_folders_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[flatten_folders_value == 0]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[flatten_folders_value == 1]}>No</option> </select><br> @@ -165,7 +165,7 @@ <span class="component-title">Paused</span> <span class="component-desc"> <select id="edit_paused" name="paused" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[paused_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[paused_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[paused_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[paused_value == 0]}>No</option> </select><br/ > @@ -194,7 +194,7 @@ <span class="component-title">Scene Numbering</span> <span class="component-desc"> <select id="edit_scene" name="scene" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[scene_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[scene_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[scene_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[scene_value == 0]}>No</option> </select><br> @@ -208,7 +208,7 @@ <span class="component-title">Anime</span> <span class="component-desc"> <select id="edit_anime" name="anime" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[anime_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[anime_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[anime_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[anime_value == 0]}>No</option> </select><br> @@ -222,7 +222,7 @@ <span class="component-title">Sports</span> <span class="component-desc"> <select id="edit_sports" name="sports" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[sports_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[sports_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[sports_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[sports_value == 0]}>No</option> </select><br> @@ -237,7 +237,7 @@ <span class="component-title">Air by date</span> <span class="component-desc"> <select id="edit_air_by_date" name="air_by_date" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[air_by_date_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[air_by_date_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[air_by_date_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[air_by_date_value == 0]}>No</option> </select><br> @@ -252,7 +252,7 @@ <span class="component-title">Subtitles</span> <span class="component-desc"> <select id="edit_subtitles" name="subtitles" class="form-control form-control-inline input-sm"> - <option value="keep" ${('', 'selected="selected"')[subtitles_value == None]}>< Keep ></option> + <option value="keep" ${('', 'selected="selected"')[subtitles_value is None]}>< Keep ></option> <option value="enable" ${('', 'selected="selected"')[subtitles_value == 1]}>Yes</option> <option value="disable" ${('', 'selected="selected"')[subtitles_value == 0]}>No</option> </select><br> diff --git a/sickbeard/__init__.py b/sickbeard/__init__.py index abd3fa33099b42b19ee7006d7c4a5af7d08ca0ad..0ddd3a8a710040211449176321a59bc7fbd19229 100644 --- a/sickbeard/__init__.py +++ b/sickbeard/__init__.py @@ -2188,13 +2188,13 @@ def launchBrowser(protocol='http', startPort=None, web_root='/'): def getEpList(epIDs, showid=None): - if epIDs == None or len(epIDs) == 0: + if epIDs is None or len(epIDs) == 0: return [] query = "SELECT * FROM tv_episodes WHERE indexerid in (%s)" % (",".join(['?'] * len(epIDs)),) params = epIDs - if showid != None: + if showid is not None: query += " AND showid = ?" params.append(showid) diff --git a/sickbeard/config.py b/sickbeard/config.py index 4bc496076ab559335b4dba553cac2b5f6238037d..a8f38d3dd37e68cb64c68558e60cb6b736de7ee0 100644 --- a/sickbeard/config.py +++ b/sickbeard/config.py @@ -120,7 +120,7 @@ def change_LOG_DIR(log_dir, web_log): else: return False - if sickbeard.WEB_LOG != web_log_value or log_dir_changed == True: + if sickbeard.WEB_LOG != web_log_value or log_dir_changed is True: sickbeard.WEB_LOG = web_log_value return True @@ -282,7 +282,7 @@ def change_VERSION_NOTIFY(version_notify): if not version_notify: sickbeard.NEWEST_VERSION_STRING = None - if oldSetting == False and version_notify == True: + if oldSetting is False and version_notify is True: sickbeard.versionCheckScheduler.forceRun() def change_DOWNLOAD_PROPERS(download_propers): diff --git a/sickbeard/db.py b/sickbeard/db.py index 95d2add4e8e613c46cdcd142bf77493017ffdfc4..92d5e08189b2a6bcfe2717286c783a42941ed56a 100644 --- a/sickbeard/db.py +++ b/sickbeard/db.py @@ -183,7 +183,7 @@ class DBConnection(object): :param fetchone: Boolean to indicate one result must be fetched (to walk results for instance) :return: query results """ - if query == None: + if query is None: return sqlResult = None @@ -192,7 +192,7 @@ class DBConnection(object): with db_locks[self.filename]: while attempt < 5: try: - if args == None: + if args is None: logger.log(self.filename + ": " + query, logger.DB) else: logger.log(self.filename + ": " + query + " with args " + str(args), logger.DB) @@ -229,7 +229,7 @@ class DBConnection(object): sqlResults = self.action(query, args, fetchall=True) - if sqlResults == None: + if sqlResults is None: return [] return sqlResults @@ -244,7 +244,7 @@ class DBConnection(object): """ sqlResults = self.action(query, args, fetchone=True) - if sqlResults == None: + if sqlResults is None: return [] return sqlResults diff --git a/sickbeard/history.py b/sickbeard/history.py index accf006f380ab2a278bf2c277443a123561717f0..e0a4b1f44f7fc841dc967057f1a8503181a49c8c 100644 --- a/sickbeard/history.py +++ b/sickbeard/history.py @@ -62,7 +62,7 @@ def logSnatch(searchResult): version = searchResult.version providerClass = searchResult.provider - if providerClass != None: + if providerClass is not None: provider = providerClass.name else: provider = "unknown" diff --git a/sickbeard/image_cache.py b/sickbeard/image_cache.py index 10c1d2e416d9c50f56a03c43f4ee1a7416fd1ab9..7ab282fee4c344aba20106db3e39662aab38a6fd 100644 --- a/sickbeard/image_cache.py +++ b/sickbeard/image_cache.py @@ -289,7 +289,7 @@ class ImageCache: cur_file_name = os.path.abspath(cur_provider.get_poster_path(show_obj)) cur_file_type = self.which_type(cur_file_name) - if cur_file_type == None: + if cur_file_type is None: logger.log(u"Unable to retrieve image type, not using the image from " + str(cur_file_name), logger.WARNING) continue diff --git a/sickbeard/naming.py b/sickbeard/naming.py index 1e3c0fe62f76a3856769f1f6668275474785360f..9b8db1d06a1492501059e061a365060d259ac407 100644 --- a/sickbeard/naming.py +++ b/sickbeard/naming.py @@ -123,15 +123,15 @@ def check_force_season_folders(pattern=None, multi=None, anime_type=None): :return: true if season folders need to be forced on or false otherwise. """ - if pattern == None: + if pattern is None: pattern = sickbeard.NAMING_PATTERN - if anime_type == None: + if anime_type is None: anime_type = sickbeard.NAMING_ANIME valid = not validate_name(pattern, None, anime_type, file_only=True) - if multi != None: + if multi is not None: valid = valid or not validate_name(pattern, multi, anime_type, file_only=True) return valid @@ -143,16 +143,16 @@ def check_valid_naming(pattern=None, multi=None, anime_type=None): :return: true if the naming is valid, false if not. """ - if pattern == None: + if pattern is None: pattern = sickbeard.NAMING_PATTERN - if anime_type == None: + if anime_type is None: anime_type = sickbeard.NAMING_ANIME logger.log(u"Checking whether the pattern " + pattern + " is valid for a single episode", logger.DEBUG) valid = validate_name(pattern, None, anime_type) - if multi != None: + if multi is not None: logger.log(u"Checking whether the pattern " + pattern + " is valid for a multi episode", logger.DEBUG) valid = valid and validate_name(pattern, multi, anime_type) @@ -165,7 +165,7 @@ def check_valid_abd_naming(pattern=None): :return: true if the naming is valid, false if not. """ - if pattern == None: + if pattern is None: pattern = sickbeard.NAMING_PATTERN logger.log(u"Checking whether the pattern " + pattern + " is valid for an air-by-date episode", logger.DEBUG) @@ -180,7 +180,7 @@ def check_valid_sports_naming(pattern=None): :return: true if the naming is valid, false if not. """ - if pattern == None: + if pattern is None: pattern = sickbeard.NAMING_PATTERN logger.log(u"Checking whether the pattern " + pattern + " is valid for an sports episode", logger.DEBUG) @@ -263,7 +263,7 @@ def generate_sample_ep(multi=None, abd=False, sports=False, anime_type=None): else: ep._release_name = 'Show.Name.S02E03.HDTV.XviD-RLSGROUP' - if multi != None: + if multi is not None: ep._name = "Ep Name (1)" if anime_type != 3: diff --git a/sickbeard/notifiers/pushover.py b/sickbeard/notifiers/pushover.py index f4f102b0bbaa3ef526f2282a815b6a35c0345445..1dc232f16ed34ec2d9172aaa9b695d978070f1c6 100644 --- a/sickbeard/notifiers/pushover.py +++ b/sickbeard/notifiers/pushover.py @@ -47,13 +47,13 @@ class PushoverNotifier(object): returns: True if the message succeeded, False otherwise """ - if userKey == None: + if userKey is None: userKey = sickbeard.PUSHOVER_USERKEY - if apiKey == None: + if apiKey is None: apiKey = sickbeard.PUSHOVER_APIKEY - if sound == None: + if sound is None: sound = sickbeard.PUSHOVER_SOUND logger.log(u"Pushover API KEY in use: " + apiKey, logger.DEBUG) diff --git a/sickbeard/nzbSplitter.py b/sickbeard/nzbSplitter.py index 09cb3df81ab386d9a3a29ce469d48acafb91d9e2..311443aa5077f21f403276a03dcd8f446daf44a6 100644 --- a/sickbeard/nzbSplitter.py +++ b/sickbeard/nzbSplitter.py @@ -145,7 +145,7 @@ def splitResult(result): return False # bust it up - season = parse_result.season_number if parse_result.season_number != None else 1 + season = parse_result.season_number if parse_result.season_number is not None else 1 separateNZBs, xmlns = getSeasonNZBs(result.name, urlData, season) @@ -167,8 +167,8 @@ def splitResult(result): return False # make sure the result is sane - if (parse_result.season_number != None and parse_result.season_number != season) or ( - parse_result.season_number == None and season != 1): + if (parse_result.season_number is not None and parse_result.season_number != season) or ( + parse_result.season_number is None and season != 1): logger.log( u"Found " + newNZB + " inside " + result.name + " but it doesn't seem to belong to the same season, ignoring it", logger.WARNING) diff --git a/sickbeard/nzbget.py b/sickbeard/nzbget.py index 809133a97952190fb636fe75c17ae3c4543133b0..8ac44154500b1c766e1ed26d7158c43e608ff619 100644 --- a/sickbeard/nzbget.py +++ b/sickbeard/nzbget.py @@ -47,7 +47,7 @@ def sendNZB(nzb, proper=False): else: nzbgetXMLrpc = "http://%(username)s:%(password)s@%(host)s/xmlrpc" - if sickbeard.NZBGET_HOST == None: + if sickbeard.NZBGET_HOST is None: logger.log(u"No NZBget host found in configuration. Please configure it.", logger.ERROR) return False @@ -116,7 +116,7 @@ def sendNZB(nzb, proper=False): if nzb.resultType == "nzb": genProvider = GenericProvider("") data = genProvider.getURL(nzb.url) - if data == None: + if data is None: return False nzbcontent64 = standard_b64encode(data) nzbget_result = nzbGetRPC.append(nzb.name + ".nzb", category, addToTop, nzbcontent64) diff --git a/sickbeard/postProcessor.py b/sickbeard/postProcessor.py index 575bf3b89a942ca4332cf85513564c3de7decff9..853210a86cbe089544709127ffa470ff3cad03c1 100644 --- a/sickbeard/postProcessor.py +++ b/sickbeard/postProcessor.py @@ -344,7 +344,7 @@ class PostProcessor(object): cur_extension = cur_lang + os.path.splitext(cur_extension)[1] # replace .nfo with .nfo-orig to avoid conflicts - if cur_extension == 'nfo' and sickbeard.NFO_RENAME == True: + if cur_extension == 'nfo' and sickbeard.NFO_RENAME is True: cur_extension = 'nfo-orig' # If new base name then convert name @@ -521,7 +521,7 @@ class PostProcessor(object): # remember whether it's a proper if parse_result.extra_info: - self.is_proper = re.search(r'(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) != None + self.is_proper = re.search(r'(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) is not None # if the result is complete then remember that for later # if the result is complete then set release name @@ -659,7 +659,7 @@ class PostProcessor(object): if cur_version is not None: version = cur_version - if cur_season != None: + if cur_season is not None: season = cur_season if cur_episodes: episodes = cur_episodes @@ -696,12 +696,12 @@ class PostProcessor(object): continue # if there's no season then we can hopefully just use 1 automatically - elif season == None and show: + elif season is None and show: myDB = db.DBConnection() numseasonsSQlResult = myDB.select( "SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and indexer = ? and season != 0", [show.indexerid, show.indexer]) - if int(numseasonsSQlResult[0][0]) == 1 and season == None: + if int(numseasonsSQlResult[0][0]) == 1 and season is None: self._log( u"Don't have a season number, but this show appears to only have 1 season, setting season number to 1...", logger.DEBUG) @@ -738,7 +738,7 @@ class PostProcessor(object): raise EpisodePostProcessingFailedException() # associate all the episodes together under a single root episode - if root_ep == None: + if root_ep is None: root_ep = curEp root_ep.relatedEps = [] elif curEp not in root_ep.relatedEps: @@ -916,7 +916,7 @@ class PostProcessor(object): if not show: self._log(u"This show isn't in your list, you need to add it to SR before post-processing an episode") raise EpisodePostProcessingFailedException() - elif season == None or not episodes: + elif season is None or not episodes: self._log(u"Not enough information to determine what episode this is. Quitting post-processing") return False diff --git a/sickbeard/providers/alpharatio.py b/sickbeard/providers/alpharatio.py index d2b096faeaf39bf4d6f50670703fe57d38e57467..0e58915fa0e4e706f6c9e0334d592e71f2fb31dd 100644 --- a/sickbeard/providers/alpharatio.py +++ b/sickbeard/providers/alpharatio.py @@ -85,7 +85,7 @@ class AlphaRatioProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (search_string, self.categories) @@ -125,12 +125,12 @@ class AlphaRatioProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/bitcannon.py b/sickbeard/providers/bitcannon.py index 54ea2276879e6a796187d287a8b9addf0ce57d7a..ebdd16551107fca7e2a21f9d60234da964f5529e 100644 --- a/sickbeard/providers/bitcannon.py +++ b/sickbeard/providers/bitcannon.py @@ -75,7 +75,7 @@ class BitCannonProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue @@ -83,7 +83,7 @@ class BitCannonProvider(generic.TorrentProvider): download_url = 'magnet:?xt=urn:btih:%s&dn=%s&tr=%s' % (info_hash, quote_plus(title.encode('utf-8')), u'&tr='.join([quote_plus(x.encode('utf-8')) for x in trackers])) item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/bitsoup.py b/sickbeard/providers/bitsoup.py index 162f7b3bc1fb63f8c236a443f5b28f2b7a4c9faf..e25855c9deee2c8029bee140220fb234dc4fc253 100644 --- a/sickbeard/providers/bitsoup.py +++ b/sickbeard/providers/bitsoup.py @@ -89,7 +89,7 @@ class BitSoupProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params['search'] = search_string @@ -128,12 +128,12 @@ class BitSoupProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/bluetigers.py b/sickbeard/providers/bluetigers.py index 5cd45d00c592f90d9b12344f926a867501d0eff2..561503a401732b3df83c43ef7da75950493d16fc 100644 --- a/sickbeard/providers/bluetigers.py +++ b/sickbeard/providers/bluetigers.py @@ -93,7 +93,7 @@ class BLUETIGERSProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params['search'] = search_string @@ -125,12 +125,12 @@ class BLUETIGERSProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/btdigg.py b/sickbeard/providers/btdigg.py index 553e7e320bfcd1a66395b6c964a350d9e31e5ca2..4eda679d1cdf9e9371d3566cdcf4b02ad4aaaa8f 100644 --- a/sickbeard/providers/btdigg.py +++ b/sickbeard/providers/btdigg.py @@ -55,11 +55,11 @@ class BTDIGGProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s" % search_string, logger.DEBUG) search_params['q'] = search_string.encode('utf-8') - search_params['order'] = '1' if mode is not 'RSS' else '2' + search_params['order'] = '1' if mode != 'RSS' else '2' searchURL = self.urls['api'] + '?' + urlencode(search_params) logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) @@ -83,12 +83,12 @@ class BTDIGGProvider(generic.TorrentProvider): # Filter unseeded torrent (Unsupported) # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s" % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/cpasbien.py b/sickbeard/providers/cpasbien.py index 67641af0006547fd78cb73d998bf3508d14bd042..e91160f8db116325b9629173d66b48db37b3678e 100644 --- a/sickbeard/providers/cpasbien.py +++ b/sickbeard/providers/cpasbien.py @@ -49,7 +49,7 @@ class CpasbienProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.url + '/recherche/'+search_string.replace('.', '-') + '.html' @@ -101,7 +101,7 @@ class CpasbienProvider(generic.TorrentProvider): continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/extratorrent.py b/sickbeard/providers/extratorrent.py index d16cccb75180c752bf8fccc6c906c176f44fdcde..eda874561dfa78266ab8f8fe4bd592cd64100af4 100644 --- a/sickbeard/providers/extratorrent.py +++ b/sickbeard/providers/extratorrent.py @@ -58,7 +58,7 @@ class ExtraTorrentProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) try: @@ -99,12 +99,12 @@ class ExtraTorrentProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/fnt.py b/sickbeard/providers/fnt.py index 52f83e8a32985ffb9ca1129eb9efc874ea2f8fb7..78bc2d1ea74e333a8bdb062758d06ed2e91a7de2 100644 --- a/sickbeard/providers/fnt.py +++ b/sickbeard/providers/fnt.py @@ -90,7 +90,7 @@ class FNTProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params['recherche'] = search_string @@ -135,12 +135,12 @@ class FNTProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/freshontv.py b/sickbeard/providers/freshontv.py index 3c5b7688d2263a848cda22853a42611976029326..d0cc75351f1bbf564358aa889cd56d40f9ff5c04 100644 --- a/sickbeard/providers/freshontv.py +++ b/sickbeard/providers/freshontv.py @@ -117,7 +117,7 @@ class FreshOnTVProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (freeleech, search_string) @@ -190,7 +190,7 @@ class FreshOnTVProvider(generic.TorrentProvider): for individual_torrent in torrent_rows: # skip if torrent has been nuked due to poor quality - if individual_torrent.find('img', alt='Nuked') != None: + if individual_torrent.find('img', alt='Nuked') is not None: continue try: @@ -215,12 +215,12 @@ class FreshOnTVProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/gftracker.py b/sickbeard/providers/gftracker.py index 826e42ccf49dbda3a63661c9f5cf626d89f2e161..14d6656cdda3a1050548120b441c249d78675049 100644 --- a/sickbeard/providers/gftracker.py +++ b/sickbeard/providers/gftracker.py @@ -94,7 +94,7 @@ class GFTrackerProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (self.categories, search_string) @@ -146,12 +146,12 @@ class GFTrackerProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/hdspace.py b/sickbeard/providers/hdspace.py index 48eec48a7180d1cb79130ceb3e37c5efd1a39178..5a61844d13a233194b2cd0faa0800669f8b24e55 100644 --- a/sickbeard/providers/hdspace.py +++ b/sickbeard/providers/hdspace.py @@ -93,13 +93,13 @@ class HDSpaceProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': searchURL = self.urls['search'] % (urllib.quote_plus(search_string.replace('.', ' ')),) else: searchURL = self.urls['search'] % '' logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s" % search_string, logger.DEBUG) data = self.getURL(searchURL) @@ -145,12 +145,12 @@ class HDSpaceProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/hdtorrents.py b/sickbeard/providers/hdtorrents.py index e2708f3cdd8db40a231cc133930e7aba15b8bfa4..4183f702686d7d68f975bb8e59e5e86fff1798b0 100644 --- a/sickbeard/providers/hdtorrents.py +++ b/sickbeard/providers/hdtorrents.py @@ -92,13 +92,13 @@ class HDTorrentsProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': searchURL = self.urls['search'] % (urllib.quote_plus(search_string), self.categories) else: searchURL = self.urls['rss'] % self.categories logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s" % search_string, logger.DEBUG) data = self.getURL(searchURL) @@ -177,12 +177,12 @@ class HDTorrentsProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/hounddawgs.py b/sickbeard/providers/hounddawgs.py index 3736bfcb4d4bde0066dc9b69c71e5e8dfcdec5f5..704320e3e57ffd5b3cbd2374716d5e7b29ff7d3f 100644 --- a/sickbeard/providers/hounddawgs.py +++ b/sickbeard/providers/hounddawgs.py @@ -95,7 +95,7 @@ class HoundDawgsProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params['searchstr'] = search_string @@ -157,12 +157,12 @@ class HoundDawgsProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/iptorrents.py b/sickbeard/providers/iptorrents.py index 000c9b03e42f0f19a84169d051d85f44bdcc5ac4..12c29eb991a7c1cfecb980ba437a8d78bc60f239 100644 --- a/sickbeard/providers/iptorrents.py +++ b/sickbeard/providers/iptorrents.py @@ -90,12 +90,12 @@ class IPTorrentsProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) # URL with 50 tv-show results, or max 150 if adjusted in IPTorrents profile searchURL = self.urls['search'] % (self.categories, freeleech, search_string) - searchURL += ';o=seeders' if mode is not 'RSS' else '' + searchURL += ';o=seeders' if mode != 'RSS' else '' logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) data = self.getURL(searchURL) @@ -136,12 +136,12 @@ class IPTorrentsProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/kat.py b/sickbeard/providers/kat.py index ba84c2584970e4644f08623cf96bfc701a6f34ae..0a0a79a81486a754e3677cb050b093c425992367 100755 --- a/sickbeard/providers/kat.py +++ b/sickbeard/providers/kat.py @@ -75,13 +75,13 @@ class KATProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - self.search_params['q'] = search_string.encode('utf-8') if mode is not 'RSS' else '' - self.search_params['field'] = 'seeders' if mode is not 'RSS' else 'time_add' + self.search_params['q'] = search_string.encode('utf-8') if mode != 'RSS' else '' + self.search_params['field'] = 'seeders' if mode != 'RSS' else 'time_add' - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s" % search_string, logger.DEBUG) - url_fmt_string = 'usearch' if mode is not 'RSS' else search_string + url_fmt_string = 'usearch' if mode != 'RSS' else search_string try: searchURL = self.urls['search'] % url_fmt_string + '?' + urlencode(self.search_params) logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) @@ -127,17 +127,17 @@ class KATProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue if self.confirmed and not verified: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result " + title + " but that doesn't seem like a verified result so I'm ignoring it", logger.DEBUG) continue item = title, download_url, size, seeders, leechers, info_hash - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/libertalia.py b/sickbeard/providers/libertalia.py index dc2a9a5141570b2c3774eead9bd91bdf2a026c47..657f3be0e50398ff0d602e7d20d9beb6c4e3d386 100644 --- a/sickbeard/providers/libertalia.py +++ b/sickbeard/providers/libertalia.py @@ -87,7 +87,7 @@ class LibertaliaProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urlsearch % (urllib.quote(search_string), self.categories) @@ -121,12 +121,12 @@ class LibertaliaProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/morethantv.py b/sickbeard/providers/morethantv.py index c89b22540ed42b04e4b01db0c55ed7a881b97bd6..82ad0842a77235dde2fa4cd4252a2eaa931a2558 100644 --- a/sickbeard/providers/morethantv.py +++ b/sickbeard/providers/morethantv.py @@ -106,7 +106,7 @@ class MoreThanTVProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (search_string.replace('(', '').replace(')', '')) @@ -133,7 +133,7 @@ class MoreThanTVProvider(generic.TorrentProvider): link = cells[1].find('a', attrs={'title': 'Download'}) # skip if torrent has been nuked due to poor quality - if cells[1].find('img', alt='Nuked') != None: + if cells[1].find('img', alt='Nuked') is not None: continue torrent_id_long = link['href'].replace('torrents.php?action=download&id=', '') @@ -162,12 +162,12 @@ class MoreThanTVProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/newpct.py b/sickbeard/providers/newpct.py index 1332d0e4628f354f9a72916c114c6741f91008aa..3bcd2caaffb668c71f5d06d7670bf2259f0e0861 100644 --- a/sickbeard/providers/newpct.py +++ b/sickbeard/providers/newpct.py @@ -92,7 +92,7 @@ class newpctProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params.update({'q': search_string.strip()}) @@ -136,12 +136,12 @@ class newpctProvider(generic.TorrentProvider): # Filter unseeded torrent (Unsupported) # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/nextgen.py b/sickbeard/providers/nextgen.py index 08e575da4364b18283be23c117d8dbf8ce1b67c2..5915ff6a5f999b815dc9bd88e35bb92caa5850b7 100644 --- a/sickbeard/providers/nextgen.py +++ b/sickbeard/providers/nextgen.py @@ -122,7 +122,7 @@ class NextGenProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (urllib.quote(search_string.encode('utf-8')), self.categories) @@ -171,12 +171,12 @@ class NextGenProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/nyaatorrents.py b/sickbeard/providers/nyaatorrents.py index ee7ef56343002f1163f55d7743f39f6adff1d441..1b58081c1697783adab1a487496cec72168a57ac 100644 --- a/sickbeard/providers/nyaatorrents.py +++ b/sickbeard/providers/nyaatorrents.py @@ -55,7 +55,7 @@ class NyaaProvider(generic.TorrentProvider): for mode in search_strings.keys(): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s" % search_string, logger.DEBUG) params = { @@ -64,7 +64,7 @@ class NyaaProvider(generic.TorrentProvider): "sort": 2, # Sort Descending By Seeders "order": 1 } - if mode is not 'RSS': + if mode != 'RSS': params["term"] = search_string.encode('utf-8') searchURL = self.url + '?' + urllib.urlencode(params) @@ -85,16 +85,16 @@ class NyaaProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue - if self.confirmed and not verified and mode is not 'RSS': + if self.confirmed and not verified and mode != 'RSS': logger.log(u"Found result " + title + " but that doesn't seem like a verified result so I'm ignoring it", logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/pretome.py b/sickbeard/providers/pretome.py index f165135dd6b09a1ebf9ae419bf5743b6e7edc7e4..30dbac2d2efaa2d74f989ae7ab462f28c16315f0 100644 --- a/sickbeard/providers/pretome.py +++ b/sickbeard/providers/pretome.py @@ -91,7 +91,7 @@ class PretomeProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (urllib.quote(search_string.encode('utf-8')), self.categories) @@ -148,12 +148,12 @@ class PretomeProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/rarbg.py b/sickbeard/providers/rarbg.py index 38921fb59daeefb9109ed48785645f571476ecdb..f2b2bb362f26604ff8559eacfa3625d7b8456ee9 100644 --- a/sickbeard/providers/rarbg.py +++ b/sickbeard/providers/rarbg.py @@ -108,7 +108,7 @@ class RarbgProvider(generic.TorrentProvider): if not self._doLogin(): return results - if epObj != None: + if epObj is not None: ep_indexerid = epObj.show.indexerid ep_indexer = epObj.show.indexer else: @@ -119,7 +119,7 @@ class RarbgProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) if mode is 'RSS': @@ -226,7 +226,7 @@ class RarbgProvider(generic.TorrentProvider): continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/scc.py b/sickbeard/providers/scc.py index 67159e3e5867a320d5379ecffbbd55e513348120..c02ac02d5a63bd6fb2dc7b404fbf5d7525129953 100644 --- a/sickbeard/providers/scc.py +++ b/sickbeard/providers/scc.py @@ -89,10 +89,10 @@ class SCCProvider(generic.TorrentProvider): items = {'Season': [], 'Episode': [], 'RSS': []} for mode in search_strings.keys(): - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (urllib.quote(search_string), self.categories[search_mode]) @@ -140,12 +140,12 @@ class SCCProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/scenetime.py b/sickbeard/providers/scenetime.py index 92dabe2a0ce0a4df2f9aa4577ff8557b626a943f..c4136a07c4fc8a385fce958b5a2b1dc36e35ceda 100644 --- a/sickbeard/providers/scenetime.py +++ b/sickbeard/providers/scenetime.py @@ -81,7 +81,7 @@ class SceneTimeProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (urllib.quote(search_string), self.categories) @@ -132,12 +132,12 @@ class SceneTimeProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/speedcd.py b/sickbeard/providers/speedcd.py index a3c5377a8a474674e1f596e97e7706df4a813924..b5fe4feab1f0d11e383934e3c1e9f06172bb4cbb 100644 --- a/sickbeard/providers/speedcd.py +++ b/sickbeard/providers/speedcd.py @@ -80,7 +80,7 @@ class SpeedCDProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) search_string = '+'.join(search_string.split()) @@ -114,12 +114,12 @@ class SpeedCDProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/strike.py b/sickbeard/providers/strike.py index 7f03fd5de6d7f2cdb866d6f82281ec5b00d5d9c3..a761eb5b893df139042b0afce2c2c95a6f9e05f1 100644 --- a/sickbeard/providers/strike.py +++ b/sickbeard/providers/strike.py @@ -42,7 +42,7 @@ class STRIKEProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: " + search_string.strip(), logger.DEBUG) searchURL = self.url + "api/v2/torrents/search/?category=TV&phrase=" + search_string @@ -66,11 +66,11 @@ class STRIKEProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) item = title, download_url, size, seeders, leechers diff --git a/sickbeard/providers/t411.py b/sickbeard/providers/t411.py index 4a1d4d2f9aff776ad6ff46cee3d7720a1a6dc29f..55375b41a8fff87e4a3c5844b70ed59a12af272b 100644 --- a/sickbeard/providers/t411.py +++ b/sickbeard/providers/t411.py @@ -90,7 +90,7 @@ class T411Provider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURLS = ([self.urls['search'] % (search_string, u) for u in self.subcategories], [self.urls['rss']])[mode is 'RSS'] @@ -101,11 +101,11 @@ class T411Provider(generic.TorrentProvider): continue try: - if 'torrents' not in data and mode is not 'RSS': + if 'torrents' not in data and mode != 'RSS': logger.log(u"Data returned from provider does not contain any torrents", logger.DEBUG) continue - torrents = data['torrents'] if mode is not 'RSS' else data + torrents = data['torrents'] if mode != 'RSS' else data if not torrents: logger.log(u"Data returned from provider does not contain any torrents", logger.DEBUG) @@ -129,16 +129,16 @@ class T411Provider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue - if self.confirmed and not verified and mode is not 'RSS': + if self.confirmed and not verified and mode != 'RSS': logger.log(u"Found result " + title + " but that doesn't seem like a verified result so I'm ignoring it", logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/thepiratebay.py b/sickbeard/providers/thepiratebay.py index aba4c0b2ed1997f8b8c497597a9a9766d8f2e16a..79aaa0fd1cddcb02ad4039d1508ee6cb51b01f4d 100644 --- a/sickbeard/providers/thepiratebay.py +++ b/sickbeard/providers/thepiratebay.py @@ -75,7 +75,7 @@ class ThePirateBayProvider(generic.TorrentProvider): self.search_params.update({'q': search_string.strip()}) - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: " + search_string, logger.DEBUG) searchURL = self.urls[('search', 'rss')[mode is 'RSS']] + '?' + urlencode(self.search_params) @@ -99,18 +99,18 @@ class ThePirateBayProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue # Accept Torrent only from Good People for every Episode Search if self.confirmed and re.search(r'(VIP|Trusted|Helper|Moderator)', torrent.group(0)) is None: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result %s but that doesn't seem like a trusted result so I'm ignoring it" % title, logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/titansoftv.py b/sickbeard/providers/titansoftv.py index 5281e199a3928e25df8a46a6210e507392dcdaf9..cea172b8bd6cd41ed9a5afab296725cd490a8e14 100644 --- a/sickbeard/providers/titansoftv.py +++ b/sickbeard/providers/titansoftv.py @@ -96,7 +96,7 @@ class TitansOfTVProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue diff --git a/sickbeard/providers/tntvillage.py b/sickbeard/providers/tntvillage.py index 5b4fc5d4fb8036ee739ac052dc0d46535eb13c13..c00842148d894428c82c6f309e7afa44dc9d37f7 100644 --- a/sickbeard/providers/tntvillage.py +++ b/sickbeard/providers/tntvillage.py @@ -300,12 +300,12 @@ class TNTVillageProvider(generic.TorrentProvider): if last_page: break - if mode is not 'RSS': + if mode != 'RSS': searchURL = (self.urls['search_page'] + '&filter={2}').format(z, self.categories, search_string) else: searchURL = self.urls['search_page'].format(z, self.categories) - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) logger.log(u"Search URL: %s" % searchURL, logger.DEBUG) @@ -379,12 +379,12 @@ class TNTVillageProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/tokyotoshokan.py b/sickbeard/providers/tokyotoshokan.py index ed7acce2a9950d6992d484e8cee6acf92e6ee3fd..6a078faa8de2c8459c887366350a89d79b1d4992 100644 --- a/sickbeard/providers/tokyotoshokan.py +++ b/sickbeard/providers/tokyotoshokan.py @@ -95,7 +95,7 @@ class TokyoToshokanProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue diff --git a/sickbeard/providers/torrentbytes.py b/sickbeard/providers/torrentbytes.py index 30711eda2f6b62ddb9b4f378dc1e1e1987854f98..0a0d3a68a453a52169ef4ee46912320b052ea94d 100644 --- a/sickbeard/providers/torrentbytes.py +++ b/sickbeard/providers/torrentbytes.py @@ -84,7 +84,7 @@ class TorrentBytesProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urls['search'] % (urllib.quote(search_string.encode('utf-8')), self.categories) @@ -147,12 +147,12 @@ class TorrentBytesProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/torrentday.py b/sickbeard/providers/torrentday.py index 1d84445385dd6c11e7df7f754b65aed7db1b98dd..62550dab1691fff5d1d277d98ce36e2beb7ced46 100644 --- a/sickbeard/providers/torrentday.py +++ b/sickbeard/providers/torrentday.py @@ -102,7 +102,7 @@ class TorrentDayProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) search_string = '+'.join(search_string.split()) @@ -138,12 +138,12 @@ class TorrentDayProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/torrentleech.py b/sickbeard/providers/torrentleech.py index 2ab8987dcaa441a6788cb59c680f8442852d3d8f..7ccac63bb57895d8fd88f7fac4a85e164b373c66 100644 --- a/sickbeard/providers/torrentleech.py +++ b/sickbeard/providers/torrentleech.py @@ -125,12 +125,12 @@ class TorrentLeechProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/torrentproject.py b/sickbeard/providers/torrentproject.py index b9c52266d88910d4ea7ab80137ec22b5279499cc..2f84b81c8309da3ba1b787babf7bfc507026e772 100644 --- a/sickbeard/providers/torrentproject.py +++ b/sickbeard/providers/torrentproject.py @@ -48,7 +48,7 @@ class TORRENTPROJECTProvider(generic.TorrentProvider): for mode in search_strings.keys(): # Mode = RSS, Season, Episode logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) @@ -68,7 +68,7 @@ class TORRENTPROJECTProvider(generic.TorrentProvider): seeders = helpers.tryInt(torrents[i]["seeds"], 1) leechers = helpers.tryInt(torrents[i]["leechs"], 0) if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Torrent doesn't meet minimum seeds & leechers not selecting : %s" % title, logger.DEBUG) continue @@ -77,7 +77,7 @@ class TORRENTPROJECTProvider(generic.TorrentProvider): try: assert seeders < 10 - assert mode is not 'RSS' + assert mode != 'RSS' logger.log(u"Torrent has less than 10 seeds getting dyn trackers: " + title, logger.DEBUG) trackerUrl = self.urls['api'] + "" + t_hash + "/trackers_json" jdata = self.getURL(trackerUrl, json=True) @@ -91,7 +91,7 @@ class TORRENTPROJECTProvider(generic.TorrentProvider): item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s" % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/torrentz.py b/sickbeard/providers/torrentz.py index f1dd3e8ffaba848dfced0340fdbe8c4e770df8c5..576a8ca114fea8a6aef3a229e2cb20761e4d8e2a 100644 --- a/sickbeard/providers/torrentz.py +++ b/sickbeard/providers/torrentz.py @@ -63,7 +63,7 @@ class TORRENTZProvider(generic.TorrentProvider): for mode in search_strings: for search_string in search_strings[mode]: search_url = self.urls['verified'] if self.confirmed else self.urls['feed'] - if mode is not 'RSS': + if mode != 'RSS': search_url += '?q=' + urllib.parse.quote_plus(search_string) logger.log(search_url) @@ -112,7 +112,7 @@ class TORRENTZProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue diff --git a/sickbeard/providers/transmitthenet.py b/sickbeard/providers/transmitthenet.py index e4e5b30e79f0ef4931a0115c74dedd36880a1d24..2049b638ddb4b600d2425a1e32268f8db2d1c2c4 100644 --- a/sickbeard/providers/transmitthenet.py +++ b/sickbeard/providers/transmitthenet.py @@ -90,7 +90,7 @@ class TransmitTheNetProvider(generic.TorrentProvider): for mode in search_strings.keys(): for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) data = self.getURL(self.urls['index'], params=self.search_params) @@ -133,12 +133,12 @@ class TransmitTheNetProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/tvchaosuk.py b/sickbeard/providers/tvchaosuk.py index 49aab00075b0503218f75e6772d567116bda63eb..dee2176c41791fff58c385a2e5429c28f4b228b4 100644 --- a/sickbeard/providers/tvchaosuk.py +++ b/sickbeard/providers/tvchaosuk.py @@ -131,7 +131,7 @@ class TVChaosUKProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_strings[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) self.search_params['keywords'] = search_string.strip() @@ -156,7 +156,7 @@ class TVChaosUKProvider(generic.TorrentProvider): # Filter unseeded torrent if seeders < self.minseed or leechers < self.minleech: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) continue @@ -176,7 +176,7 @@ class TVChaosUKProvider(generic.TorrentProvider): size = -1 item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/providers/xthor.py b/sickbeard/providers/xthor.py index 71cf973b5fb0310756133e72110c6c825f0b0370..2805fbe5b6270d4f4b9cf6ea7511fab4600510a4 100644 --- a/sickbeard/providers/xthor.py +++ b/sickbeard/providers/xthor.py @@ -80,7 +80,7 @@ class XthorProvider(generic.TorrentProvider): logger.log(u"Search Mode: %s" % mode, logger.DEBUG) for search_string in search_params[mode]: - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Search string: %s " % search_string, logger.DEBUG) searchURL = self.urlsearch % (urllib.quote(search_string), self.categories) @@ -109,12 +109,12 @@ class XthorProvider(generic.TorrentProvider): # Filter unseeded torrent # if seeders < self.minseed or leechers < self.minleech: - # if mode is not 'RSS': + # if mode != 'RSS': # logger.log(u"Discarding torrent because it doesn't meet the minimum seeders or leechers: {0} (S:{1} L:{2})".format(title, seeders, leechers), logger.DEBUG) # continue item = title, download_url, size, seeders, leechers - if mode is not 'RSS': + if mode != 'RSS': logger.log(u"Found result: %s " % title, logger.DEBUG) items[mode].append(item) diff --git a/sickbeard/sab.py b/sickbeard/sab.py index b22c1b7f470fc01c3f4f31ebb7f62a492016b3e7..4c1cc0e7d8952ff68d86f03c4fc8b99c6191ce9a 100644 --- a/sickbeard/sab.py +++ b/sickbeard/sab.py @@ -44,11 +44,11 @@ def sendNZB(nzb): # set up a dict with the URL params in it params = {} - if sickbeard.SAB_USERNAME != None: + if sickbeard.SAB_USERNAME is not None: params['ma_username'] = sickbeard.SAB_USERNAME - if sickbeard.SAB_PASSWORD != None: + if sickbeard.SAB_PASSWORD is not None: params['ma_password'] = sickbeard.SAB_PASSWORD - if sickbeard.SAB_APIKEY != None: + if sickbeard.SAB_APIKEY is not None: params['apikey'] = sickbeard.SAB_APIKEY category = sickbeard.SAB_CATEGORY if nzb.show.is_anime: @@ -61,7 +61,7 @@ def sendNZB(nzb): if nzb.show.is_anime: category = sickbeard.SAB_CATEGORY_ANIME_BACKLOG - if category != None: + if category is not None: params['cat'] = category # use high priority if specified (recently aired episode) @@ -120,7 +120,7 @@ def sendNZB(nzb): return False # this means we couldn't open the connection or something just as bad - if f == None: + if f is None: logger.log(u"No data returned from SABnzbd, NZB not sent", logger.ERROR) return False @@ -202,7 +202,7 @@ def _sabURLOpenSimple(url): except httplib.InvalidURL, e: logger.log(u"Invalid SAB host, check your config: " + ex(e), logger.ERROR) return False, "Invalid SAB host" - if f == None: + if f is None: logger.log(u"No data returned from SABnzbd", logger.ERROR) return False, "No data returned from SABnzbd" else: diff --git a/sickbeard/search.py b/sickbeard/search.py index 263e8f6e70dd025a7d79007fa72fc9639ae5cb55..293016c7039b546878ffa48e3bb7593154954670 100644 --- a/sickbeard/search.py +++ b/sickbeard/search.py @@ -52,7 +52,7 @@ def _downloadResult(result): """ resProvider = result.provider - if resProvider == None: + if resProvider is None: logger.log(u"Invalid provider name - this is a coding error, report it please", logger.ERROR) return False @@ -106,7 +106,7 @@ def snatchEpisode(result, endStatus=SNATCHED): for curEp in result.episodes: if datetime.date.today() - curEp.airdate <= datetime.timedelta(days=7): result.priority = 1 - if re.search(r'(^|[\. _-])(proper|repack)([\. _-]|$)', result.name, re.I) != None: + if re.search(r'(^|[\. _-])(proper|repack)([\. _-]|$)', result.name, re.I) is not None: endStatus = SNATCHED_PROPER if result.url.startswith('magnet') or result.url.endswith('torrent'): @@ -480,7 +480,7 @@ def searchProviders(show, episodes, manualSearch=False, downCurQuality=False): search_mode = curProvider.search_mode # Always search for episode when manually searching when in sponly - if search_mode == 'sponly' and manualSearch == True: + if search_mode == 'sponly' and manualSearch is True: search_mode = 'eponly' while True: diff --git a/sickbeard/searchBacklog.py b/sickbeard/searchBacklog.py index 9b5808ea24fd786d4dee85cc935b5e1980adb329..7ac69b0ae0dfcd33707b04d103e03c81c8d0462e 100644 --- a/sickbeard/searchBacklog.py +++ b/sickbeard/searchBacklog.py @@ -124,7 +124,7 @@ class BacklogSearcher: if len(sqlResults) == 0: lastBacklog = 1 - elif sqlResults[0]["last_backlog"] == None or sqlResults[0]["last_backlog"] == "": + elif sqlResults[0]["last_backlog"] is None or sqlResults[0]["last_backlog"] == "": lastBacklog = 1 else: lastBacklog = int(sqlResults[0]["last_backlog"]) diff --git a/sickbeard/show_queue.py b/sickbeard/show_queue.py index c195832099dcb91a095eff98712106131be65b32..9cec79e7257cbdbd4844e319cfb7ffba7faf8995 100644 --- a/sickbeard/show_queue.py +++ b/sickbeard/show_queue.py @@ -48,7 +48,7 @@ class ShowQueue(generic_queue.GenericQueue): return show.indexerid in [x.show.indexerid if x.show else 0 for x in self.queue if x.action_id in actions] def _isBeingSomethinged(self, show, actions): - return self.currentItem != None and show == self.currentItem.show and \ + return self.currentItem is not None and show == self.currentItem.show and \ self.currentItem.action_id in actions def isInUpdateQueue(self, show): @@ -79,7 +79,7 @@ class ShowQueue(generic_queue.GenericQueue): return self._isBeingSomethinged(show, (ShowQueueActions.SUBTITLE,)) def _getLoadingShowList(self): - return [x for x in self.queue + [self.currentItem] if x != None and x.isLoading] + return [x for x in self.queue + [self.currentItem] if x is not None and x.isLoading] loadingShowList = property(_getLoadingShowList) @@ -256,7 +256,7 @@ class QueueItemAdd(ShowQueueItem): Returns the show name if there is a show object created, if not returns the dir that the show is being added to. """ - if self.show == None: + if self.show is None: return self.showDir return self.show.name @@ -267,7 +267,7 @@ class QueueItemAdd(ShowQueueItem): Returns True if we've gotten far enough to have a show object, or False if we still only know the folder name. """ - if self.show == None: + if self.show is None: return True return False @@ -352,13 +352,13 @@ class QueueItemAdd(ShowQueueItem): # set up initial values self.show.location = self.showDir - self.show.subtitles = self.subtitles if self.subtitles != None else sickbeard.SUBTITLES_DEFAULT + self.show.subtitles = self.subtitles if self.subtitles is not None else sickbeard.SUBTITLES_DEFAULT self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT - self.show.flatten_folders = self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT - self.show.anime = self.anime if self.anime != None else sickbeard.ANIME_DEFAULT - self.show.scene = self.scene if self.scene != None else sickbeard.SCENE_DEFAULT - self.show.archive_firstmatch = self.archive if self.archive != None else sickbeard.ARCHIVE_DEFAULT - self.show.paused = self.paused if self.paused != None else False + self.show.flatten_folders = self.flatten_folders if self.flatten_folders is not None else sickbeard.FLATTEN_FOLDERS_DEFAULT + self.show.anime = self.anime if self.anime is not None else sickbeard.ANIME_DEFAULT + self.show.scene = self.scene if self.scene is not None else sickbeard.SCENE_DEFAULT + self.show.archive_firstmatch = self.archive if self.archive is not None else sickbeard.ARCHIVE_DEFAULT + self.show.paused = self.paused if self.paused is not None else False # set up default new/missing episode status logger.log(u"Setting all episodes to the specified default status: " + str(self.show.default_ep_status)) @@ -479,7 +479,7 @@ class QueueItemAdd(ShowQueueItem): self.finish() def _finishEarly(self): - if self.show != None: + if self.show is not None: sickbeard.showQueueScheduler.action.removeShow(self.show) self.finish() diff --git a/sickbeard/tv.py b/sickbeard/tv.py index 6999fb4ef6527ecc6927084fe00b245d45650141..54aa8be9b0f73559b82d8e2889bf7006d9dada26 100644 --- a/sickbeard/tv.py +++ b/sickbeard/tv.py @@ -115,7 +115,7 @@ class TVShow(object): self.release_groups = None otherShow = helpers.findCertainShow(sickbeard.showList, self.indexerid) - if otherShow != None: + if otherShow is not None: raise MultipleShowObjectsException("Can't create a show if it already exists") self.loadFromDB() @@ -283,7 +283,7 @@ class TVShow(object): else: ep = TVEpisode(self, season, episode) - if ep != None: + if ep is not None: self.episodes[season][episode] = ep return self.episodes[season][episode] @@ -447,7 +447,7 @@ class TVShow(object): curEpisode.release_name = ep_file_name # store the reference in the show - if curEpisode != None: + if curEpisode is not None: if self.subtitles: try: curEpisode.refreshSubtitles() @@ -644,7 +644,7 @@ class TVShow(object): return None # for now lets assume that any episode in the show dir belongs to that show - season = parse_result.season_number if parse_result.season_number != None else 1 + season = parse_result.season_number if parse_result.season_number is not None else 1 episodes = parse_result.episode_numbers rootEp = None @@ -974,7 +974,7 @@ class TVShow(object): "SELECT airdate, season, episode FROM tv_episodes WHERE showid = ? AND airdate >= ? AND status IN (?,?) ORDER BY airdate ASC LIMIT 1", [self.indexerid, datetime.date.today().toordinal(), UNAIRED, WANTED]) - if sqlResults == None or len(sqlResults) == 0: + if sqlResults is None or len(sqlResults) == 0: logger.log(str(self.indexerid) + u": No episode found... need to implement a show status", logger.DEBUG) self.nextaired = "" else: @@ -1317,13 +1317,13 @@ class TVShow(object): elif epStatus in (SNATCHED, SNATCHED_PROPER, SNATCHED_BEST): return Overview.SNATCHED # if they don't want re-downloads then we call it good if they have anything - elif maxBestQuality == None: + elif maxBestQuality is None: return Overview.GOOD # if the want only first match and already have one call it good elif self.archive_firstmatch and curQuality in bestQualities: return Overview.GOOD # if they want only first match and current quality is higher than minimal best quality call it good - elif self.archive_firstmatch and minBestQuality != None and curQuality > minBestQuality: + elif self.archive_firstmatch and minBestQuality is not None and curQuality > minBestQuality: return Overview.GOOD # if they have one but it's not the best they want then mark it as qual elif curQuality < maxBestQuality: @@ -2047,7 +2047,7 @@ class TVEpisode(object): singleName = False break - if curGoodName == None: + if curGoodName is None: curGoodName = match.group(1) elif curGoodName != match.group(1): singleName = False @@ -2195,14 +2195,14 @@ class TVEpisode(object): Manipulates an episode naming pattern and then fills the template in """ - if pattern == None: + if pattern is None: pattern = sickbeard.NAMING_PATTERN - if multi == None: + if multi is None: multi = sickbeard.NAMING_MULTI_EP if sickbeard.NAMING_CUSTOM_ANIME: - if anime_type == None: + if anime_type is None: anime_type = sickbeard.NAMING_ANIME else: anime_type = 3 @@ -2406,7 +2406,7 @@ class TVEpisode(object): Just the filename of the episode, formatted based on the naming settings """ - if pattern == None: + if pattern is None: # we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep if self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and not self.relatedEps: pattern = sickbeard.NAMING_ABD_PATTERN diff --git a/sickbeard/tvcache.py b/sickbeard/tvcache.py index 6c6ce5677c29117b532d7f9dd70be46af44da64c..5a9229bffa4c9fd47f5f07c2a828592891489ac3 100644 --- a/sickbeard/tvcache.py +++ b/sickbeard/tvcache.py @@ -298,7 +298,7 @@ class TVCache(object): myDB = self._getDB() sql = "SELECT * FROM [" + self.providerID + "] WHERE name LIKE '%.PROPER.%' OR name LIKE '%.REPACK.%'" - if date != None: + if date is not None: sql += " AND time >= " + str(int(time.mktime(date.timetuple()))) propers_results = myDB.select(sql) diff --git a/sickbeard/ui.py b/sickbeard/ui.py index 3d7c559bf934d59c1d188a2b4c6d22ca90b50dc2..7b62dac3f416e2d5f430a96dd3768cb0179464bb 100644 --- a/sickbeard/ui.py +++ b/sickbeard/ui.py @@ -128,7 +128,7 @@ class ProgressIndicators(): # if any of the progress indicators are done take them off the list for curPI in ProgressIndicators._pi[name]: - if curPI != None and curPI.percentComplete() == 100: + if curPI is not None and curPI.percentComplete() == 100: ProgressIndicators._pi[name].remove(curPI) # return the list of progress indicators associated with this name diff --git a/sickbeard/versionChecker.py b/sickbeard/versionChecker.py index b3dbf50cd0bf4cac5c6032f00151a6a9bdd7e88a..64a05f2f2a52d9e27698220848c3af85f8645ed5 100644 --- a/sickbeard/versionChecker.py +++ b/sickbeard/versionChecker.py @@ -71,7 +71,7 @@ class CheckVersion(object): if sickbeard.AUTO_UPDATE: logger.log(u"New update found for SickRage, starting auto-updater ...") ui.notifications.message('New update found for SickRage, starting auto-updater') - if self.run_backup_if_safe() is True: + if self.run_backup_if_safe(): if sickbeard.versionCheckScheduler.action.update(): logger.log(u"Update was successful!") ui.notifications.message('Update was successful') @@ -96,7 +96,7 @@ class CheckVersion(object): if not os.path.isdir(backupDir): os.mkdir(backupDir) - if self._keeplatestbackup(backupDir) == True and self._backup(backupDir) == True: + if self._keeplatestbackup(backupDir) and self._backup(backupDir): logger.log(u"Config backup successful, updating...") ui.notifications.message('Backup', 'Config backup successful, updating...') return True @@ -155,22 +155,26 @@ class CheckVersion(object): def safe_to_update(self): def db_safe(self): + message = { + 'equal': { + 'type': logger.DEBUG, + 'text': u"We can proceed with the update. New update has same DB version"}, + 'upgrade': { + 'type': logger.WARNING, + 'text': u"We can't proceed with the update. New update has a new DB version. Please manually update"}, + 'downgrade': { + 'type': logger.ERROR, + 'text': u"We can't proceed with the update. New update has a old DB version. It's not possible to downgrade"}, + } try: result = self.getDBcompare() - if result == 'equal': - logger.log(u"We can proceed with the update. New update has same DB version", logger.DEBUG) - return True - elif result == 'upgrade': - logger.log(u"We can't proceed with the update. New update has a new DB version. Please manually update", logger.WARNING) - return False - elif result == 'downgrade': - logger.log(u"We can't proceed with the update. New update has a old DB version. It's not possible to downgrade", logger.ERROR) - return False + if result in message: + logger.log(message[result]['text'], message[result]['type']) # unpack the result message into a log entry else: logger.log(u"We can't proceed with the update. Unable to check remote DB version. Error: %s" % result, logger.ERROR) - return False - except Exception as e: - logger.log(u"We can't proceed with the update. Unable to compare DB version. Error: %s" % repr(e), logger.ERROR) + return result in ['equal'] # add future True results to the list + except Exception as error: + logger.log(u"We can't proceed with the update. Unable to compare DB version. Error: %s" % repr(error), logger.ERROR) return False def postprocessor_safe(): @@ -193,7 +197,7 @@ class CheckVersion(object): postprocessor_safe = postprocessor_safe() showupdate_safe = showupdate_safe() - if db_safe == True and postprocessor_safe == True and showupdate_safe == True: + if db_safe and postprocessor_safe and showupdate_safe: logger.log(u"Proceeding with auto update", logger.DEBUG) return True else: diff --git a/sickbeard/webapi.py b/sickbeard/webapi.py index 4a4a8bd980c7466cc8209ebffb3558696582a208..11fb7e6ae0b110f9fe738372169bebb8913b7334 100644 --- a/sickbeard/webapi.py +++ b/sickbeard/webapi.py @@ -1,3 +1,4 @@ +# coding=utf-8 # Author: Dennis Lutter <lad1337@gmail.com> # Author: Jonathon Saine <thezoggy@gmail.com> # URL: http://code.google.com/p/sickbeard/ @@ -16,7 +17,10 @@ # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. -# pylint: disable=W0223,E0202 + +# TODO: break this up into separate files +# pylint: disable=C0301,C0302 +# pylint: disable=E1101,E0202,C0111,C0103 import io import os @@ -64,8 +68,10 @@ from sickbeard.common import statusStrings try: import json except ImportError: + # pylint: disable=F0401 import simplejson as json +# pylint: disable=F0401 from tornado.web import RequestHandler indexer_ids = ["indexerid", "tvdbid"] @@ -109,13 +115,13 @@ class ApiHandler(RequestHandler): # set the output callback # default json - outputCallbackDict = { + output_callback_dict = { 'default': self._out_as_json, 'image': self._out_as_image, } - accessMsg = u"API :: " + self.request.remote_ip + " - gave correct API KEY. ACCESS GRANTED" - logger.log(accessMsg, logger.DEBUG) + access_msg = u"API :: " + self.request.remote_ip + " - gave correct API KEY. ACCESS GRANTED" + logger.log(access_msg, logger.DEBUG) # set the original call_dispatcher as the local _call_dispatcher _call_dispatcher = self.call_dispatcher @@ -127,24 +133,24 @@ class ApiHandler(RequestHandler): del kwargs["profile"] try: - outDict = _call_dispatcher(args, kwargs) + out_dict = _call_dispatcher(args, kwargs) except Exception, e: # real internal error oohhh nooo :( logger.log(u"API :: " + ex(e), logger.ERROR) - errorData = { + error_data = { "error_msg": ex(e), "args": args, "kwargs": kwargs } - outDict = _responds(RESULT_FATAL, errorData, - "SickRage encountered an internal error! Please report to the Devs") + out_dict = _responds(RESULT_FATAL, error_data, + "SickRage encountered an internal error! Please report to the Devs") - if 'outputType' in outDict: - outputCallback = outputCallbackDict[outDict['outputType']] + if 'outputType' in out_dict: + output_callback = output_callback_dict[out_dict['outputType']] else: - outputCallback = outputCallbackDict['default'] + output_callback = output_callback_dict['default'] try: - self.finish(outputCallback(outDict)) + self.finish(output_callback(out_dict)) except Exception: pass @@ -157,7 +163,7 @@ class ApiHandler(RequestHandler): try: out = json.dumps(_dict, ensure_ascii=False, sort_keys=True) callback = self.get_query_argument('callback', None) or self.get_query_argument('jsonp', None) - if callback is not None: + if callback: out = callback + '(' + out + ');' # wrap with JSONP call if requested except Exception, e: # if we fail to generate the output fake an error logger.log(u"API :: " + traceback.format_exc(), logger.DEBUG) @@ -174,101 +180,94 @@ class ApiHandler(RequestHandler): logger.log(u"API :: all args: '" + str(args) + "'", logger.DEBUG) logger.log(u"API :: all kwargs: '" + str(kwargs) + "'", logger.DEBUG) - cmds = None + commands = None if args: - cmds = args[0] - args = args[1:] - - if "cmd" in kwargs: - cmds = kwargs["cmd"] - del kwargs["cmd"] - - outDict = {} - if cmds is not None: - cmds = cmds.split("|") - multiCmds = bool(len(cmds) > 1) - for cmd in cmds: - curArgs, curKwargs = self.filter_params(cmd, args, kwargs) - cmdIndex = None - if len(cmd.split("_")) > 1: # was a index used for this cmd ? - cmd, cmdIndex = cmd.split("_") # this gives us the clear cmd and the index - - logger.log(u"API :: " + cmd + ": curKwargs " + str(curKwargs), logger.DEBUG) - if not (multiCmds and cmd in ('show.getbanner', 'show.getfanart', 'show.getnetworklogo', 'show.getposter')): # skip these cmd while chaining + commands, args = args[0], args[1:] + commands = kwargs.pop("cmd", commands) + + out_dict = {} + if commands: + commands = commands.split("|") + multi_commands = len(commands) > 1 + for cmd in commands: + cur_args, cur_kwargs = self.filter_params(cmd, args, kwargs) + + cmd = cmd.split("_") # was a index used for this cmd ? + cmd, cmd_index = cmd[0], cmd[1:] # this gives us the clear cmd and the index + + logger.log(u"API :: " + cmd + ": cur_kwargs " + str(cur_kwargs), logger.DEBUG) + if not (cmd in ('show.getbanner', 'show.getfanart', 'show.getnetworklogo', 'show.getposter') and + multi_commands): # skip these cmd while chaining try: if cmd in function_mapper: - # map function - func = function_mapper.get(cmd) - - # add request handler to function - func.rh = self - - # call function and get response back - curOutDict = func(curArgs, curKwargs).run() + func = function_mapper.get(cmd) # map function + func.rh = self # add request handler to function + cur_out_dict = func(cur_args, cur_kwargs).run() # call function and get response elif _is_int(cmd): - curOutDict = TVDBShorthandWrapper(curArgs, curKwargs, cmd).run() + cur_out_dict = TVDBShorthandWrapper(cur_args, cur_kwargs, cmd).run() else: - curOutDict = _responds(RESULT_ERROR, "No such cmd: '" + cmd + "'") - except ApiError, e: # Api errors that we raised, they are harmless - curOutDict = _responds(RESULT_ERROR, msg=ex(e)) - else: # if someone chained one of the forbiden cmds they will get an error for this one cmd - curOutDict = _responds(RESULT_ERROR, msg="The cmd '" + cmd + "' is not supported while chaining") - - if multiCmds: - # note: if multiple same cmds are issued but one has not an index defined it will override all others - # or the other way around, this depends on the order of the cmds - # this is not a bug - if cmdIndex is None: # do we need a index dict for this cmd ? - outDict[cmd] = curOutDict + cur_out_dict = _responds(RESULT_ERROR, "No such cmd: '" + cmd + "'") + except ApiError as error: # Api errors that we raised, they are harmless + cur_out_dict = _responds(RESULT_ERROR, msg=ex(error)) + else: # if someone chained one of the forbidden commands they will get an error for this one cmd + cur_out_dict = _responds(RESULT_ERROR, msg="The cmd '" + cmd + "' is not supported while chaining") + + if multi_commands: + # note: if duplicate commands are issued and one has an index defined it will override + # all others or the other way around, depending on the command order + # THIS IS NOT A BUG! + if cmd_index: # do we need an index dict for this cmd ? + if cmd not in out_dict: + out_dict[cmd] = {} + out_dict[cmd][cmd_index] = cur_out_dict else: - if not cmd in outDict: - outDict[cmd] = {} - outDict[cmd][cmdIndex] = curOutDict + out_dict[cmd] = cur_out_dict else: - outDict = curOutDict + out_dict = cur_out_dict - if multiCmds: # if we had multiple cmds we have to wrap it in a response dict - outDict = _responds(RESULT_SUCCESS, outDict) + if multi_commands: # if we had multiple commands we have to wrap it in a response dict + out_dict = _responds(RESULT_SUCCESS, out_dict) else: # index / no cmd given - outDict = CMD_SickBeard(args, kwargs).run() + out_dict = CMD_SickBeard(args, kwargs).run() - return outDict + return out_dict def filter_params(self, cmd, args, kwargs): """ return only params kwargs that are for cmd and rename them to a clean version (remove "<cmd>_") - args are shared across all cmds + args are shared across all commands - all args and kwarks are lowerd + all args and kwargs are lowered cmd are separated by "|" e.g. &cmd=shows|future - kwargs are namespaced with "." e.g. show.indexerid=101501 - if a karg has no namespace asing it anyways (global) + kwargs are name-spaced with "." e.g. show.indexerid=101501 + if a kwarg has no namespace asking it anyways (global) full e.g. /api?apikey=1234&cmd=show.seasonlist_asd|show.seasonlist_2&show.seasonlist_asd.indexerid=101501&show.seasonlist_2.indexerid=79488&sort=asc two calls of show.seasonlist one has the index "asd" the other one "2" - the "indexerid" kwargs / params have the indexed cmd as a namspace + the "indexerid" kwargs / params have the indexed cmd as a namespace and the kwarg / param "sort" is a used as a global """ - curArgs = [] + cur_args = [] for arg in args: - curArgs.append(arg.lower()) - curArgs = tuple(curArgs) + cur_args.append(arg.lower()) + cur_args = tuple(cur_args) - curKwargs = {} + cur_kwargs = {} for kwarg in kwargs: if kwarg.find(cmd + ".") == 0: - cleanKey = kwarg.rpartition(".")[2] - curKwargs[cleanKey] = kwargs[kwarg].lower() - elif not "." in kwarg: # the kwarg was not namespaced therefore a "global" - curKwargs[kwarg] = kwargs[kwarg] - return curArgs, curKwargs + clean_key = kwarg.rpartition(".")[2] + cur_kwargs[clean_key] = kwargs[kwarg].lower() + elif "." not in kwarg: # the kwarg was not name-spaced therefore a "global" + cur_kwargs[kwarg] = kwargs[kwarg] + return cur_args, cur_kwargs class ApiCall(ApiHandler): + _help = {"desc": "This command is not documented. Please report this to the developers."} def __init__(self, args, kwargs): @@ -304,7 +303,7 @@ class ApiCall(ApiHandler): if paramType in self._help: for paramName in paramDict: - if not paramName in self._help[paramType]: + if paramName not in self._help[paramType]: self._help[paramType][paramName] = {} if paramDict[paramName]["allowedValues"]: self._help[paramType][paramName]["allowedValues"] = paramDict[paramName]["allowedValues"] @@ -331,7 +330,7 @@ class ApiCall(ApiHandler): msg = "The required parameters: '" + "','".join(self._missing) + "' where not set" return _responds(RESULT_ERROR, msg=msg) - def check_params(self, args, kwargs, key, default, required, arg_type, allowedValues): + def check_params(self, args, kwargs, key, default, required, arg_type, allowed_values): """ function to check passed params for the shorthand wrapper and to detect missing/required params @@ -345,10 +344,10 @@ class ApiCall(ApiHandler): self.indexer = indexer_ids.index(key) missing = True - orgDefault = default + org_default = default if arg_type == "bool": - allowedValues = [0, 1] + allowed_values = [0, 1] if args: default = args[0] @@ -363,28 +362,27 @@ class ApiCall(ApiHandler): self._requiredParams.append(key) except AttributeError: self._missing = [] - self._requiredParams = {key: {"allowedValues": allowedValues, - "defaultValue": orgDefault, + self._requiredParams = {key: {"allowed_values": allowed_values, + "defaultValue": org_default, "type": arg_type}} if missing and key not in self._missing: self._missing.append(key) else: try: - self._optionalParams[key] = {"allowedValues": allowedValues, - "defaultValue": orgDefault, + self._optionalParams[key] = {"allowed_values": allowed_values, + "defaultValue": org_default, "type": arg_type} except AttributeError: - self._optionalParams = {} - self._optionalParams[key] = {"allowedValues": allowedValues, - "defaultValue": orgDefault, - "type": arg_type} + self._optionalParams = {key: {"allowed_values": allowed_values, + "defaultValue": org_default, + "type": arg_type}} if default: default = self._check_param_type(default, key, arg_type) if arg_type == "bool": arg_type = [] - self._check_param_value(default, key, allowedValues) + self._check_param_value(default, key, allowed_values) return default, args @@ -430,25 +428,25 @@ class ApiCall(ApiHandler): return value - def _check_param_value(self, value, name, allowedValues): + def _check_param_value(self, value, name, allowed_values): """ will check if value (or all values in it ) are in allowed values will raise an exception if value is "out of range" - if bool(allowedValue) == False a check is not performed and all values are excepted + if bool(allowedValue) is False a check is not performed and all values are excepted """ - if allowedValues: + if allowed_values: error = False if isinstance(value, list): for item in value: - if not item in allowedValues: + if item not in allowed_values: error = True else: - if not value in allowedValues: + if value not in allowed_values: error = True if error: # this is kinda a ApiError but raising an error is the only way of quitting here raise ApiError(u"param: '" + str(name) + "' with given value: '" + str( - value) + "' is out of allowed range '" + str(allowedValues) + "'") + value) + "' is out of allowed range '" + str(allowed_values) + "'") class TVDBShorthandWrapper(ApiCall): @@ -489,10 +487,10 @@ def _is_int(data): return True -def _rename_element(dict_obj, oldKey, newKey): +def _rename_element(dict_obj, old_key, new_key): try: - dict_obj[newKey] = dict_obj[oldKey] - del dict_obj[oldKey] + dict_obj[new_key] = dict_obj[old_key] + del dict_obj[old_key] except (ValueError, TypeError, NameError): pass return dict_obj @@ -504,19 +502,17 @@ def _responds(result_type, data=None, msg=""): message is a human readable string, can be empty data is either a dict or a array, can be a empty dict or empty array """ - if data is None: - data = {} return {"result": result_type_map[result_type], "message": msg, - "data": data} + "data": {} if not data else data} -def _get_status_Strings(s): +def _get_status_strings(s): return statusStrings[s] -def _ordinal_to_dateTimeForm(ordinal): - # workaround for episodes with no airdate +def _ordinal_to_datetime_form(ordinal): + # workaround for episodes with no air date if int(ordinal) != 1: date = datetime.date.fromordinal(ordinal) else: @@ -524,7 +520,7 @@ def _ordinal_to_dateTimeForm(ordinal): return date.strftime(dateTimeFormat) -def _ordinal_to_dateForm(ordinal): +def _ordinal_to_date_form(ordinal): if int(ordinal) != 1: date = datetime.date.fromordinal(ordinal) else: @@ -532,28 +528,28 @@ def _ordinal_to_dateForm(ordinal): return date.strftime(dateFormat) -def _historyDate_to_dateTimeForm(timeString): - date = datetime.datetime.strptime(timeString, History.date_format) +def _history_date_to_datetime_form(time_string): + date = datetime.datetime.strptime(time_string, History.date_format) return date.strftime(dateTimeFormat) -def _mapQuality(showObj): - quality_map = _getQualityMap() +def _map_quality(show_obj): + quality_map = _get_quality_map() - anyQualities = [] - bestQualities = [] + any_qualities = [] + best_qualities = [] - iqualityID, aqualityID = Quality.splitQuality(int(showObj)) - if iqualityID: - for quality in iqualityID: - anyQualities.append(quality_map[quality]) - if aqualityID: - for quality in aqualityID: - bestQualities.append(quality_map[quality]) - return anyQualities, bestQualities + i_quality_id, a_quality_id = Quality.splitQuality(int(show_obj)) + if i_quality_id: + for quality in i_quality_id: + any_qualities.append(quality_map[quality]) + if a_quality_id: + for quality in a_quality_id: + best_qualities.append(quality_map[quality]) + return any_qualities, best_qualities -def _getQualityMap(): +def _get_quality_map(): return {Quality.SDTV: 'sdtv', Quality.SDDVD: 'sddvd', Quality.HDTV: 'hdtv', @@ -566,15 +562,15 @@ def _getQualityMap(): Quality.UNKNOWN: 'unknown'} -def _getRootDirs(): +def _get_root_dirs(): if sickbeard.ROOT_DIRS == "": return {} - rootDir = {} + root_dir = {} root_dirs = sickbeard.ROOT_DIRS.split('|') default_index = int(sickbeard.ROOT_DIRS.split('|')[0]) - rootDir["default_index"] = int(sickbeard.ROOT_DIRS.split('|')[0]) + root_dir["default_index"] = int(sickbeard.ROOT_DIRS.split('|')[0]) # remove default_index value from list (this fixes the offset) root_dirs.pop(0) @@ -597,11 +593,12 @@ def _getRootDirs(): if root_dir is default_dir: default = 1 - curDir = {} - curDir['valid'] = valid - curDir['location'] = root_dir - curDir['default'] = default - dir_list.append(curDir) + cur_dir = { + 'valid': valid, + 'location': root_dir, + 'default': default + } + dir_list.append(cur_dir) return dir_list @@ -614,7 +611,7 @@ class ApiError(Exception): class IntParseError(Exception): """ - A value could not be parsed into an int, but should be parsable to an int + A value could not be parsed into an int, but should be parse-able to an int """ @@ -722,44 +719,41 @@ class CMD_Episode(ApiCall): def run(self): """ Get detailed information about an episode """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") - myDB = db.DBConnection(row_type="dict") - sqlResults = myDB.select( + my_db = db.DBConnection(row_type="dict") + sql_results = my_db.select( "SELECT name, description, airdate, status, location, file_size, release_name, subtitles FROM tv_episodes WHERE showid = ? AND episode = ? AND season = ?", [self.indexerid, self.e, self.s]) - if not len(sqlResults) == 1: + if not len(sql_results) == 1: raise ApiError("Episode not found") - episode = sqlResults[0] + episode = sql_results[0] # handle path options # absolute vs relative vs broken - showPath = None + show_path = None try: - showPath = showObj.location + show_path = show_obj.location except ShowDirectoryNotFoundException: pass - if bool(self.fullPath) == True and showPath: - pass - elif bool(self.fullPath) == False and showPath: - # using the length because lstrip removes to much - showPathLength = len(showPath) + 1 # the / or \ yeah not that nice i know - episode["location"] = episode["location"][showPathLength:] - elif not showPath: # show dir is broken ... episode path will be empty + if not show_path: # show dir is broken ... episode path will be empty episode["location"] = "" + elif not self.fullPath: + # using the length because lstrip() removes to much + show_path_length = len(show_path) + 1 # the / or \ yeah not that nice i know + episode["location"] = episode["location"][show_path_length:] # convert stuff to human form - if helpers.tryInt(episode['airdate'], 1) > 693595: # 1900 + if helpers.tryInt(episode['airdate'], 1) > 693595: # 1900 episode['airdate'] = sbdatetime.sbdatetime.sbfdate(sbdatetime.sbdatetime.convert_to_setting( - network_timezones.parse_date_time(int(episode['airdate']), showObj.airs, showObj.network)), - d_preset=dateFormat) + network_timezones.parse_date_time(int(episode['airdate']), show_obj.airs, show_obj.network)), d_preset=dateFormat) else: episode['airdate'] = 'Never' status, quality = Quality.splitCompositeStatus(int(episode["status"])) - episode["status"] = _get_status_Strings(status) + episode["status"] = _get_status_strings(status) episode["quality"] = get_quality_string(quality) episode["file_size_human"] = helpers.pretty_filesize(episode["file_size"]) @@ -790,26 +784,26 @@ class CMD_EpisodeSearch(ApiCall): def run(self): """ Search for an episode """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") # retrieve the episode object and fail if we can't get one - epObj = showObj.getEpisode(int(self.s), int(self.e)) - if isinstance(epObj, str): + ep_obj = show_obj.getEpisode(int(self.s), int(self.e)) + if isinstance(ep_obj, str): return _responds(RESULT_FAILURE, msg="Episode not found") # make a queue item for it and put it on the queue - ep_queue_item = search_queue.ManualSearchQueueItem(showObj, epObj) + ep_queue_item = search_queue.ManualSearchQueueItem(show_obj, ep_obj) sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) # @UndefinedVariable # wait until the queue item tells us whether it worked or not - while ep_queue_item.success == None: # @UndefinedVariable + while ep_queue_item.success is None: # @UndefinedVariable time.sleep(1) # return the correct json value if ep_queue_item.success: - status, quality = Quality.splitCompositeStatus(epObj.status) # @UnusedVariable + status, quality = Quality.splitCompositeStatus(ep_obj.status) # @UnusedVariable # TODO: split quality and status? return _responds(RESULT_SUCCESS, {"quality": get_quality_string(quality)}, "Snatched (" + get_quality_string(quality) + ")") @@ -846,8 +840,8 @@ class CMD_EpisodeSetStatus(ApiCall): def run(self): """ Set the status of an episode or a season (when no episode is provided) """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") # convert the string status to a int @@ -855,22 +849,22 @@ class CMD_EpisodeSetStatus(ApiCall): if str(statusStrings[status]).lower() == str(self.status).lower(): self.status = status break - else: # if we dont break out of the for loop we got here. + else: # if we don't break out of the for loop we got here. # the allowed values has at least one item that could not be matched against the internal status strings raise ApiError("The status string could not be matched to a status. Report to Devs!") ep_list = [] if self.e: - epObj = showObj.getEpisode(self.s, self.e) - if epObj == None: + ep_obj = show_obj.getEpisode(self.s, self.e) + if not ep_obj: return _responds(RESULT_FAILURE, msg="Episode not found") - ep_list = [epObj] + ep_list = [ep_obj] else: - # get all episode numbers frome self,season - ep_list = showObj.getAllEpisodes(season=self.s) + # get all episode numbers from self, season + ep_list = show_obj.getAllEpisodes(season=self.s) - def _epResult(result_code, ep, msg=""): - return {'season': ep.season, 'episode': ep.episode, 'status': _get_status_Strings(ep.status), + def _ep_result(result_code, ep, msg=""): + return {'season': ep.season, 'episode': ep.episode, 'status': _get_status_strings(ep.status), 'result': result_type_map[result_code], 'message': msg} ep_results = [] @@ -879,52 +873,52 @@ class CMD_EpisodeSetStatus(ApiCall): segments = {} sql_l = [] - for epObj in ep_list: - with epObj.lock: + for ep_obj in ep_list: + with ep_obj.lock: if self.status == WANTED: # figure out what episodes are wanted so we can backlog them - if epObj.season in segments: - segments[epObj.season].append(epObj) + if ep_obj.season in segments: + segments[ep_obj.season].append(ep_obj) else: - segments[epObj.season] = [epObj] + segments[ep_obj.season] = [ep_obj] - # don't let them mess up UNAIRED episodes - if epObj.status == UNAIRED: - if self.e != None: # setting the status of a unaired is only considert a failure if we directly wanted this episode, but is ignored on a season request + # don't let them mess up UN-AIRED episodes + if ep_obj.status == UNAIRED: + if self.e is not None: # setting the status of an un-aired is only considered a failure if we directly wanted this episode, but is ignored on a season request ep_results.append( - _epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is UNAIRED")) + _ep_result(RESULT_FAILURE, ep_obj, "Refusing to change status because it is UN-AIRED")) failure = True continue if self.status == FAILED and not sickbeard.USE_FAILED_DOWNLOADS: - ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status to FAILED because failed download handling is disabled")) + ep_results.append(_ep_result(RESULT_FAILURE, ep_obj, "Refusing to change status to FAILED because failed download handling is disabled")) failure = True continue # allow the user to force setting the status for an already downloaded episode - if epObj.status in Quality.DOWNLOADED + Quality.ARCHIVED and not self.force: - ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is already marked as DOWNLOADED")) + if ep_obj.status in Quality.DOWNLOADED + Quality.ARCHIVED and not self.force: + ep_results.append(_ep_result(RESULT_FAILURE, ep_obj, "Refusing to change status because it is already marked as DOWNLOADED")) failure = True continue - epObj.status = self.status - sql_l.append(epObj.get_sql()) + ep_obj.status = self.status + sql_l.append(ep_obj.get_sql()) if self.status == WANTED: start_backlog = True - ep_results.append(_epResult(RESULT_SUCCESS, epObj)) + ep_results.append(_ep_result(RESULT_SUCCESS, ep_obj)) if len(sql_l) > 0: - myDB = db.DBConnection() - myDB.mass_action(sql_l) + my_db = db.DBConnection() + my_db.mass_action(sql_l) extra_msg = "" if start_backlog: for season, segment in segments.iteritems(): - cur_backlog_queue_item = search_queue.BacklogQueueItem(showObj, segment) + cur_backlog_queue_item = search_queue.BacklogQueueItem(show_obj, segment) sickbeard.searchQueueScheduler.action.add_item(cur_backlog_queue_item) # @UndefinedVariable - logger.log(u"API :: Starting backlog for " + showObj.name + " season " + str( + logger.log(u"API :: Starting backlog for " + show_obj.name + " season " + str( season) + " because some episodes were set to WANTED") extra_msg = " Backlog started" @@ -959,28 +953,28 @@ class CMD_SubtitleSearch(ApiCall): def run(self): """ Search for an episode subtitles """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") # retrieve the episode object and fail if we can't get one - epObj = showObj.getEpisode(int(self.s), int(self.e)) - if isinstance(epObj, str): + ep_obj = show_obj.getEpisode(int(self.s), int(self.e)) + if isinstance(ep_obj, str): return _responds(RESULT_FAILURE, msg="Episode not found") # try do download subtitles for that episode - previous_subtitles = epObj.subtitles + previous_subtitles = ep_obj.subtitles try: - subtitles = epObj.downloadSubtitles() + subtitles = ep_obj.downloadSubtitles() except Exception: return _responds(RESULT_FAILURE, msg='Unable to find subtitles') # return the correct json value - newSubtitles = frozenset(epObj.subtitles).difference(previous_subtitles) - if newSubtitles: - newLangs = [subtitles.fromietf(newSub) for newSub in newSubtitles] - status = 'New subtitles downloaded: %s' % ', '.join([newLang.name for newLang in newLangs]) + new_subtitles = frozenset(ep_obj.subtitles).difference(previous_subtitles) + if new_subtitles: + new_languages = [subtitles.fromietf(newSub) for newSub in new_subtitles] + status = 'New subtitles downloaded: %s' % ', '.join([new_language.name for new_language in new_languages]) response = _responds(RESULT_SUCCESS, msg='New subtitles found') else: status = 'No subtitles downloaded' @@ -1010,27 +1004,27 @@ class CMD_Exceptions(ApiCall): def run(self): """ Get the scene exceptions for all or a given show """ - myDB = db.DBConnection("cache.db", row_type="dict") + my_db = db.DBConnection("cache.db", row_type="dict") - if self.indexerid == None: - sqlResults = myDB.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions") + if self.indexerid is None: + sql_results = my_db.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions") scene_exceptions = {} - for row in sqlResults: + for row in sql_results: indexerid = row["indexerid"] - if not indexerid in scene_exceptions: + if indexerid not in scene_exceptions: scene_exceptions[indexerid] = [] scene_exceptions[indexerid].append(row["show_name"]) else: - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") - sqlResults = myDB.select( + sql_results = my_db.select( "SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions WHERE indexer_id = ?", [self.indexerid]) scene_exceptions = [] - for row in sqlResults: + for row in sql_results: scene_exceptions.append(row["show_name"]) return _responds(RESULT_SUCCESS, scene_exceptions) @@ -1062,14 +1056,14 @@ class CMD_History(ApiCall): for row in data: status, quality = Quality.splitCompositeStatus(int(row["action"])) - status = _get_status_Strings(status) + status = _get_status_strings(status) if self.type and not status.lower() == self.type: continue row["status"] = status row["quality"] = get_quality_string(quality) - row["date"] = _historyDate_to_dateTimeForm(str(row["date"])) + row["date"] = _history_date_to_datetime_form(str(row["date"])) del row["action"] @@ -1134,15 +1128,15 @@ class CMD_Failed(ApiCall): def run(self): """ Get the failed downloads """ - myDB = db.DBConnection('failed.db', row_type="dict") + my_db = db.DBConnection('failed.db', row_type="dict") - ulimit = min(int(self.limit), 100) - if ulimit == 0: - sqlResults = myDB.select("SELECT * FROM failed") + u_limit = min(int(self.limit), 100) + if u_limit == 0: + sql_results = my_db.select("SELECT * FROM failed") else: - sqlResults = myDB.select("SELECT * FROM failed LIMIT ?", [ulimit]) + sql_results = my_db.select("SELECT * FROM failed LIMIT ?", [u_limit]) - return _responds(RESULT_SUCCESS, sqlResults) + return _responds(RESULT_SUCCESS, sql_results) class CMD_Backlog(ApiCall): @@ -1159,27 +1153,27 @@ class CMD_Backlog(ApiCall): shows = [] - myDB = db.DBConnection(row_type="dict") + my_db = db.DBConnection(row_type="dict") for curShow in sickbeard.showList: - showEps = [] + show_eps = [] - sqlResults = myDB.select( + sql_results = my_db.select( "SELECT tv_episodes.*, tv_shows.paused FROM tv_episodes INNER JOIN tv_shows ON tv_episodes.showid = tv_shows.indexer_id WHERE showid = ? and paused = 0 ORDER BY season DESC, episode DESC", [curShow.indexerid]) - for curResult in sqlResults: + for curResult in sql_results: - curEpCat = curShow.getOverview(int(curResult["status"] or -1)) - if curEpCat and curEpCat in (Overview.WANTED, Overview.QUAL): - showEps.append(curResult) + cur_ep_cat = curShow.getOverview(int(curResult["status"] or -1)) + if cur_ep_cat and cur_ep_cat in (Overview.WANTED, Overview.QUAL): + show_eps.append(curResult) - if showEps: + if show_eps: shows.append({ "indexerid": curShow.indexerid, "show_name": curShow.name, "status": curShow.status, - "episodes": showEps + "episodes": show_eps }) return _responds(RESULT_SUCCESS, shows) @@ -1208,7 +1202,7 @@ class CMD_Logs(ApiCall): def run(self): """ Get the logs """ # 10 = Debug / 20 = Info / 30 = Warning / 40 = Error - minLevel = logger.reverseNames[str(self.min_level).upper()] + min_level = logger.reverseNames[str(self.min_level).upper()] data = [] if os.path.isfile(logger.logFile): @@ -1217,11 +1211,11 @@ class CMD_Logs(ApiCall): regex = r"^(\d\d\d\d)\-(\d\d)\-(\d\d)\s*(\d\d)\:(\d\d):(\d\d)\s*([A-Z]+)\s*(.+?)\s*\:\:\s*(.*)$" - finalData = [] + final_data = [] - numLines = 0 - lastLine = False - numToShow = min(50, len(data)) + num_lines = 0 + last_line = False + num_to_show = min(50, len(data)) for x in reversed(data): @@ -1230,25 +1224,25 @@ class CMD_Logs(ApiCall): if match: level = match.group(7) if level not in logger.reverseNames: - lastLine = False + last_line = False continue - if logger.reverseNames[level] >= minLevel: - lastLine = True - finalData.append(x.rstrip("\n")) + if logger.reverseNames[level] >= min_level: + last_line = True + final_data.append(x.rstrip("\n")) else: - lastLine = False + last_line = False continue - elif lastLine: - finalData.append("AA" + x) + elif last_line: + final_data.append("AA" + x) - numLines += 1 + num_lines += 1 - if numLines >= numToShow: + if num_lines >= num_to_show: break - return _responds(RESULT_SUCCESS, finalData) + return _responds(RESULT_SUCCESS, final_data) class CMD_PostProcess(ApiCall): @@ -1296,7 +1290,7 @@ class CMD_PostProcess(ApiCall): if not self.return_data: data = "" - return _responds(RESULT_SUCCESS, data=data, msg="Started postprocess for %s" % self.path) + return _responds(RESULT_SUCCESS, data=data, msg="Started post-process for %s" % self.path) class CMD_SickBeard(ApiCall): @@ -1341,7 +1335,7 @@ class CMD_SickBeardAddRootDir(ApiCall): location_matched = 0 index = 0 - # dissallow adding/setting an invalid dir + # disallow adding/setting an invalid dir if not ek(os.path.isdir, self.location): return _responds(RESULT_FAILURE, msg="Location is invalid") @@ -1373,7 +1367,7 @@ class CMD_SickBeardAddRootDir(ApiCall): root_dirs_new = '|'.join(unicode(x) for x in root_dirs_new) sickbeard.ROOT_DIRS = root_dirs_new - return _responds(RESULT_SUCCESS, _getRootDirs(), msg="Root directories updated") + return _responds(RESULT_SUCCESS, _get_root_dirs(), msg="Root directories updated") class CMD_SickBeardCheckVersion(ApiCall): @@ -1386,21 +1380,21 @@ class CMD_SickBeardCheckVersion(ApiCall): ApiCall.__init__(self, args, kwargs) def run(self): - checkversion = CheckVersion() - needs_update = checkversion.check_for_new_version() + check_version = CheckVersion() + needs_update = check_version.check_for_new_version() data = { "current_version": { - "branch": checkversion.get_branch(), - "commit": checkversion.updater.get_cur_commit_hash(), - "version": checkversion.updater.get_cur_version(), + "branch": check_version.get_branch(), + "commit": check_version.updater.get_cur_commit_hash(), + "version": check_version.updater.get_cur_version(), }, "latest_version": { - "branch": checkversion.get_branch(), - "commit": checkversion.updater.get_newest_commit_hash(), - "version": checkversion.updater.get_newest_version(), + "branch": check_version.get_branch(), + "commit": check_version.updater.get_newest_commit_hash(), + "version": check_version.updater.get_newest_version(), }, - "commits_offset": checkversion.updater.get_num_commits_behind(), + "commits_offset": check_version.updater.get_num_commits_behind(), "needs_update": needs_update, } @@ -1418,16 +1412,16 @@ class CMD_SickBeardCheckScheduler(ApiCall): def run(self): """ Get information about the scheduler """ - myDB = db.DBConnection() - sqlResults = myDB.select("SELECT last_backlog FROM info") + my_db = db.DBConnection() + sql_results = my_db.select("SELECT last_backlog FROM info") - backlogPaused = sickbeard.searchQueueScheduler.action.is_backlog_paused() # @UndefinedVariable - backlogRunning = sickbeard.searchQueueScheduler.action.is_backlog_in_progress() # @UndefinedVariable - nextBacklog = sickbeard.backlogSearchScheduler.nextRun().strftime(dateFormat).decode(sickbeard.SYS_ENCODING) + backlog_paused = sickbeard.searchQueueScheduler.action.is_backlog_paused() # @UndefinedVariable + backlog_running = sickbeard.searchQueueScheduler.action.is_backlog_in_progress() # @UndefinedVariable + next_backlog = sickbeard.backlogSearchScheduler.nextRun().strftime(dateFormat).decode(sickbeard.SYS_ENCODING) - data = {"backlog_is_paused": int(backlogPaused), "backlog_is_running": int(backlogRunning), - "last_backlog": _ordinal_to_dateForm(sqlResults[0]["last_backlog"]), - "next_backlog": nextBacklog} + data = {"backlog_is_paused": int(backlog_paused), "backlog_is_running": int(backlog_running), + "last_backlog": _ordinal_to_date_form(sql_results[0]["last_backlog"]), + "next_backlog": next_backlog} return _responds(RESULT_SUCCESS, data) @@ -1449,9 +1443,9 @@ class CMD_SickBeardDeleteRootDir(ApiCall): def run(self): """ Delete a root (parent) directory from SickRage """ if sickbeard.ROOT_DIRS == "": - return _responds(RESULT_FAILURE, _getRootDirs(), msg="No root directories detected") + return _responds(RESULT_FAILURE, _get_root_dirs(), msg="No root directories detected") - newIndex = 0 + new_index = 0 root_dirs_new = [] root_dirs = sickbeard.ROOT_DIRS.split('|') index = int(root_dirs[0]) @@ -1463,21 +1457,21 @@ class CMD_SickBeardDeleteRootDir(ApiCall): if not curRootDir == self.location: root_dirs_new.append(curRootDir) else: - newIndex = 0 + new_index = 0 for curIndex, curNewRootDir in enumerate(root_dirs_new): if curNewRootDir is old_root_dir: - newIndex = curIndex + new_index = curIndex break root_dirs_new = [urllib.unquote_plus(x) for x in root_dirs_new] if len(root_dirs_new) > 0: - root_dirs_new.insert(0, newIndex) + root_dirs_new.insert(0, new_index) root_dirs_new = "|".join(unicode(x) for x in root_dirs_new) sickbeard.ROOT_DIRS = root_dirs_new # what if the root dir was not found? - return _responds(RESULT_SUCCESS, _getRootDirs(), msg="Root directory deleted") + return _responds(RESULT_SUCCESS, _get_root_dirs(), msg="Root directory deleted") class CMD_SickBeardGetDefaults(ApiCall): @@ -1492,11 +1486,11 @@ class CMD_SickBeardGetDefaults(ApiCall): def run(self): """ Get SickRage's user default configuration value """ - anyQualities, bestQualities = _mapQuality(sickbeard.QUALITY_DEFAULT) + any_qualities, best_qualities = _map_quality(sickbeard.QUALITY_DEFAULT) data = {"status": statusStrings[sickbeard.STATUS_DEFAULT].lower(), - "flatten_folders": int(sickbeard.FLATTEN_FOLDERS_DEFAULT), "initial": anyQualities, - "archive": bestQualities, "future_show_paused": int(sickbeard.COMING_EPS_DISPLAY_PAUSED)} + "flatten_folders": int(sickbeard.FLATTEN_FOLDERS_DEFAULT), "initial": any_qualities, + "archive": best_qualities, "future_show_paused": int(sickbeard.COMING_EPS_DISPLAY_PAUSED)} return _responds(RESULT_SUCCESS, data) @@ -1530,14 +1524,14 @@ class CMD_SickBeardGetRootDirs(ApiCall): def run(self): """ Get all root (parent) directories """ - return _responds(RESULT_SUCCESS, _getRootDirs()) + return _responds(RESULT_SUCCESS, _get_root_dirs()) class CMD_SickBeardPauseBacklog(ApiCall): _help = { - "desc": "Pause or unpause the backlog search", + "desc": "Pause or un-pause the backlog search", "optionalParameters": { - "pause ": {"desc": "True to pause the backlog search, False to unpause it"} + "pause ": {"desc": "True to pause the backlog search, False to un-pause it"} } } @@ -1549,13 +1543,13 @@ class CMD_SickBeardPauseBacklog(ApiCall): ApiCall.__init__(self, args, kwargs) def run(self): - """ Pause or unpause the backlog search """ + """ Pause or un-pause the backlog search """ if self.pause: sickbeard.searchQueueScheduler.action.pause_backlog() # @UndefinedVariable return _responds(RESULT_SUCCESS, msg="Backlog paused") else: sickbeard.searchQueueScheduler.action.unpause_backlog() # @UndefinedVariable - return _responds(RESULT_SUCCESS, msg="Backlog unpaused") + return _responds(RESULT_SUCCESS, msg="Backlog un-paused") class CMD_SickBeardPing(ApiCall): @@ -1623,23 +1617,23 @@ class CMD_SickBeardSearchIndexers(ApiCall): if self.name and not self.indexerid: # only name was given for _indexer in sickbeard.indexerApi().indexers if self.indexer == 0 else [int(self.indexer)]: - lINDEXER_API_PARMS = sickbeard.indexerApi(_indexer).api_params.copy() + indexer_api_params = sickbeard.indexerApi(_indexer).api_params.copy() if self.lang and not self.lang == sickbeard.INDEXER_DEFAULT_LANGUAGE: - lINDEXER_API_PARMS['language'] = self.lang + indexer_api_params['language'] = self.lang - lINDEXER_API_PARMS['actors'] = False - lINDEXER_API_PARMS['custom_ui'] = classes.AllShowsListUI + indexer_api_params['actors'] = False + indexer_api_params['custom_ui'] = classes.AllShowsListUI - t = sickbeard.indexerApi(_indexer).indexer(**lINDEXER_API_PARMS) + t = sickbeard.indexerApi(_indexer).indexer(**indexer_api_params) try: - apiData = t[str(self.name).encode()] + api_data = t[str(self.name).encode()] except (sickbeard.indexer_shownotfound, sickbeard.indexer_showincomplete, sickbeard.indexer_error): logger.log(u"API :: Unable to find show with id " + str(self.indexerid), logger.WARNING) continue - for curSeries in apiData: + for curSeries in api_data: results.append({indexer_ids[_indexer]: int(curSeries['id']), "name": curSeries['seriesname'], "first_aired": curSeries['firstaired'], @@ -1649,31 +1643,31 @@ class CMD_SickBeardSearchIndexers(ApiCall): elif self.indexerid: for _indexer in sickbeard.indexerApi().indexers if self.indexer == 0 else [int(self.indexer)]: - lINDEXER_API_PARMS = sickbeard.indexerApi(_indexer).api_params.copy() + indexer_api_params = sickbeard.indexerApi(_indexer).api_params.copy() if self.lang and not self.lang == sickbeard.INDEXER_DEFAULT_LANGUAGE: - lINDEXER_API_PARMS['language'] = self.lang + indexer_api_params['language'] = self.lang - lINDEXER_API_PARMS['actors'] = False + indexer_api_params['actors'] = False - t = sickbeard.indexerApi(_indexer).indexer(**lINDEXER_API_PARMS) + t = sickbeard.indexerApi(_indexer).indexer(**indexer_api_params) try: - myShow = t[int(self.indexerid)] + my_show = t[int(self.indexerid)] except (sickbeard.indexer_shownotfound, sickbeard.indexer_showincomplete, sickbeard.indexer_error): logger.log(u"API :: Unable to find show with id " + str(self.indexerid), logger.WARNING) return _responds(RESULT_SUCCESS, {"results": [], "langid": lang_id}) - if not myShow.data['seriesname']: + if not my_show.data['seriesname']: logger.log( u"API :: Found show with indexerid: " + str( self.indexerid) + ", however it contained no show name", logger.DEBUG) return _responds(RESULT_FAILURE, msg="Show contains no name, invalid result") # found show - results = [{indexer_ids[_indexer]: int(myShow.data['id']), - "name": unicode(myShow.data['seriesname']), - "first_aired": myShow.data['firstaired'], + results = [{indexer_ids[_indexer]: int(my_show.data['id']), + "name": unicode(my_show.data['seriesname']), + "first_aired": my_show.data['firstaired'], "indexer": int(_indexer)}] break @@ -1763,18 +1757,18 @@ class CMD_SickBeardSetDefaults(ApiCall): 'fullhdbluray': Quality.FULLHDBLURAY, 'unknown': Quality.UNKNOWN} - iqualityID = [] - aqualityID = [] + i_quality_id = [] + a_quality_id = [] if self.initial: for quality in self.initial: - iqualityID.append(quality_map[quality]) + i_quality_id.append(quality_map[quality]) if self.archive: for quality in self.archive: - aqualityID.append(quality_map[quality]) + a_quality_id.append(quality_map[quality]) - if iqualityID or aqualityID: - sickbeard.QUALITY_DEFAULT = Quality.combineQualities(iqualityID, aqualityID) + if i_quality_id or a_quality_id: + sickbeard.QUALITY_DEFAULT = Quality.combineQualities(i_quality_id, a_quality_id) if self.status: # convert the string status to a int @@ -1782,18 +1776,18 @@ class CMD_SickBeardSetDefaults(ApiCall): if statusStrings[status].lower() == str(self.status).lower(): self.status = status break - # this should be obsolete bcause of the above - if not self.status in statusStrings: + # this should be obsolete because of the above + if self.status not in statusStrings: raise ApiError("Invalid Status") # only allow the status options we want if int(self.status) not in (3, 5, 6, 7): raise ApiError("Status Prohibited") sickbeard.STATUS_DEFAULT = self.status - if self.flatten_folders != None: + if self.flatten_folders is not None: sickbeard.FLATTEN_FOLDERS_DEFAULT = int(self.flatten_folders) - if self.future_show_paused != None: + if self.future_show_paused is not None: sickbeard.COMING_EPS_DISPLAY_PAUSED = int(self.future_show_paused) return _responds(RESULT_SUCCESS, msg="Saved defaults") @@ -1826,11 +1820,11 @@ class CMD_SickBeardUpdate(ApiCall): ApiCall.__init__(self, args, kwargs) def run(self): - checkversion = CheckVersion() + check_version = CheckVersion() - if checkversion.check_for_new_version(): - if checkversion.run_backup_if_safe(): - checkversion.update() + if check_version.check_for_new_version(): + if check_version.run_backup_if_safe(): + check_version.update() return _responds(RESULT_SUCCESS, msg="SickRage is updating ...") @@ -1859,76 +1853,76 @@ class CMD_Show(ApiCall): def run(self): """ Get detailed information about a show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") - showDict = { + show_dict = { "season_list": CMD_ShowSeasonList((), {"indexerid": self.indexerid}).run()["data"], "cache": CMD_ShowCache((), {"indexerid": self.indexerid}).run()["data"] } - genreList = [] - if showObj.genre: - genreListTmp = showObj.genre.split("|") - for genre in genreListTmp: + genre_list = [] + if show_obj.genre: + genre_list_tmp = show_obj.genre.split("|") + for genre in genre_list_tmp: if genre: - genreList.append(genre) + genre_list.append(genre) - showDict["genre"] = genreList - showDict["quality"] = get_quality_string(showObj.quality) + show_dict["genre"] = genre_list + show_dict["quality"] = get_quality_string(show_obj.quality) - anyQualities, bestQualities = _mapQuality(showObj.quality) - showDict["quality_details"] = {"initial": anyQualities, "archive": bestQualities} + any_qualities, best_qualities = _map_quality(show_obj.quality) + show_dict["quality_details"] = {"initial": any_qualities, "archive": best_qualities} try: - showDict["location"] = showObj.location + show_dict["location"] = show_obj.location except ShowDirectoryNotFoundException: - showDict["location"] = "" - - showDict["language"] = showObj.lang - showDict["show_name"] = showObj.name - showDict["paused"] = (0, 1)[showObj.paused] - showDict["subtitles"] = (0, 1)[showObj.subtitles] - showDict["air_by_date"] = (0, 1)[showObj.air_by_date] - showDict["flatten_folders"] = (0, 1)[showObj.flatten_folders] - showDict["sports"] = (0, 1)[showObj.sports] - showDict["anime"] = (0, 1)[showObj.anime] - showDict["airs"] = str(showObj.airs).replace('am', ' AM').replace('pm', ' PM').replace(' ', ' ') - showDict["dvdorder"] = (0, 1)[showObj.dvdorder] - - if showObj.rls_require_words: - showDict["rls_require_words"] = showObj.rls_require_words.split(", ") + show_dict["location"] = "" + + show_dict["language"] = show_obj.lang + show_dict["show_name"] = show_obj.name + show_dict["paused"] = (0, 1)[show_obj.paused] + show_dict["subtitles"] = (0, 1)[show_obj.subtitles] + show_dict["air_by_date"] = (0, 1)[show_obj.air_by_date] + show_dict["flatten_folders"] = (0, 1)[show_obj.flatten_folders] + show_dict["sports"] = (0, 1)[show_obj.sports] + show_dict["anime"] = (0, 1)[show_obj.anime] + show_dict["airs"] = str(show_obj.airs).replace('am', ' AM').replace('pm', ' PM').replace(' ', ' ') + show_dict["dvdorder"] = (0, 1)[show_obj.dvdorder] + + if show_obj.rls_require_words: + show_dict["rls_require_words"] = show_obj.rls_require_words.split(", ") else: - showDict["rls_require_words"] = [] + show_dict["rls_require_words"] = [] - if showObj.rls_ignore_words: - showDict["rls_ignore_words"] = showObj.rls_ignore_words.split(", ") + if show_obj.rls_ignore_words: + show_dict["rls_ignore_words"] = show_obj.rls_ignore_words.split(", ") else: - showDict["rls_ignore_words"] = [] + show_dict["rls_ignore_words"] = [] - showDict["scene"] = (0, 1)[showObj.scene] - showDict["archive_firstmatch"] = (0, 1)[showObj.archive_firstmatch] + show_dict["scene"] = (0, 1)[show_obj.scene] + show_dict["archive_firstmatch"] = (0, 1)[show_obj.archive_firstmatch] - showDict["indexerid"] = showObj.indexerid - showDict["tvdbid"] = helpers.mapIndexersToShow(showObj)[1] - showDict["imdbid"] = showObj.imdbid + show_dict["indexerid"] = show_obj.indexerid + show_dict["tvdbid"] = helpers.mapIndexersToShow(show_obj)[1] + show_dict["imdbid"] = show_obj.imdbid - showDict["network"] = showObj.network - if not showDict["network"]: - showDict["network"] = "" - showDict["status"] = showObj.status + show_dict["network"] = show_obj.network + if not show_dict["network"]: + show_dict["network"] = "" + show_dict["status"] = show_obj.status - if helpers.tryInt(showObj.nextaired, 1) > 693595: - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting( - network_timezones.parse_date_time(showObj.nextaired, showDict['airs'], showDict['network'])) - showDict['airs'] = sbdatetime.sbdatetime.sbftime(dtEpisodeAirs, t_preset=timeFormat).lstrip('0').replace( + if helpers.tryInt(show_obj.nextaired, 1) > 693595: + dt_episode_airs = sbdatetime.sbdatetime.convert_to_setting( + network_timezones.parse_date_time(show_obj.nextaired, show_dict['airs'], show_dict['network'])) + show_dict['airs'] = sbdatetime.sbdatetime.sbftime(dt_episode_airs, t_preset=timeFormat).lstrip('0').replace( ' 0', ' ') - showDict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + show_dict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dt_episode_airs, d_preset=dateFormat) else: - showDict['next_ep_airdate'] = '' + show_dict['next_ep_airdate'] = '' - return _responds(RESULT_SUCCESS, showDict) + return _responds(RESULT_SUCCESS, show_dict) class CMD_ShowAddExisting(ApiCall): @@ -1967,27 +1961,27 @@ class CMD_ShowAddExisting(ApiCall): def run(self): """ Add an existing show in SickRage """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if show_obj: return _responds(RESULT_FAILURE, msg="An existing indexerid already exists in the database") if not ek(os.path.isdir, self.location): return _responds(RESULT_FAILURE, msg='Not a valid location') - indexerName = None - indexerResult = CMD_SickBeardSearchIndexers([], {indexer_ids[self.indexer]: self.indexerid}).run() + indexer_name = None + indexer_result = CMD_SickBeardSearchIndexers([], {indexer_ids[self.indexer]: self.indexerid}).run() - if indexerResult['result'] == result_type_map[RESULT_SUCCESS]: - if not indexerResult['data']['results']: + if indexer_result['result'] == result_type_map[RESULT_SUCCESS]: + if not indexer_result['data']['results']: return _responds(RESULT_FAILURE, msg="Empty results returned, check indexerid and try again") - if len(indexerResult['data']['results']) == 1 and 'name' in indexerResult['data']['results'][0]: - indexerName = indexerResult['data']['results'][0]['name'] + if len(indexer_result['data']['results']) == 1 and 'name' in indexer_result['data']['results'][0]: + indexer_name = indexer_result['data']['results'][0]['name'] - if not indexerName: + if not indexer_name: return _responds(RESULT_FAILURE, msg="Unable to retrieve information from indexer") # set indexer so we can pass it along when adding show to SR - indexer = indexerResult['data']['results'][0]['indexer'] + indexer = indexer_result['data']['results'][0]['indexer'] quality_map = {'sdtv': Quality.SDTV, 'sddvd': Quality.SDDVD, @@ -2000,28 +1994,28 @@ class CMD_ShowAddExisting(ApiCall): 'fullhdbluray': Quality.FULLHDBLURAY, 'unknown': Quality.UNKNOWN} - # use default quality as a failsafe - newQuality = int(sickbeard.QUALITY_DEFAULT) - iqualityID = [] - aqualityID = [] + # use default quality as a fail-safe + new_quality = int(sickbeard.QUALITY_DEFAULT) + i_quality_id = [] + a_quality_id = [] if self.initial: for quality in self.initial: - iqualityID.append(quality_map[quality]) + i_quality_id.append(quality_map[quality]) if self.archive: for quality in self.archive: - aqualityID.append(quality_map[quality]) + a_quality_id.append(quality_map[quality]) - if iqualityID or aqualityID: - newQuality = Quality.combineQualities(iqualityID, aqualityID) + if i_quality_id or a_quality_id: + new_quality = Quality.combineQualities(i_quality_id, a_quality_id) sickbeard.showQueueScheduler.action.addShow( int(indexer), int(self.indexerid), self.location, default_status=sickbeard.STATUS_DEFAULT, - quality=newQuality, flatten_folders=int(self.flatten_folders), subtitles=self.subtitles, + quality=new_quality, flatten_folders=int(self.flatten_folders), subtitles=self.subtitles, default_status_after=sickbeard.STATUS_DEFAULT_AFTER, archive=self.archive_firstmatch ) - return _responds(RESULT_SUCCESS, {"name": indexerName}, indexerName + " has been queued to be added") + return _responds(RESULT_SUCCESS, {"name": indexer_name}, indexer_name + " has been queued to be added") class CMD_ShowAddNew(ApiCall): @@ -2082,8 +2076,8 @@ class CMD_ShowAddNew(ApiCall): def run(self): """ Add a new show to SickRage """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if show_obj: return _responds(RESULT_FAILURE, msg="An existing indexerid already exists in database") if not self.location: @@ -2109,23 +2103,23 @@ class CMD_ShowAddNew(ApiCall): 'fullhdbluray': Quality.FULLHDBLURAY, 'unknown': Quality.UNKNOWN} - # use default quality as a failsafe - newQuality = int(sickbeard.QUALITY_DEFAULT) - iqualityID = [] - aqualityID = [] + # use default quality as a fail-safe + new_quality = int(sickbeard.QUALITY_DEFAULT) + i_quality_id = [] + a_quality_id = [] if self.initial: for quality in self.initial: - iqualityID.append(quality_map[quality]) + i_quality_id.append(quality_map[quality]) if self.archive: for quality in self.archive: - aqualityID.append(quality_map[quality]) + a_quality_id.append(quality_map[quality]) - if iqualityID or aqualityID: - newQuality = Quality.combineQualities(iqualityID, aqualityID) + if i_quality_id or a_quality_id: + new_quality = Quality.combineQualities(i_quality_id, a_quality_id) - # use default status as a failsafe - newStatus = sickbeard.STATUS_DEFAULT + # use default status as a fail-safe + new_status = sickbeard.STATUS_DEFAULT if self.status: # convert the string status to a int for status in statusStrings: @@ -2139,9 +2133,9 @@ class CMD_ShowAddNew(ApiCall): # only allow the status options we want if int(self.status) not in (WANTED, SKIPPED, IGNORED): return _responds(RESULT_FAILURE, msg="Status prohibited") - newStatus = self.status + new_status = self.status - # use default status as a failsafe + # use default status as a fail-safe default_ep_status_after = sickbeard.STATUS_DEFAULT_AFTER if self.future_status: # convert the string status to a int @@ -2158,43 +2152,43 @@ class CMD_ShowAddNew(ApiCall): return _responds(RESULT_FAILURE, msg="Status prohibited") default_ep_status_after = self.future_status - indexerName = None - indexerResult = CMD_SickBeardSearchIndexers([], {indexer_ids[self.indexer]: self.indexerid}).run() + indexer_name = None + indexer_result = CMD_SickBeardSearchIndexers([], {indexer_ids[self.indexer]: self.indexerid}).run() - if indexerResult['result'] == result_type_map[RESULT_SUCCESS]: - if not indexerResult['data']['results']: + if indexer_result['result'] == result_type_map[RESULT_SUCCESS]: + if not indexer_result['data']['results']: return _responds(RESULT_FAILURE, msg="Empty results returned, check indexerid and try again") - if len(indexerResult['data']['results']) == 1 and 'name' in indexerResult['data']['results'][0]: - indexerName = indexerResult['data']['results'][0]['name'] + if len(indexer_result['data']['results']) == 1 and 'name' in indexer_result['data']['results'][0]: + indexer_name = indexer_result['data']['results'][0]['name'] - if not indexerName: + if not indexer_name: return _responds(RESULT_FAILURE, msg="Unable to retrieve information from indexer") # set indexer for found show so we can pass it along - indexer = indexerResult['data']['results'][0]['indexer'] + indexer = indexer_result['data']['results'][0]['indexer'] # moved the logic check to the end in an attempt to eliminate empty directory being created from previous errors - showPath = ek(os.path.join, self.location, helpers.sanitizeFileName(indexerName)) + show_path = ek(os.path.join, self.location, helpers.sanitizeFileName(indexer_name)) # don't create show dir if config says not to if sickbeard.ADD_SHOWS_WO_DIR: - logger.log(u"Skipping initial creation of " + showPath + " due to config.ini setting") + logger.log(u"Skipping initial creation of " + show_path + " due to config.ini setting") else: - dir_exists = helpers.makeDir(showPath) + dir_exists = helpers.makeDir(show_path) if not dir_exists: - logger.log(u"API :: Unable to create the folder " + showPath + ", can't add the show", logger.ERROR) - return _responds(RESULT_FAILURE, {"path": showPath}, - "Unable to create the folder " + showPath + ", can't add the show") + logger.log(u"API :: Unable to create the folder " + show_path + ", can't add the show", logger.ERROR) + return _responds(RESULT_FAILURE, {"path": show_path}, + "Unable to create the folder " + show_path + ", can't add the show") else: - helpers.chmodAsParent(showPath) + helpers.chmodAsParent(show_path) sickbeard.showQueueScheduler.action.addShow( - int(indexer), int(self.indexerid), showPath, default_status=newStatus, quality=newQuality, + int(indexer), int(self.indexerid), show_path, default_status=new_status, quality=new_quality, flatten_folders=int(self.flatten_folders), lang=self.lang, subtitles=self.subtitles, anime=self.anime, scene=self.scene, default_status_after=default_ep_status_after, archive=self.archive_firstmatch ) - return _responds(RESULT_SUCCESS, {"name": indexerName}, indexerName + " has been queued to be added") + return _responds(RESULT_SUCCESS, {"name": indexer_name}, indexer_name + " has been queued to be added") class CMD_ShowCache(ApiCall): @@ -2217,8 +2211,8 @@ class CMD_ShowCache(ApiCall): def run(self): """ Check SickRage's cache to see if the images (poster, banner, fanart) for a show are valid """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") # TODO: catch if cache dir is missing/invalid.. so it doesn't break show/show.cache @@ -2229,9 +2223,9 @@ class CMD_ShowCache(ApiCall): has_poster = 0 has_banner = 0 - if ek(os.path.isfile, cache_obj.poster_path(showObj.indexerid)): + if ek(os.path.isfile, cache_obj.poster_path(show_obj.indexerid)): has_poster = 1 - if ek(os.path.isfile, cache_obj.banner_path(showObj.indexerid)): + if ek(os.path.isfile, cache_obj.banner_path(show_obj.indexerid)): has_banner = 1 return _responds(RESULT_SUCCESS, {"poster": has_poster, "banner": has_banner}) @@ -2263,7 +2257,7 @@ class CMD_ShowDelete(ApiCall): """ Delete a show in SickRage """ error, show = Show.delete(self.indexerid, self.removefiles) - if error is not None: + if error: return _responds(RESULT_FAILURE, msg=error) return _responds(RESULT_SUCCESS, msg='%s has been queued to be deleted' % show.name) @@ -2289,13 +2283,13 @@ class CMD_ShowGetQuality(ApiCall): def run(self): """ Get the quality setting of a show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") - anyQualities, bestQualities = _mapQuality(showObj.quality) + any_qualities, best_qualities = _map_quality(show_obj.quality) - return _responds(RESULT_SUCCESS, {"initial": anyQualities, "archive": bestQualities}) + return _responds(RESULT_SUCCESS, {"initial": any_qualities, "archive": best_qualities}) class CMD_ShowGetPoster(ApiCall): @@ -2406,7 +2400,7 @@ class CMD_ShowGetFanArt(ApiCall): class CMD_ShowPause(ApiCall): _help = { - "desc": "Pause or unpause a show", + "desc": "Pause or un-pause a show", "requiredParameters": { "indexerid": {"desc": "Unique ID of a show"}, }, @@ -2425,10 +2419,10 @@ class CMD_ShowPause(ApiCall): ApiCall.__init__(self, args, kwargs) def run(self): - """ Pause or unpause a show """ + """ Pause or un-pause a show """ error, show = Show.pause(self.indexerid, self.pause) - if error is not None: + if error: return _responds(RESULT_FAILURE, msg=error) return _responds(RESULT_SUCCESS, msg='%s has been %s' % (show.name, ('resumed', 'paused')[show.paused])) @@ -2456,7 +2450,7 @@ class CMD_ShowRefresh(ApiCall): """ Refresh a show in SickRage """ error, show = Show.refresh(self.indexerid) - if error is not None: + if error: return _responds(RESULT_FAILURE, msg=error) return _responds(RESULT_SUCCESS, msg='%s has queued to be refreshed' % show.name) @@ -2484,22 +2478,22 @@ class CMD_ShowSeasonList(ApiCall): def run(self): """ Get the list of seasons of a show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") - myDB = db.DBConnection(row_type="dict") + my_db = db.DBConnection(row_type="dict") if self.sort == "asc": - sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season ASC", - [self.indexerid]) + sql_results = my_db.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season ASC", + [self.indexerid]) else: - sqlResults = myDB.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season DESC", - [self.indexerid]) - seasonList = [] # a list with all season numbers - for row in sqlResults: - seasonList.append(int(row["season"])) + sql_results = my_db.select("SELECT DISTINCT season FROM tv_episodes WHERE showid = ? ORDER BY season DESC", + [self.indexerid]) + season_list = [] # a list with all season numbers + for row in sql_results: + season_list.append(int(row["season"])) - return _responds(RESULT_SUCCESS, seasonList) + return _responds(RESULT_SUCCESS, season_list) class CMD_ShowSeasons(ApiCall): @@ -2524,57 +2518,57 @@ class CMD_ShowSeasons(ApiCall): def run(self): """ Get the list of episodes for one or all seasons of a show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + sho_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not sho_obj: return _responds(RESULT_FAILURE, msg="Show not found") - myDB = db.DBConnection(row_type="dict") + my_db = db.DBConnection(row_type="dict") - if self.season == None: - sqlResults = myDB.select( + if self.season is None: + sql_results = my_db.select( "SELECT name, episode, airdate, status, release_name, season, location, file_size, subtitles FROM tv_episodes WHERE showid = ?", [self.indexerid]) seasons = {} - for row in sqlResults: + for row in sql_results: status, quality = Quality.splitCompositeStatus(int(row["status"])) - row["status"] = _get_status_Strings(status) + row["status"] = _get_status_strings(status) row["quality"] = get_quality_string(quality) if helpers.tryInt(row['airdate'], 1) > 693595: # 1900 - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting( - network_timezones.parse_date_time(row['airdate'], showObj.airs, showObj.network)) - row['airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + dt_episode_airs = sbdatetime.sbdatetime.convert_to_setting( + network_timezones.parse_date_time(row['airdate'], sho_obj.airs, sho_obj.network)) + row['airdate'] = sbdatetime.sbdatetime.sbfdate(dt_episode_airs, d_preset=dateFormat) else: row['airdate'] = 'Never' - curSeason = int(row["season"]) - curEpisode = int(row["episode"]) + cur_season = int(row["season"]) + cur_episode = int(row["episode"]) del row["season"] del row["episode"] - if not curSeason in seasons: - seasons[curSeason] = {} - seasons[curSeason][curEpisode] = row + if cur_season not in seasons: + seasons[cur_season] = {} + seasons[cur_season][cur_episode] = row else: - sqlResults = myDB.select( + sql_results = my_db.select( "SELECT name, episode, airdate, status, location, file_size, release_name, subtitles FROM tv_episodes WHERE showid = ? AND season = ?", [self.indexerid, self.season]) - if len(sqlResults) is 0: + if len(sql_results) == 0: return _responds(RESULT_FAILURE, msg="Season not found") seasons = {} - for row in sqlResults: - curEpisode = int(row["episode"]) + for row in sql_results: + cur_episode = int(row["episode"]) del row["episode"] status, quality = Quality.splitCompositeStatus(int(row["status"])) - row["status"] = _get_status_Strings(status) + row["status"] = _get_status_strings(status) row["quality"] = get_quality_string(quality) if helpers.tryInt(row['airdate'], 1) > 693595: # 1900 - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting( - network_timezones.parse_date_time(row['airdate'], showObj.airs, showObj.network)) - row['airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + dt_episode_airs = sbdatetime.sbdatetime.convert_to_setting( + network_timezones.parse_date_time(row['airdate'], sho_obj.airs, sho_obj.network)) + row['airdate'] = sbdatetime.sbdatetime.sbfdate(dt_episode_airs, d_preset=dateFormat) else: row['airdate'] = 'Never' - if not curEpisode in seasons: - seasons[curEpisode] = {} - seasons[curEpisode] = row + if cur_episode not in seasons: + seasons[cur_episode] = {} + seasons[cur_episode] = row return _responds(RESULT_SUCCESS, seasons) @@ -2597,7 +2591,7 @@ class CMD_ShowSetQuality(ApiCall): self.indexerid, args = self.check_params(args, kwargs, "indexerid", None, True, "int", []) # optional # this for whatever reason removes hdbluray not sdtv... which is just wrong. reverting to previous code.. plus we didnt use the new code everywhere. - # self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", _getQualityMap().values()[1:]) + # self.archive, args = self.check_params(args, kwargs, "archive", None, False, "list", _get_quality_map().values()[1:]) self.initial, args = self.check_params(args, kwargs, "initial", None, False, "list", ["sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown"]) @@ -2610,8 +2604,8 @@ class CMD_ShowSetQuality(ApiCall): def run(self): """ Set the quality setting of a show. If no quality is provided, the default user setting is used. """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") quality_map = {'sdtv': Quality.SDTV, @@ -2625,24 +2619,24 @@ class CMD_ShowSetQuality(ApiCall): 'fullhdbluray': Quality.FULLHDBLURAY, 'unknown': Quality.UNKNOWN} - # use default quality as a failsafe - newQuality = int(sickbeard.QUALITY_DEFAULT) - iqualityID = [] - aqualityID = [] + # use default quality as a fail-safe + new_quality = int(sickbeard.QUALITY_DEFAULT) + i_quality_id = [] + a_quality_id = [] if self.initial: for quality in self.initial: - iqualityID.append(quality_map[quality]) + i_quality_id.append(quality_map[quality]) if self.archive: for quality in self.archive: - aqualityID.append(quality_map[quality]) + a_quality_id.append(quality_map[quality]) - if iqualityID or aqualityID: - newQuality = Quality.combineQualities(iqualityID, aqualityID) - showObj.quality = newQuality + if i_quality_id or a_quality_id: + new_quality = Quality.combineQualities(i_quality_id, a_quality_id) + show_obj.quality = new_quality return _responds(RESULT_SUCCESS, - msg=showObj.name + " quality has been changed to " + get_quality_string(showObj.quality)) + msg=show_obj.name + " quality has been changed to " + get_quality_string(show_obj.quality)) class CMD_ShowStats(ApiCall): @@ -2665,21 +2659,19 @@ class CMD_ShowStats(ApiCall): def run(self): """ Get episode statistics for a given show """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") # show stats - episode_status_counts_total = {} - episode_status_counts_total["total"] = 0 + episode_status_counts_total = {"total": 0} for status in statusStrings: if status in [UNKNOWN, DOWNLOADED, SNATCHED, SNATCHED_PROPER, ARCHIVED]: continue episode_status_counts_total[status] = 0 # add all the downloaded qualities - episode_qualities_counts_download = {} - episode_qualities_counts_download["total"] = 0 + episode_qualities_counts_download = {"total": 0} for statusCode in Quality.DOWNLOADED + Quality.ARCHIVED: status, quality = Quality.splitCompositeStatus(statusCode) if quality in [Quality.NONE]: @@ -2687,19 +2679,18 @@ class CMD_ShowStats(ApiCall): episode_qualities_counts_download[statusCode] = 0 # add all snatched qualities - episode_qualities_counts_snatch = {} - episode_qualities_counts_snatch["total"] = 0 + episode_qualities_counts_snatch = {"total": 0} for statusCode in Quality.SNATCHED + Quality.SNATCHED_PROPER: status, quality = Quality.splitCompositeStatus(statusCode) if quality in [Quality.NONE]: continue episode_qualities_counts_snatch[statusCode] = 0 - myDB = db.DBConnection(row_type="dict") - sqlResults = myDB.select("SELECT status, season FROM tv_episodes WHERE season != 0 AND showid = ?", - [self.indexerid]) + my_db = db.DBConnection(row_type="dict") + sql_results = my_db.select("SELECT status, season FROM tv_episodes WHERE season != 0 AND showid = ?", + [self.indexerid]) # the main loop that goes through all episodes - for row in sqlResults: + for row in sql_results: status, quality = Quality.splitCompositeStatus(int(row["status"])) episode_status_counts_total["total"] += 1 @@ -2710,36 +2701,35 @@ class CMD_ShowStats(ApiCall): elif status in Quality.SNATCHED + Quality.SNATCHED_PROPER: episode_qualities_counts_snatch["total"] += 1 episode_qualities_counts_snatch[int(row["status"])] += 1 - elif status == 0: # we dont count NONE = 0 = N/A + elif status == 0: # we don't count NONE = 0 = N/A pass else: episode_status_counts_total[status] += 1 # the outgoing container - episodes_stats = {} - episodes_stats["downloaded"] = {} + episodes_stats = {"downloaded": {}} # turning codes into strings for statusCode in episode_qualities_counts_download: if statusCode == "total": episodes_stats["downloaded"]["total"] = episode_qualities_counts_download[statusCode] continue status, quality = Quality.splitCompositeStatus(int(statusCode)) - statusString = Quality.qualityStrings[quality].lower().replace(" ", "_").replace("(", "").replace(")", "") - episodes_stats["downloaded"][statusString] = episode_qualities_counts_download[statusCode] + status_string = Quality.qualityStrings[quality].lower().replace(" ", "_").replace("(", "").replace(")", "") + episodes_stats["downloaded"][status_string] = episode_qualities_counts_download[statusCode] episodes_stats["snatched"] = {} - # truning codes into strings + # turning codes into strings # and combining proper and normal for statusCode in episode_qualities_counts_snatch: if statusCode == "total": episodes_stats["snatched"]["total"] = episode_qualities_counts_snatch[statusCode] continue status, quality = Quality.splitCompositeStatus(int(statusCode)) - statusString = Quality.qualityStrings[quality].lower().replace(" ", "_").replace("(", "").replace(")", "") + status_string = Quality.qualityStrings[quality].lower().replace(" ", "_").replace("(", "").replace(")", "") if Quality.qualityStrings[quality] in episodes_stats["snatched"]: - episodes_stats["snatched"][statusString] += episode_qualities_counts_snatch[statusCode] + episodes_stats["snatched"][status_string] += episode_qualities_counts_snatch[statusCode] else: - episodes_stats["snatched"][statusString] = episode_qualities_counts_snatch[statusCode] + episodes_stats["snatched"][status_string] = episode_qualities_counts_snatch[statusCode] # episodes_stats["total"] = {} for statusCode in episode_status_counts_total: @@ -2747,9 +2737,9 @@ class CMD_ShowStats(ApiCall): episodes_stats["total"] = episode_status_counts_total[statusCode] continue status, quality = Quality.splitCompositeStatus(int(statusCode)) - statusString = statusStrings[statusCode].lower().replace(" ", "_").replace("(", "").replace( + status_string = statusStrings[statusCode].lower().replace(" ", "_").replace("(", "").replace( ")", "") - episodes_stats[statusString] = episode_status_counts_total[statusCode] + episodes_stats[status_string] = episode_status_counts_total[statusCode] return _responds(RESULT_SUCCESS, episodes_stats) @@ -2774,16 +2764,16 @@ class CMD_ShowUpdate(ApiCall): def run(self): """ Update a show in SickRage """ - showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) - if not showObj: + show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(self.indexerid)) + if not show_obj: return _responds(RESULT_FAILURE, msg="Show not found") try: - sickbeard.showQueueScheduler.action.updateShow(showObj, True) # @UndefinedVariable - return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has queued to be updated") + sickbeard.showQueueScheduler.action.updateShow(show_obj, True) # @UndefinedVariable + return _responds(RESULT_SUCCESS, msg=str(show_obj.name) + " has queued to be updated") except CantUpdateShowException as e: logger.log(u"API::Unable to update show: {0}".format(str(e)), logger.DEBUG) - return _responds(RESULT_FAILURE, msg="Unable to update " + str(showObj.name)) + return _responds(RESULT_FAILURE, msg="Unable to update " + str(show_obj.name)) class CMD_Shows(ApiCall): @@ -2808,12 +2798,12 @@ class CMD_Shows(ApiCall): shows = {} for curShow in sickbeard.showList: - if self.paused is not None and bool(self.paused) != bool(curShow.paused): + if not self.paused and not curShow.paused: continue - indexerShow = helpers.mapIndexersToShow(curShow) + indexer_show = helpers.mapIndexersToShow(curShow) - showDict = { + show_dict = { "paused": (0, 1)[curShow.paused], "quality": get_quality_string(curShow.quality), "language": curShow.lang, @@ -2821,7 +2811,7 @@ class CMD_Shows(ApiCall): "sports": (0, 1)[curShow.sports], "anime": (0, 1)[curShow.anime], "indexerid": curShow.indexerid, - "tvdbid": indexerShow[1], + "tvdbid": indexer_show[1], "network": curShow.network, "show_name": curShow.name, "status": curShow.status, @@ -2829,19 +2819,19 @@ class CMD_Shows(ApiCall): } if helpers.tryInt(curShow.nextaired, 1) > 693595: # 1900 - dtEpisodeAirs = sbdatetime.sbdatetime.convert_to_setting( - network_timezones.parse_date_time(curShow.nextaired, curShow.airs, showDict['network'])) - showDict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dtEpisodeAirs, d_preset=dateFormat) + dt_episode_airs = sbdatetime.sbdatetime.convert_to_setting( + network_timezones.parse_date_time(curShow.nextaired, curShow.airs, show_dict['network'])) + show_dict['next_ep_airdate'] = sbdatetime.sbdatetime.sbfdate(dt_episode_airs, d_preset=dateFormat) else: - showDict['next_ep_airdate'] = '' + show_dict['next_ep_airdate'] = '' - showDict["cache"] = CMD_ShowCache((), {"indexerid": curShow.indexerid}).run()["data"] - if not showDict["network"]: - showDict["network"] = "" + show_dict["cache"] = CMD_ShowCache((), {"indexerid": curShow.indexerid}).run()["data"] + if not show_dict["network"]: + show_dict["network"] = "" if self.sort == "name": - shows[curShow.name] = showDict + shows[curShow.name] = show_dict else: - shows[curShow.indexerid] = showDict + shows[curShow.indexerid] = show_dict return _responds(RESULT_SUCCESS, shows) diff --git a/tests/common_tests.py b/tests/common_tests.py index 1ba62d02d5e958dccf085fc0b2065aed7782fc1b..b0e6a1df03d3cb955f6a2afb0d9fe0b20d2dedbb 100644 --- a/tests/common_tests.py +++ b/tests/common_tests.py @@ -236,7 +236,7 @@ class StatusStringsTest(unittest.TestCase): for i in unused: if i is None: with self.assertRaises(TypeError): - status_strings[str(i)] = 1 # 'None' != None + status_strings[str(i)] = 1 # 'None' is not None status_strings[i] = 1 # ...but None can still be used as a key else: status_strings[str(i)] = 1