diff --git a/gui/slick/js/addExistingShow.js b/gui/slick/js/addExistingShow.js index f4d04767..18498488 100644 --- a/gui/slick/js/addExistingShow.js +++ b/gui/slick/js/addExistingShow.js @@ -37,7 +37,7 @@ $(document).ready(function() { $('.dir_check').each(function(i,w){ if ($(w).is(':checked')) { if (url.length) - url += '&'; + url += '&' url += 'rootDir=' + encodeURIComponent($(w).attr('id')); } }); diff --git a/gui/slick/js/ajaxEpSubtitles.js b/gui/slick/js/ajaxEpSubtitles.js index 59cd843a..99094ef6 100644 --- a/gui/slick/js/ajaxEpSubtitles.js +++ b/gui/slick/js/ajaxEpSubtitles.js @@ -10,7 +10,7 @@ if (data.result != "failure" && data.result != "No subtitles downloaded") { // clear and update the subtitles column with new informations var subtitles = data.subtitles.split(','); - subtitles_td.empty(); + subtitles_td.empty() $.each(subtitles,function(index, language){ if (language != "" && language != "und") { if (index != subtitles.length - 1) { diff --git a/gui/slick/js/configPostProcessing.js b/gui/slick/js/configPostProcessing.js index 897e8082..ffc3a63f 100644 --- a/gui/slick/js/configPostProcessing.js +++ b/gui/slick/js/configPostProcessing.js @@ -238,8 +238,8 @@ $(document).ready(function () { config_arr.push(show_metadata ? '1' : '0'); config_arr.push(episode_metadata ? '1' : '0'); config_arr.push(fanart ? '1' : '0'); - config_arr.push(poster ? '1' : '0'); - config_arr.push(banner ? '1' : '0'); + config_arr.push(poster ? '1' : '0'); + config_arr.push(banner ? '1' : '0'); config_arr.push(episode_thumbnails ? '1' : '0'); config_arr.push(season_posters ? '1' : '0'); config_arr.push(season_banners ? '1' : '0'); @@ -274,7 +274,7 @@ $(document).ready(function () { $(this).showHideMetadata(); } - }; + } $(this).refreshMetadataConfig(true); $('img[title]').qtip( { @@ -295,7 +295,7 @@ $(document).ready(function () { position: { viewport: $(window), at: 'top center', - my: 'bottom center' + my: 'bottom center', }, style: { tip: { @@ -315,7 +315,7 @@ $(document).ready(function () { position: { viewport: $(window), at: 'center left', - my: 'center right' + my: 'center right', }, style: { tip: { diff --git a/gui/slick/js/configProviders.js b/gui/slick/js/configProviders.js index 3fe2f913..b5f04da1 100644 --- a/gui/slick/js/configProviders.js +++ b/gui/slick/js/configProviders.js @@ -1,40 +1,40 @@ $(document).ready(function(){ - $.fn.showHideProviders = function () { - $('.providerDiv').each(function () { + $.fn.showHideProviders = function() { + $('.providerDiv').each(function(){ var providerName = $(this).attr('id'); var selectedProvider = $('#editAProvider :selected').val(); - if (selectedProvider + 'Div' == providerName) + if (selectedProvider+'Div' == providerName) $(this).show(); else $(this).hide(); }); - }; + } $.fn.addProvider = function (id, name, url, key, isDefault, showProvider) { - url = $.trim(url); - if (!url) - return; - - if (!/^https?:\/\//i.test(url)) - url = "http://" + url; - + url = $.trim(url); + if (!url) + return; + + if (!/^https?:\/\//i.test(url)) + url = "http://" + url; + if (url.match('/$') == null) url = url + '/'; var newData = [isDefault, [name, url, key]]; newznabProviders[id] = newData; - if (!isDefault) { + if (!isDefault){ $('#editANewznabProvider').addOption(id, name); $(this).populateNewznabSection(); } - if ($('#provider_order_list > #' + id).length == 0 && showProvider != false) { - var toAdd = '
  • ' + name + ' ' + name + '
  • ' + if ($('#provider_order_list > #'+id).length == 0 && showProvider != false) { + var toAdd = '
  • '+name+' '+name+'
  • ' $('#provider_order_list').append(toAdd); $('#provider_order_list').sortable("refresh"); @@ -42,7 +42,7 @@ $(document).ready(function(){ $(this).makeNewznabProviderString(); - }; + } $.fn.addTorrentRssProvider = function (id, name, url) { @@ -52,8 +52,8 @@ $(document).ready(function(){ $('#editATorrentRssProvider').addOption(id, name); $(this).populateTorrentRssSection(); - if ($('#provider_order_list > #' + id).length == 0) { - var toAdd = '
  • ' + name + ' ' + name + '
  • ' + if ($('#provider_order_list > #'+id).length == 0) { + var toAdd = '
  • '+name+' '+name+'
  • ' $('#provider_order_list').append(toAdd); $('#provider_order_list').sortable("refresh"); @@ -61,7 +61,7 @@ $(document).ready(function(){ $(this).makeTorrentRssProviderString(); - }; + } $.fn.updateProvider = function (id, url, key) { @@ -72,38 +72,38 @@ $(document).ready(function(){ $(this).makeNewznabProviderString(); - }; + } $.fn.deleteProvider = function (id) { $('#editANewznabProvider').removeOption(id); delete newznabProviders[id]; $(this).populateNewznabSection(); - $('li').remove('#' + id); + $('li').remove('#'+id); $(this).makeNewznabProviderString(); - }; + } $.fn.updateTorrentRssProvider = function (id, url) { torrentRssProviders[id][1] = url; $(this).populateTorrentRssSection(); $(this).makeTorrentRssProviderString(); - }; + } $.fn.deleteTorrentRssProvider = function (id) { $('#editATorrentRssProvider').removeOption(id); delete torrentRssProviders[id]; $(this).populateTorrentRssSection(); - $('li').remove('#' + id); + $('li').remove('#'+id); $(this).makeTorrentRssProviderString(); - }; + } - $.fn.populateNewznabSection = function () { + $.fn.populateNewznabSection = function() { var selectedProvider = $('#editANewznabProvider :selected').val(); if (selectedProvider == 'addNewznab') { - var data = ['', '', '']; + var data = ['','','']; var isDefault = 0; $('#newznab_add_div').show(); $('#newznab_update_div').hide(); @@ -134,9 +134,9 @@ $(document).ready(function(){ } } - }; + } - $.fn.makeNewznabProviderString = function () { + $.fn.makeNewznabProviderString = function() { var provStrings = new Array(); @@ -146,14 +146,14 @@ $(document).ready(function(){ $('#newznab_string').val(provStrings.join('!!!')) - }; + } - $.fn.populateTorrentRssSection = function () { + $.fn.populateTorrentRssSection = function() { var selectedProvider = $('#editATorrentRssProvider :selected').val(); if (selectedProvider == 'addTorrentRss') { - var data = ['', '', '', '']; + var data = ['','','','']; $('#torrentrss_add_div').show(); $('#torrentrss_update_div').hide(); } else { @@ -180,9 +180,9 @@ $(document).ready(function(){ $('#torrentrss_delete').removeAttr("disabled"); } - }; + } - $.fn.makeTorrentRssProviderString = function () { + $.fn.makeTorrentRssProviderString = function() { var provStrings = new Array(); for (var id in torrentRssProviders) { @@ -191,19 +191,19 @@ $(document).ready(function(){ $('#torrentrss_string').val(provStrings.join('!!!')) - }; + } - $.fn.refreshProviderList = function () { + $.fn.refreshProviderList = function() { var idArr = $("#provider_order_list").sortable('toArray'); var finalArr = new Array(); - $.each(idArr, function (key, val) { - var checked = +$('#enable_' + val).prop('checked') ? '1' : '0'; + $.each(idArr, function(key, val) { + var checked = + $('#enable_'+val).prop('checked') ? '1' : '0'; finalArr.push(val + ':' + checked); }); - $("#provider_order").val(finalArr.join(' ')); - }; + $("#provider_order").val(finalArr.join(' ')); + } $.fn.hideConfigTab = function () { @@ -224,43 +224,43 @@ $(document).ready(function(){ }); }; - $.fn.addTip = function () { + $.fn.addTip = function() { var config_id = $(this).find("input").attr('id').replace("enable_", "") + "Div"; - var config_form = '
    ' + $("div[id*=" + config_id + "]").html() + '
    ' - var provider_name = $.trim($(this).text()).replace('*', '') - - if ($("div[id*=" + config_id + "]").length == 0) { - return false + var config_form = '
    ' + $("div[id*="+config_id+"]").html() + '
    ' + var provider_name = $.trim($(this).text()).replace('*','') + + if ($("div[id*="+config_id+"]").length == 0) { + return false } - + $(this).qtip({ - + overwrite: true, position: { - adjust: { - x: 0, y: 0 - }, - my: 'left top', - at: 'top right' + adjust: { + x: 0, y: 0, + }, + my: 'left top', + at: 'top right', }, show: { - event: 'mouseenter', // Show it on click... - target: false, - solo: true, - delay: 90, - effect: true + event: 'mouseenter', // Show it on click... + target: false, + solo: true, + delay: 90, + effect: true, }, hide: { - fixed: true, - delay: 900 + fixed: true, + delay: 900, }, content: { - text: config_form, - title: { - text: provider_name + ' Config', - button: true - } + text: config_form, + title: { + text: provider_name + ' Config', + button: true + } }, style: { border: { @@ -272,11 +272,11 @@ $(document).ready(function(){ background: '#FFF', padding: 15, tip: true, // Give it a speech bubble tip with automatic corner detection - classes: 'qtip-dark qtip-shadow' - } + classes: 'qtip-dark qtip-shadow', + }, }); - }; + } var newznabProviders = new Array(); var torrentRssProviders = new Array(); @@ -390,7 +390,7 @@ $(document).ready(function(){ var name = $('#torrentrss_name').val(); var url = $('#torrentrss_url').val(); - var params = { name: name, url: url}; + var params = { name: name, url: url} // send to the form with ajax, get a return value $.getJSON(sbRoot + '/config/providers/canAddTorrentRssProvider', params, @@ -447,16 +447,16 @@ $(document).ready(function(){ } }); - $.fn.makeTorrentOptionString = function (provider_id) { + $.fn.makeTorrentOptionString = function(provider_id) { - var seed_ratio = $('.providerDiv_tip #' + provider_id + '_seed_ratio').prop('value'); - var seed_time = $('.providerDiv_tip #' + provider_id + '_seed_time').prop('value'); - var process_met = $('.providerDiv_tip #' + provider_id + '_process_method').prop('value'); - var option_string = $('.providerDiv_tip #' + provider_id + '_option_string'); + var seed_ratio = $('.providerDiv_tip #'+provider_id+'_seed_ratio').prop('value'); + var seed_time = $('.providerDiv_tip #'+provider_id+'_seed_time').prop('value'); + var process_met = $('.providerDiv_tip #'+provider_id+'_process_method').prop('value'); + var option_string = $('.providerDiv_tip #'+provider_id+'_option_string'); option_string.val([seed_ratio, seed_time, process_met].join('|')) - }; + } $(this).on('change', '.seed_option', function(){ diff --git a/gui/slick/js/configSearch.js b/gui/slick/js/configSearch.js index 57f78544..1bea93eb 100644 --- a/gui/slick/js/configSearch.js +++ b/gui/slick/js/configSearch.js @@ -8,8 +8,8 @@ $(document).ready(function(){ $('#no-torrents').hide(); } - $.fn.nzb_method_handler = function () { - + $.fn.nzb_method_handler = function() { + var selectedProvider = $('#nzb_method :selected').val(); if (selectedProvider == "blackhole") { @@ -32,28 +32,28 @@ $(document).ready(function(){ $('#nzbget_settings').hide(); } - }; - - $.fn.torrent_method_handler = function () { + } + $.fn.torrent_method_handler = function() { + var selectedProvider = $('#torrent_method :selected').val(); - + if (selectedProvider == "blackhole") { $('#t_blackhole_settings').show(); $('#torrent_settings').hide(); } else if (selectedProvider == "utorrent") { $('#t_blackhole_settings').hide(); $('#torrent_settings').show(); - $('#Torrent_username').show(); + $('#Torrent_username').show() $('#Torrent_Path').hide(); $('#Torrent_Ratio').hide(); $('#Torrent_High_Bandwidth').hide(); - $('#Torrent_Label').show(); + $('#Torrent_Label').show() $('#host_desc').text('uTorrent Host'); $('#username_desc').text('uTorrent Username'); $('#password_desc').text('uTorrent Password'); $('#label_desc').text('uTorrent Label'); - } else if (selectedProvider == "transmission") { + } else if (selectedProvider == "transmission"){ $('#t_blackhole_settings').hide(); $('#torrent_settings').show(); $('#Torrent_username').show(); @@ -65,10 +65,10 @@ $(document).ready(function(){ $('#username_desc').text('Transmission Username'); $('#password_desc').text('Transmission Password'); $('#directory_desc').text('Transmission Directory'); - } else if (selectedProvider == "deluge") { + } else if (selectedProvider == "deluge"){ $('#t_blackhole_settings').hide(); $('#torrent_settings').show(); - $('#Torrent_Label').show(); + $('#Torrent_Label').show(); $('#Torrent_username').hide(); $('#Torrent_Path').show(); $('#Torrent_Ratio').show(); @@ -78,10 +78,10 @@ $(document).ready(function(){ $('#password_desc').text('Deluge Password'); $('#label_desc').text('Deluge Label'); $('#directory_desc').text('Deluge Directory'); - } else if (selectedProvider == "download_station") { + } else if (selectedProvider == "download_station"){ $('#t_blackhole_settings').hide(); $('#torrent_settings').show(); - $('#Torrent_Label').hide(); + $('#Torrent_Label').hide(); $('#Torrent_username').show(); $('#Torrent_Paused').hide(); $('#Torrent_Path').hide(); @@ -92,10 +92,10 @@ $(document).ready(function(){ $('#password_desc').text('Synology Password'); $('#label_desc').text('Synology Label'); $('#directory_desc').text('Synology Directory'); - } else if (selectedProvider == "rtorrent") { + } else if (selectedProvider == "rtorrent"){ $('#t_blackhole_settings').hide(); $('#torrent_settings').show(); - $('#Torrent_Label').show(); + $('#Torrent_Label').show(); $('#Torrent_username').show(); $('#Torrent_Paused').hide(); $('#Torrent_Path').show(); @@ -107,7 +107,7 @@ $(document).ready(function(){ $('#label_desc').text('rTorrent Label'); $('#directory_desc').text('rTorrent Directory'); } - }; + } $('#nzb_method').change($(this).nzb_method_handler); diff --git a/gui/slick/js/configSubtitles.js b/gui/slick/js/configSubtitles.js index 4b1db67f..57100e34 100644 --- a/gui/slick/js/configSubtitles.js +++ b/gui/slick/js/configSubtitles.js @@ -1,48 +1,48 @@ $(document).ready(function(){ - $.fn.showHideServices = function () { - $('.serviceDiv').each(function () { + $.fn.showHideServices = function() { + $('.serviceDiv').each(function(){ var serviceName = $(this).attr('id'); var selectedService = $('#editAService :selected').val(); - if (selectedService + 'Div' == serviceName) + if (selectedService+'Div' == serviceName) $(this).show(); else $(this).hide(); }); - }; + } $.fn.addService = function (id, name, url, key, isDefault, showService) { if (url.match('/$') == null) - url = url + '/'; + url = url + '/' var newData = [isDefault, [name, url, key]]; - if ($('#service_order_list > #' + id).length == 0 && showService != false) { - var toAdd = '
  • ' + name + ' ' + name + '
  • '; + if ($('#service_order_list > #'+id).length == 0 && showService != false) { + var toAdd = '
  • '+name+' '+name+'
  • ' $('#service_order_list').append(toAdd); $('#service_order_list').sortable("refresh"); } - }; + } $.fn.deleteService = function (id) { - $('#service_order_list > #' + id).remove(); - }; + $('#service_order_list > #'+id).remove(); + } - $.fn.refreshServiceList = function () { - var idArr = $("#service_order_list").sortable('toArray'); - var finalArr = new Array(); - $.each(idArr, function (key, val) { - var checked = +$('#enable_' + val).prop('checked') ? '1' : '0'; - finalArr.push(val + ':' + checked); - }); + $.fn.refreshServiceList = function() { + var idArr = $("#service_order_list").sortable('toArray'); + var finalArr = new Array(); + $.each(idArr, function(key, val) { + var checked = + $('#enable_'+val).prop('checked') ? '1' : '0'; + finalArr.push(val + ':' + checked); + }); - $("#service_order").val(finalArr.join(' ')); - }; + $("#service_order").val(finalArr.join(' ')); + } $('#editAService').change(function(){ $(this).showHideServices(); diff --git a/gui/slick/js/displayShow.js b/gui/slick/js/displayShow.js index 536a4392..2647620d 100644 --- a/gui/slick/js/displayShow.js +++ b/gui/slick/js/displayShow.js @@ -25,8 +25,8 @@ $(document).ready(function(){ }); $('#changeStatus').click(function(){ - var sbRoot = $('#sbRoot').val(); - var epArr = new Array(); + var sbRoot = $('#sbRoot').val() + var epArr = new Array() $('.epCheck').each(function() { @@ -37,9 +37,9 @@ $(document).ready(function(){ }); if (epArr.length == 0) - return false; + return false - url = sbRoot + '/home/setStatus?show=' + $('#showID').attr('value') + '&eps=' + epArr.join('|') + '&status=' + $('#statusSelect').attr('value'); + url = sbRoot+'/home/setStatus?show='+$('#showID').attr('value')+'&eps='+epArr.join('|')+'&status='+$('#statusSelect').attr('value') window.location.href = url }); @@ -49,7 +49,7 @@ $(document).ready(function(){ var seasNo = $(seasCheck).attr('id'); $('.epCheck:visible').each(function(){ - var epParts = $(this).attr('id').split('x'); + var epParts = $(this).attr('id').split('x') if (epParts[0] == seasNo) { this.checked = seasCheck.checked @@ -103,19 +103,19 @@ $(document).ready(function(){ // handle the show selection dropbox $('#pickShow').change(function(){ - var sbRoot = $('#sbRoot').val(); - var val = $(this).attr('value'); + var sbRoot = $('#sbRoot').val() + var val = $(this).attr('value') if (val == 0) - return; - url = sbRoot + '/home/displayShow?show=' + val; + return + url = sbRoot+'/home/displayShow?show='+val window.location.href = url }); // show/hide different types of rows when the checkboxes are changed $("#checkboxControls input").change(function(e){ - var whichClass = $(this).attr('id'); - $(this).showHideRows(whichClass); - return; + var whichClass = $(this).attr('id') + $(this).showHideRows(whichClass) + return $('tr.'+whichClass).each(function(i){ $(this).toggle(); }); @@ -133,10 +133,10 @@ $(document).ready(function(){ }); }); - $.fn.showHideRows = function (whichClass) { + $.fn.showHideRows = function(whichClass){ - var status = $('#checkboxControls > input, #' + whichClass).prop('checked'); - $("tr." + whichClass).each(function (e) { + var status = $('#checkboxControls > input, #'+whichClass).prop('checked') + $("tr."+whichClass).each(function(e){ if (status) { $(this).show(); } else { @@ -145,22 +145,22 @@ $(document).ready(function(){ }); // hide season headers with no episodes under them - $('tr.seasonheader').each(function () { - var numRows = 0; - var seasonNo = $(this).attr('id'); - $('tr.' + seasonNo + ' :visible').each(function () { + $('tr.seasonheader').each(function(){ + var numRows = 0 + var seasonNo = $(this).attr('id') + $('tr.'+seasonNo+' :visible').each(function(){ numRows++ - }); + }) if (numRows == 0) { - $(this).hide(); - $('#' + seasonNo + '-cols').hide() + $(this).hide() + $('#'+seasonNo+'-cols').hide() } else { - $(this).show(); - $('#' + seasonNo + '-cols').show() + $(this).show() + $('#'+seasonNo+'-cols').show() } - }); - }; + }); + } function setEpisodeSceneNumbering(forSeason, forEpisode, sceneSeason, sceneEpisode) { var sbRoot = $('#sbRoot').val(); diff --git a/gui/slick/js/failedDownloads.js b/gui/slick/js/failedDownloads.js index 3845ea4f..1b081ad9 100644 --- a/gui/slick/js/failedDownloads.js +++ b/gui/slick/js/failedDownloads.js @@ -1,8 +1,7 @@ $(document).ready(function(){ $('#submitMassRemove').click(function(){ - var removeArr = new Array(); - ; + var removeArr = new Array() $('.removeCheck').each(function() { if (this.checked == true) { @@ -13,7 +12,7 @@ $(document).ready(function(){ if (removeArr.length == 0) return false - url = sbRoot + '/manage/failedDownloads?toRemove=' + removeArr.join('|'); + url = sbRoot + '/manage/failedDownloads?toRemove='+removeArr.join('|') window.location.href = url diff --git a/gui/slick/js/formwizard.js b/gui/slick/js/formwizard.js index a7625a31..19534290 100644 --- a/gui/slick/js/formwizard.js +++ b/gui/slick/js/formwizard.js @@ -10,211 +10,203 @@ function formtowizard(options){ - this.setting = jQuery.extend({persistsection: false, revealfx: ['slide', 500], oninit: function () { - }, onpagechangestart: function () { - }}, options); - this.currentsection = -1; + this.setting=jQuery.extend({persistsection:false, revealfx:['slide', 500], oninit:function(){}, onpagechangestart:function(){}}, options) + this.currentsection=-1 this.init(this.setting) } -formtowizard.prototype = { +formtowizard.prototype={ - createfieldsets: function ($theform, arr) { //reserved function for future version (dynamically wraps form elements with a fieldset element) - $theform.find('fieldset.sectionwrap').removeClass('sectionwrap'); //make sure no fieldsets carry 'sectionwrap' before proceeding - var $startelement = $theform.find(':first-child'); //reference first element inside form - for (var i = 0; i < arr.length; i++) { //loop thru "break" elements - var $fieldsetelements = $startelement.nextUntil('#' + arr[i].breakafter + ', *[name=' + arr[i].breakafter + ']').andSelf(); //reference all elements from start element to break element (nextUntil() is jQuery 1.4 function) - $fieldsetelements.add($fieldsetelements.next()).wrapAll('
    '); //wrap these elements with fieldset element - $startelement = $theform.find('fieldset.sectionwrap').eq(i).prepend('' + arr[i].legend + '').next(); //increment startelement to begin at the end of the just inserted fieldset element - } - }, + createfieldsets:function($theform, arr){ //reserved function for future version (dynamically wraps form elements with a fieldset element) + $theform.find('fieldset.sectionwrap').removeClass('sectionwrap') //make sure no fieldsets carry 'sectionwrap' before proceeding + var $startelement=$theform.find(':first-child') //reference first element inside form + for (var i=0; i') //wrap these elements with fieldset element + $startelement=$theform.find('fieldset.sectionwrap').eq(i).prepend(''+arr[i].legend+'').next() //increment startelement to begin at the end of the just inserted fieldset element + } + }, - loadsection: function (rawi, bypasshooks) { - var thiswizard = this; - //doload Boolean checks to see whether to load next section (true if bypasshooks param is true or onpagechangestart() event handler doesn't return false) - var doload = bypasshooks || this.setting.onpagechangestart(jQuery, this.currentsection, this.sections.$sections.eq(this.currentsection)); - doload = (doload === false) ? false : true; //unless doload is explicitly false, set to true - if (!bypasshooks && this.setting.validate) { - var outcome = this.validate(this.currentsection); - if (outcome === false) - doload = false - } - var i = (rawi == "prev") ? this.currentsection - 1 : (rawi == "next") ? this.currentsection + 1 : parseInt(rawi); //get index of next section to show - i = (i < 0) ? this.sections.count - 1 : (i > this.sections.count - 1) ? 0 : i; //make sure i doesn't exceed min/max limit - if (i < this.sections.count && doload) { //if next section to show isn't the same as the current section shown - this.$thesteps.eq(this.currentsection).addClass('disabledstep').end().eq(i).removeClass('disabledstep'); //dull current "step" text then highlight next "step" text - if (this.setting.revealfx[0] == "slide") { - this.sections.$sections.css("visibility", "visible"); - this.sections.$outerwrapper.stop().animate({height: this.sections.$sections.eq(i).outerHeight()}, this.setting.revealfx[1]); //animate fieldset wrapper's height to accomodate next section's height - this.sections.$innerwrapper.stop().animate({left: -i * this.maxfieldsetwidth}, this.setting.revealfx[1], function () { //slide next section into view - thiswizard.sections.$sections.each(function (thissec) { - if (thissec != i) //hide fieldset sections currently not in veiw, so tabbing doesn't go to elements within them (and mess up layout) - thiswizard.sections.$sections.eq(thissec).css("visibility", "hidden") - }) - }) - } - else if (this.setting.revealfx[0] == "fade") { //if fx is "fade" - this.sections.$sections.eq(this.currentsection).hide().end().eq(i).fadeIn(this.setting.revealfx[1], function () { - if (document.all && this.style && this.style.removeAttribute) - this.style.removeAttribute('filter'); //fix IE clearType problem - }) - } - else { - this.sections.$sections.eq(this.currentsection).hide().end().eq(i).show() - } - this.paginatediv.$status.text("Page " + (i + 1) + " of " + this.sections.count); //update current page status text - this.paginatediv.$navlinks.css('visibility', 'visible'); - if (i == 0) //hide "prev" link - this.paginatediv.$navlinks.eq(0).css('visibility', 'hidden'); - else if (i == this.sections.count - 1) //hide "next" link - this.paginatediv.$navlinks.eq(1).css('visibility', 'hidden'); - if (this.setting.persistsection) //enable persistence? - formtowizard.routines.setCookie(this.setting.formid + "_persist", i); - this.currentsection = i; - if (i === 0) { - setTimeout(function () { - $('#nameToSearch').focus(); - }, 250); - } - } - }, + loadsection:function(rawi, bypasshooks){ + var thiswizard=this + //doload Boolean checks to see whether to load next section (true if bypasshooks param is true or onpagechangestart() event handler doesn't return false) + var doload=bypasshooks || this.setting.onpagechangestart(jQuery, this.currentsection, this.sections.$sections.eq(this.currentsection)) + doload=(doload===false)? false : true //unless doload is explicitly false, set to true + if (!bypasshooks && this.setting.validate){ + var outcome=this.validate(this.currentsection) + if (outcome===false) + doload=false + } + var i=(rawi=="prev")? this.currentsection-1 : (rawi=="next")? this.currentsection+1 : parseInt(rawi) //get index of next section to show + i=(i<0)? this.sections.count-1 : (i>this.sections.count-1)? 0 : i //make sure i doesn't exceed min/max limit + if (i 0) { //radio and checkbox elements - var onechecked = false; - for (var r = 0; r < elements[i].length; r++) { - if (elements[i][r].checked == true) { - onechecked = true; - break - } - } - if (!onechecked) { - invalidate(elements[i][0]) - } - } - } - if (!validated) - alert(invalidtext.join('\n')); - return validated - }, + validate:function(section){ + var elements=this.sections.$sections.eq(section).data('elements') //reference elements within this section that should be validated + var validated=true, invalidtext=["Please fill out the following fields:\n"] + function invalidate(el){ + validated=false + invalidtext.push("- "+ (el.id || el.name)) + } + for (var i=0; i0){ //radio and checkbox elements + var onechecked=false + for (var r=0; r 0) - thiswizard.createfieldsets($theform, setting.manualfieldsets); - var $stepsguide = $('
    '); //create Steps Container to house the "steps" text - var $sections = $theform.find('fieldset.sectionwrap').hide(); //find all fieldset elements within form and hide them initially - if (setting.revealfx[0] == "slide") { //create outer DIV that will house all the fieldset.sectionwrap elements - $sectionswrapper = $('
    ').insertBefore($sections.eq(0)); //add DIV above the first fieldset.sectionwrap element - $sectionswrapper_inner = $('
    '); //create inner DIV of $sectionswrapper that will scroll to reveal a fieldset element - } - var maxfieldsetwidth = $sections.eq(0).outerWidth(); //variable to get width of widest fieldset.sectionwrap - $sections.slice(1).each(function (i) { //loop through $sections (starting from 2nd one) - maxfieldsetwidth = Math.max($(this).outerWidth(), maxfieldsetwidth) - }); - maxfieldsetwidth += 2; //add 2px to final width to reveal fieldset border (if not removed via CSS) - thiswizard.maxfieldsetwidth = maxfieldsetwidth; - $sections.each(function (i) { //loop through $sections again - var $section = $(this); - if (setting.revealfx[0] == "slide") { - $section.data('page', i).css({position: 'absolute', top: 0, left: maxfieldsetwidth * i}).appendTo($sectionswrapper_inner); //set fieldset position to "absolute" and move it to inside sectionswrapper_inner DIV - } - $section.data('elements', []); //empty array to contain elements within this section that should be validated for data (applicable only if validate option is defined) - //create each "step" DIV and add it to main Steps Container: - var $thestep = $('
    ').data('section', i).html('Step ' + (i + 1) + '
    ' + $section.find('legend:eq(0)').text() + '

    ').appendTo($stepsguide); - $thestep.click(function () { //assign behavior to each step div - thiswizard.loadsection($(this).data('section')) - }) - }); - if (setting.revealfx[0] == "slide") { - $sectionswrapper.width(maxfieldsetwidth); //set fieldset wrapper to width of widest fieldset - $sectionswrapper.append($sectionswrapper_inner); //add $sectionswrapper_inner as a child of $sectionswrapper - } - $theform.prepend($stepsguide); //add $thesteps div to the beginning of the form - //$stepsguide.insertBefore($sectionswrapper) //add Steps Container before sectionswrapper container - var $thesteps = $stepsguide.find('div.step'); - //create pagination DIV and add it to end of form: - var $paginatediv = $('
    Prev Step 1 of Next
    '); - $theform.append($paginatediv); - thiswizard.$theform = $theform; - if (setting.revealfx[0] == "slide") { - thiswizard.sections = {$outerwrapper: $sectionswrapper, $innerwrapper: $sectionswrapper_inner, $sections: $sections, count: $sections.length}; //remember various parts of section container - thiswizard.sections.$sections.show() - } - else { - thiswizard.sections = {$sections: $sections, count: $sections.length}; //remember various parts of section container - } - thiswizard.$thesteps = $thesteps; //remember this ref - thiswizard.paginatediv = {$main: $paginatediv, $navlinks: $paginatediv.find('span.prev, span.next'), $status: $paginatediv.find('span.status')}; //remember various parts of pagination DIV - thiswizard.paginatediv.$main.click(function (e) { //assign behavior to pagination buttons - if (/(prev)|(next)/.test(e.target.className)) - thiswizard.loadsection(e.target.className) - }); - var i = (setting.persistsection) ? formtowizard.routines.getCookie(setting.formid + "_persist") : 0; - thiswizard.loadsection(i || 0, true); //show the first section - thiswizard.setting.oninit($, i, $sections.eq(i)); //call oninit event handler - if (setting.validate) { //if validate array defined - thiswizard.addvalidatefields(); //seek out and cache form elements that should be validated - thiswizard.$theform.submit(function () { - var returnval = true; - for (var i = 0; i < thiswizard.sections.count; i++) { - if (!thiswizard.validate(i)) { - thiswizard.loadsection(i, true); - returnval = false; - break - } - } - return returnval; //allow or disallow form submission - }) - } - }) - } -}; + init:function(setting){ + var thiswizard=this + jQuery(function($){ //on document.ready + var $theform=$('#'+setting.formid) + if ($theform.length==0) //if form with specified ID doesn't exist, try name attribute instead + $theform=$('form[name='+setting.formid+']') + if (setting.manualfieldsets && setting.manualfieldsets.length>0) + thiswizard.createfieldsets($theform, setting.manualfieldsets) + var $stepsguide=$('
    ') //create Steps Container to house the "steps" text + var $sections=$theform.find('fieldset.sectionwrap').hide() //find all fieldset elements within form and hide them initially + if (setting.revealfx[0]=="slide"){ //create outer DIV that will house all the fieldset.sectionwrap elements + $sectionswrapper=$('
    ').insertBefore($sections.eq(0)) //add DIV above the first fieldset.sectionwrap element + $sectionswrapper_inner=$('
    ') //create inner DIV of $sectionswrapper that will scroll to reveal a fieldset element + } + var maxfieldsetwidth=$sections.eq(0).outerWidth() //variable to get width of widest fieldset.sectionwrap + $sections.slice(1).each(function(i){ //loop through $sections (starting from 2nd one) + maxfieldsetwidth=Math.max($(this).outerWidth(), maxfieldsetwidth) + }) + maxfieldsetwidth+=2 //add 2px to final width to reveal fieldset border (if not removed via CSS) + thiswizard.maxfieldsetwidth=maxfieldsetwidth + $sections.each(function(i){ //loop through $sections again + var $section=$(this) + if (setting.revealfx[0]=="slide"){ + $section.data('page', i).css({position:'absolute', top:0, left:maxfieldsetwidth*i}).appendTo($sectionswrapper_inner) //set fieldset position to "absolute" and move it to inside sectionswrapper_inner DIV + } + $section.data('elements', []) //empty array to contain elements within this section that should be validated for data (applicable only if validate option is defined) + //create each "step" DIV and add it to main Steps Container: + var $thestep=$('
    ').data('section', i).html('Step '+(i+1)+'
    '+$section.find('legend:eq(0)').text()+'

    ').appendTo($stepsguide) + $thestep.click(function(){ //assign behavior to each step div + thiswizard.loadsection($(this).data('section')) + }) + }) + if (setting.revealfx[0]=="slide"){ + $sectionswrapper.width(maxfieldsetwidth) //set fieldset wrapper to width of widest fieldset + $sectionswrapper.append($sectionswrapper_inner) //add $sectionswrapper_inner as a child of $sectionswrapper + } + $theform.prepend($stepsguide) //add $thesteps div to the beginning of the form + //$stepsguide.insertBefore($sectionswrapper) //add Steps Container before sectionswrapper container + var $thesteps=$stepsguide.find('div.step') + //create pagination DIV and add it to end of form: + var $paginatediv=$('
    Prev Step 1 of Next
    ') + $theform.append($paginatediv) + thiswizard.$theform=$theform + if (setting.revealfx[0]=="slide"){ + thiswizard.sections={$outerwrapper:$sectionswrapper, $innerwrapper:$sectionswrapper_inner, $sections:$sections, count:$sections.length} //remember various parts of section container + thiswizard.sections.$sections.show() + } + else{ + thiswizard.sections={$sections:$sections, count:$sections.length} //remember various parts of section container + } + thiswizard.$thesteps=$thesteps //remember this ref + thiswizard.paginatediv={$main:$paginatediv, $navlinks:$paginatediv.find('span.prev, span.next'), $status:$paginatediv.find('span.status')} //remember various parts of pagination DIV + thiswizard.paginatediv.$main.click(function(e){ //assign behavior to pagination buttons + if (/(prev)|(next)/.test(e.target.className)) + thiswizard.loadsection(e.target.className) + }) + var i=(setting.persistsection)? formtowizard.routines.getCookie(setting.formid+"_persist") : 0 + thiswizard.loadsection(i||0, true) //show the first section + thiswizard.setting.oninit($, i, $sections.eq(i)) //call oninit event handler + if (setting.validate){ //if validate array defined + thiswizard.addvalidatefields() //seek out and cache form elements that should be validated + thiswizard.$theform.submit(function(){ + var returnval=true + for (var i=0; i 0) ? (dest == this.topkeyword ? 0 : $('#' + dest)) : (dest) ? $(dest) : []; //get element based on id, topkeyword, or dom ref - if ($dest === 0 || $dest.length == 1 && (!options.autorun || options.autorun && Math.abs($dest.offset().top + (options.yoffset || this.setting.yoffset) - $(window).scrollTop()) > 5)) { - this.$body.animate({scrollTop: ($dest === 0) ? 0 : $dest.offset().top + (options.yoffset || this.setting.yoffset)}, (options.duration || this.setting.duration), function () { + scrollTo:function(dest, options, hash){ + var $=jQuery, options=options || {} + var $dest=(typeof dest=="string" && dest.length>0)? (dest==this.topkeyword? 0 : $('#'+dest)) : (dest)? $(dest) : [] //get element based on id, topkeyword, or dom ref + if ($dest===0 || $dest.length==1 && (!options.autorun || options.autorun && Math.abs($dest.offset().top+(options.yoffset||this.setting.yoffset)-$(window).scrollTop())>5)){ + this.$body.animate({scrollTop: ($dest===0)? 0 : $dest.offset().top+(options.yoffset||this.setting.yoffset)}, (options.duration||this.setting.duration), function(){ //** if ($dest!==0 && hash) //** location.hash=hash - }) - } - }, + }) + } + }, - urlparamselect: function () { - var param = window.location.search.match(/scrollto=[\w\-_,]+/i); //search for scrollto=divid - return (param) ? param[0].split('=')[1] : null - }, + urlparamselect:function(){ + var param=window.location.search.match(/scrollto=[\w\-_,]+/i) //search for scrollto=divid + return (param)? param[0].split('=')[1] : null + }, + + init:function(){ + jQuery(document).ready(function($){ + var mainobj=bookmarkscroll + mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body') + var urlselectid=mainobj.urlparamselect() //get div of page.htm?scrollto=divid + if (urlselectid) //if id defined + setTimeout(function(){mainobj.scrollTo(document.getElementById(urlselectid) || $('a[name='+urlselectid+']:eq(0)').get(0), {autorun:true})}, 100) + $('a[href^="#"]').each(function(){ //loop through links with "#" prefix + var hashvalue=this.getAttribute('href').match(/#\w+$/i) //filter links at least 1 character following "#" prefix + hashvalue=(hashvalue)? hashvalue[0].substring(1) : null //strip "#" from hashvalue + if (this.hash.length>1){ //if hash value is more than just "#" + var $bookmark=$('a[name='+this.hash.substr(1)+']:eq(0)') + if ($bookmark.length==1 || this.hash==mainobj.topkeyword){ //if HTML anchor with given ID exists or href==topkeyword + if ($bookmark.length==1 && !document.all) //non IE, or IE7+ + $bookmark.html('.').css({position:'absolute', fontSize:1, visibility:'hidden'}) + $(this).click(function(e){ + mainobj.scrollTo((this.hash==mainobj.topkeyword)? mainobj.topkeyword : $bookmark.get(0), {}, this.hash) + e.preventDefault() + }) + } + } + }) + }) + } +} - init: function () { - jQuery(document).ready(function ($) { - var mainobj = bookmarkscroll; - mainobj.$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); - var urlselectid = mainobj.urlparamselect(); //get div of page.htm?scrollto=divid - if (urlselectid) //if id defined - setTimeout(function () { - mainobj.scrollTo(document.getElementById(urlselectid) || $('a[name=' + urlselectid + ']:eq(0)').get(0), {autorun: true}) - }, 100); - $('a[href^="#"]').each(function () { //loop through links with "#" prefix - var hashvalue = this.getAttribute('href').match(/#\w+$/i); //filter links at least 1 character following "#" prefix - hashvalue = (hashvalue) ? hashvalue[0].substring(1) : null; //strip "#" from hashvalue - if (this.hash.length > 1) { //if hash value is more than just "#" - var $bookmark = $('a[name=' + this.hash.substr(1) + ']:eq(0)'); - if ($bookmark.length == 1 || this.hash == mainobj.topkeyword) { //if HTML anchor with given ID exists or href==topkeyword - if ($bookmark.length == 1 && !document.all) //non IE, or IE7+ - $bookmark.html('.').css({position: 'absolute', fontSize: 1, visibility: 'hidden'}); - $(this).click(function (e) { - mainobj.scrollTo((this.hash == mainobj.topkeyword) ? mainobj.topkeyword : $bookmark.get(0), {}, this.hash); - e.preventDefault() - }) - } - } - }) - }) - } -}; - -bookmarkscroll.init(); \ No newline at end of file +bookmarkscroll.init() \ No newline at end of file diff --git a/gui/slick/js/lib/jquery.scrolltopcontrol-1.1.js b/gui/slick/js/lib/jquery.scrolltopcontrol-1.1.js index c599a018..4a6b4d10 100644 --- a/gui/slick/js/lib/jquery.scrolltopcontrol-1.1.js +++ b/gui/slick/js/lib/jquery.scrolltopcontrol-1.1.js @@ -5,75 +5,72 @@ //** 2) Fixes scroll animation not working in Opera. -var scrolltotop = { - //startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control - //scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top). - setting: {startline: 100, scrollto: 0, scrollduration: 1000, fadeduration: [500, 100]}, - controlHTML: top_image_html,//set in inc_top.tmpl so it can be $sbRooted - controlattrs: {offsetx: 10, offsety: 10}, //offset of control relative to right/ bottom of window corner - anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links +var scrolltotop={ + //startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control + //scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top). + setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]}, + controlHTML: top_image_html,//set in inc_top.tmpl so it can be $sbRooted + controlattrs: {offsetx:10, offsety:10}, //offset of control relative to right/ bottom of window corner + anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links - state: {isvisible: false, shouldvisible: false}, + state: {isvisible:false, shouldvisible:false}, - scrollup: function () { - if (!this.cssfixedsupport) //if control is positioned using JavaScript - this.$control.css({opacity: 0}); //hide control immediately after clicking it - var dest = isNaN(this.setting.scrollto) ? this.setting.scrollto : parseInt(this.setting.scrollto); - if (typeof dest == "string" && jQuery('#' + dest).length == 1) //check element set by string exists - dest = jQuery('#' + dest).offset().top; - else - dest = 0; - this.$body.animate({scrollTop: dest}, this.setting.scrollduration); - }, + scrollup:function(){ + if (!this.cssfixedsupport) //if control is positioned using JavaScript + this.$control.css({opacity:0}) //hide control immediately after clicking it + var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto) + if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists + dest=jQuery('#'+dest).offset().top + else + dest=0 + this.$body.animate({scrollTop: dest}, this.setting.scrollduration); + }, - keepfixed: function () { - var $window = jQuery(window); - var controlx = $window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx; - var controly = $window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety; - this.$control.css({left: controlx + 'px', top: controly + 'px'}) - }, + keepfixed:function(){ + var $window=jQuery(window) + var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx + var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety + this.$control.css({left:controlx+'px', top:controly+'px'}) + }, - togglecontrol: function () { - var scrolltop = jQuery(window).scrollTop(); - if (!this.cssfixedsupport) - this.keepfixed(); - this.state.shouldvisible = (scrolltop >= this.setting.startline) ? true : false; - if (this.state.shouldvisible && !this.state.isvisible) { - this.$control.stop().animate({opacity: 1}, this.setting.fadeduration[0]); - this.state.isvisible = true - } - else if (this.state.shouldvisible == false && this.state.isvisible) { - this.$control.stop().animate({opacity: 0}, this.setting.fadeduration[1]); - this.state.isvisible = false - } - }, + togglecontrol:function(){ + var scrolltop=jQuery(window).scrollTop() + if (!this.cssfixedsupport) + this.keepfixed() + this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false + if (this.state.shouldvisible && !this.state.isvisible){ + this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0]) + this.state.isvisible=true + } + else if (this.state.shouldvisible==false && this.state.isvisible){ + this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1]) + this.state.isvisible=false + } + }, + + init:function(){ + jQuery(document).ready(function($){ + var mainobj=scrolltotop + var iebrws=document.all + mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode + mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body') + mainobj.$control=$('
    '+mainobj.controlHTML+'
    ') + .css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:mainobj.controlattrs.offsety, right:mainobj.controlattrs.offsetx, opacity:0, cursor:'pointer'}) + .attr({title:'Scroll Back to Top'}) + .click(function(){mainobj.scrollup(); return false}) + .appendTo('body') + if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text + mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text + mainobj.togglecontrol() + $('a[href="' + mainobj.anchorkeyword +'"]').click(function(){ + mainobj.scrollup() + return false + }) + $(window).bind('scroll resize', function(e){ + mainobj.togglecontrol() + }) + }) + } +} - init: function () { - jQuery(document).ready(function ($) { - var mainobj = scrolltotop; - var iebrws = document.all; - mainobj.cssfixedsupport = !iebrws || iebrws && document.compatMode == "CSS1Compat" && window.XMLHttpRequest; //not IE or IE7+ browsers in standards mode - mainobj.$body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); - mainobj.$control = $('
    ' + mainobj.controlHTML + '
    ') - .css({position: mainobj.cssfixedsupport ? 'fixed' : 'absolute', bottom: mainobj.controlattrs.offsety, right: mainobj.controlattrs.offsetx, opacity: 0, cursor: 'pointer'}) - .attr({title: 'Scroll Back to Top'}) - .click(function () { - mainobj.scrollup(); - return false - }) - .appendTo('body'); - if (document.all && !window.XMLHttpRequest && mainobj.$control.text() != '') //loose check for IE6 and below, plus whether control contains any text - mainobj.$control.css({width: mainobj.$control.width()}); //IE6- seems to require an explicit width on a DIV containing text - mainobj.togglecontrol(); - $('a[href="' + mainobj.anchorkeyword + '"]').click(function () { - mainobj.scrollup(); - return false - }); - $(window).bind('scroll resize', function (e) { - mainobj.togglecontrol() - }) - }) - } -}; - -scrolltotop.init(); \ No newline at end of file +scrolltotop.init() \ No newline at end of file diff --git a/gui/slick/js/lib/jquery.tokeninput.js b/gui/slick/js/lib/jquery.tokeninput.js index b1122aad..2afcc0f2 100644 --- a/gui/slick/js/lib/jquery.tokeninput.js +++ b/gui/slick/js/lib/jquery.tokeninput.js @@ -96,29 +96,29 @@ var KEY = { // Additional public (exposed) methods var methods = { - init: function (url_or_data_or_function, options) { + init: function(url_or_data_or_function, options) { var settings = $.extend({}, DEFAULT_SETTINGS, options || {}); return this.each(function () { $(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings)); }); }, - clear: function () { + clear: function() { this.data("tokenInputObject").clear(); return this; }, - add: function (item) { + add: function(item) { this.data("tokenInputObject").add(item); return this; }, - remove: function (item) { + remove: function(item) { this.data("tokenInputObject").remove(item); return this; }, - get: function () { - return this.data("tokenInputObject").getTokens(); - } -}; + get: function() { + return this.data("tokenInputObject").getTokens(); + } +} // Expose the .tokenInput function to jQuery as a plugin $.fn.tokenInput = function (method) { @@ -384,20 +384,20 @@ $.TokenList = function (input, url_or_data, settings) { // Public functions // - this.clear = function () { - token_list.children("li").each(function () { + this.clear = function() { + token_list.children("li").each(function() { if ($(this).children("input").length === 0) { delete_token($(this)); } }); - }; + } - this.add = function (item) { + this.add = function(item) { add_token(item); - }; + } - this.remove = function (item) { - token_list.children("li").each(function () { + this.remove = function(item) { + token_list.children("li").each(function() { if ($(this).children("input").length === 0) { var currToken = $(this).data("tokeninput"); var match = true; @@ -412,11 +412,11 @@ $.TokenList = function (input, url_or_data, settings) { } } }); - }; + } - this.getTokens = function () { - return saved_tokens; - }; + this.getTokens = function() { + return saved_tokens; + } // // Private functions diff --git a/gui/slick/js/manageEpisodeStatuses.js b/gui/slick/js/manageEpisodeStatuses.js index 745033eb..7956236d 100644 --- a/gui/slick/js/manageEpisodeStatuses.js +++ b/gui/slick/js/manageEpisodeStatuses.js @@ -13,7 +13,7 @@ $(document).ready(function() { row += ' '; row += ' '+season+'x'+episode+''; row += ' '+name+''; - row += ' '; + row += ' ' return row; } diff --git a/gui/slick/js/manageSubtitleMissed.js b/gui/slick/js/manageSubtitleMissed.js index 5e54df7a..190fbd8c 100644 --- a/gui/slick/js/manageSubtitleMissed.js +++ b/gui/slick/js/manageSubtitleMissed.js @@ -12,13 +12,13 @@ $(document).ready(function() { row += ' '+season+'x'+episode+''; row += ' '+name+''; row += ' '; - subtitles = subtitles.split(','); + subtitles = subtitles.split(',') for (i in subtitles) { row += ' '+subtitles[i]+' '; } row += ' '; - row += ' '; + row += ' ' return row; } diff --git a/gui/slick/js/massUpdate.js b/gui/slick/js/massUpdate.js index fddbc73b..42469672 100644 --- a/gui/slick/js/massUpdate.js +++ b/gui/slick/js/massUpdate.js @@ -1,7 +1,7 @@ $(document).ready(function(){ $('#submitMassEdit').click(function(){ - var editArr = new Array(); + var editArr = new Array() $('.editCheck').each(function() { if (this.checked == true) { @@ -19,12 +19,12 @@ $(document).ready(function(){ $('#submitMassUpdate').click(function(){ - var updateArr = new Array(); - var refreshArr = new Array(); - var renameArr = new Array(); - var subtitleArr = new Array(); - var deleteArr = new Array(); - var metadataArr = new Array(); + var updateArr = new Array() + var refreshArr = new Array() + var renameArr = new Array() + var subtitleArr = new Array() + var deleteArr = new Array() + var metadataArr = new Array() $('.updateCheck').each(function() { if (this.checked == true) { diff --git a/gui/slick/js/rootDirs.js b/gui/slick/js/rootDirs.js index 172c0dc2..f2b461f5 100644 --- a/gui/slick/js/rootDirs.js +++ b/gui/slick/js/rootDirs.js @@ -112,10 +112,10 @@ $(document).ready(function() { console.log('setting default to '+which); if (which != undefined && !which.length) - return; + return if ($('#whichDefaultRootDir').val() == which && force != true) - return; + return // put an asterisk on the text if ($('#'+which).text().charAt(0) != '*') @@ -141,7 +141,7 @@ $(document).ready(function() { function refreshRootDirs() { if (!$("#rootDirs").length) - return; + return var do_disable = 'true'; @@ -150,7 +150,7 @@ $(document).ready(function() { // if nothing's selected then select the default if (!$("#rootDirs option:selected").length && $('#whichDefaultRootDir').val().length) - $('#' + $('#whichDefaultRootDir').val()).prop("selected", true); + $('#'+$('#whichDefaultRootDir').val()).prop("selected", true) // if something's selected then we have some behavior to figure out if ($("#rootDirs option:selected").length) { @@ -183,7 +183,7 @@ $(document).ready(function() { // set up buttons on page load syncOptionIDs(); - setDefault($('#whichDefaultRootDir').val(), true); + setDefault($('#whichDefaultRootDir').val(), true) refreshRootDirs(); }); \ No newline at end of file diff --git a/gui/slick/js/testRename.js b/gui/slick/js/testRename.js index bf34ee1e..10ba453a 100644 --- a/gui/slick/js/testRename.js +++ b/gui/slick/js/testRename.js @@ -4,7 +4,7 @@ $(document).ready(function(){ var seasNo = $(seasCheck).attr('id'); $('.epCheck:visible').each(function(){ - var epParts = $(this).attr('id').split('x'); + var epParts = $(this).attr('id').split('x') if (epParts[0] == seasNo) { this.checked = seasCheck.checked @@ -13,7 +13,7 @@ $(document).ready(function(){ }); $('input[type=submit]').click(function(){ - var epArr = new Array(); + var epArr = new Array() $('.epCheck').each(function() { if (this.checked == true) { diff --git a/lib/bencode/PKG-INFO b/lib/bencode/PKG-INFO deleted file mode 100644 index 892c1634..00000000 --- a/lib/bencode/PKG-INFO +++ /dev/null @@ -1,16 +0,0 @@ -Metadata-Version: 1.0 -Name: BitTorrent-bencode -Version: 5.0.8.1 -Summary: The BitTorrent bencode module as leight-weight, standalone package. -Home-page: http://bittorrent.com/ -Author: Bram Cohen -Author-email: bugs@bittorrent.com -License: BitTorrent Open Source License -Description: This package simply re-packages the existing bencoding and bdecoding implemention from the 'official' BitTorrent client as a separate, leight-weight package for re-using them without having the entire BitTorrent software as a dependency. - - It currently uses the implementation from BitTorrent Version 5.0.8, the file `bencode.py` is a verbatim, unmodified copy from that distribution. - - It also contains some tests and a benchmark. - -Keywords: bittorrent bencode bdecode -Platform: UNKNOWN diff --git a/lib/bencode/README.txt b/lib/bencode/README.txt deleted file mode 100644 index 8e6608d4..00000000 --- a/lib/bencode/README.txt +++ /dev/null @@ -1,21 +0,0 @@ -This package simply re-packages the existing bencoding and bdecoding implemention from the 'official' BitTorrent client as a separate, leight-weight package for re-using them without having the entire BitTorrent software as a dependency. - -It currently uses the implementation from BitTorrent Version 5.0.8, the file `bencode.py` is a verbatim, unmodified copy from that distribution. - -It also contains some tests and a benchmark. - -Tom Lazar, tom@tomster.org - -HISTORY -======= - -5.0.8.1 - 2010-12-19 --------------------- - - - re-release containing packaging fixes. should now install on current - versions of setuptools and distribute (also tested with Python 2.6 now) - -5.0.8 - 2007-07-29 ------------------- - - - original release \ No newline at end of file diff --git a/lib/bencode/__init__.py b/lib/bencode/__init__.py index 231687ad..4424fc7e 100644 --- a/lib/bencode/__init__.py +++ b/lib/bencode/__init__.py @@ -1 +1 @@ -# not empty \ No newline at end of file +from bencode import * \ No newline at end of file diff --git a/lib/bencode/bencode.py b/lib/bencode/bencode.py index 7a2af172..ad36ef65 100644 --- a/lib/bencode/bencode.py +++ b/lib/bencode/bencode.py @@ -66,8 +66,8 @@ def bdecode(x): r, l = decode_func[x[0]](x, 0) except (IndexError, KeyError, ValueError): raise BTFailure("not a valid bencoded string") - if l != len(x): - raise BTFailure("invalid bencoded value (data after valid prefix)") +# if l != len(x): +# raise BTFailure("invalid bencoded value (data after valid prefix)") return r from types import StringType, IntType, LongType, DictType, ListType, TupleType diff --git a/lib/bencode/setup.cfg b/lib/bencode/setup.cfg deleted file mode 100644 index 861a9f55..00000000 --- a/lib/bencode/setup.cfg +++ /dev/null @@ -1,5 +0,0 @@ -[egg_info] -tag_build = -tag_date = 0 -tag_svn_revision = 0 - diff --git a/lib/bencode/setup.py b/lib/bencode/setup.py deleted file mode 100644 index f1332d46..00000000 --- a/lib/bencode/setup.py +++ /dev/null @@ -1,22 +0,0 @@ -from setuptools import setup - -setup( - name = "BitTorrent-bencode", - version = "5.0.8.1", - py_modules = ['bencode', 'BTL'], - # metadata for upload to PyPI - author = "Bram Cohen", - author_email = "bugs@bittorrent.com", - description = "The BitTorrent bencode module as leight-weight, standalone package.", - license = "BitTorrent Open Source License", - keywords = "bittorrent bencode bdecode", - url = "http://bittorrent.com/", - zip_safe = True, - test_suite = "test.testbencode", - long_description = """This package simply re-packages the existing bencoding and bdecoding implemention from the 'official' BitTorrent client as a separate, leight-weight package for re-using them without having the entire BitTorrent software as a dependency. - -It currently uses the implementation from BitTorrent Version 5.0.8, the file `bencode.py` is a verbatim, unmodified copy from that distribution. - -It also contains some tests and a benchmark. -""", -) \ No newline at end of file diff --git a/sickbeard/__init__.py b/sickbeard/__init__.py index ac1a7bb5..fc35b092 100644 --- a/sickbeard/__init__.py +++ b/sickbeard/__init__.py @@ -1630,13 +1630,13 @@ def launchBrowser(startPort=None): def getEpList(epIDs, showid=None): - if epIDs is None or len(epIDs) == 0: + if epIDs == None or len(epIDs) == 0: return [] query = "SELECT * FROM tv_episodes WHERE indexerid in (%s)" % (",".join(['?']*len(epIDs)),) params = epIDs - if showid is not None: + if showid != None: query += " AND showid = ?" params.append(showid) diff --git a/sickbeard/classes.py b/sickbeard/classes.py index 1c647d1c..e0f545dd 100644 --- a/sickbeard/classes.py +++ b/sickbeard/classes.py @@ -94,7 +94,7 @@ class SearchResult: def __str__(self): - if self.provider is None: + if self.provider == None: return "Invalid provider, unable to print self" myString = self.provider.name + " @ " + self.url + "\n" @@ -166,7 +166,7 @@ class Proper: self.episode = -1 def __str__(self): - return str(self.date)+" "+self.name+" "+str(self.season)+"x"+str(self.episode)+" of "+str(self.indexerid)+" from "+str(self.indexer) + return str(self.date)+" "+self.name+" "+str(self.season)+"x"+str(self.episode)+" of "+str(self.indexerid+" from "+self.indexer) class ErrorViewer(): diff --git a/sickbeard/clients/deluge.py b/sickbeard/clients/deluge.py index 2bbdcd33..137641b9 100644 --- a/sickbeard/clients/deluge.py +++ b/sickbeard/clients/deluge.py @@ -132,7 +132,7 @@ class DelugeAPI(GenericClient): self._request(method='post', data=post_data) labels = self.response.json()['result'] - if labels is not None: + if labels != None: if label not in labels: logger.log(self.name + ': ' + label +u" label does not exist in Deluge we must add it", logger.DEBUG) post_data = json.dumps({"method": 'label.add', diff --git a/sickbeard/clients/generic.py b/sickbeard/clients/generic.py index 06734a9c..5ba4e0de 100644 --- a/sickbeard/clients/generic.py +++ b/sickbeard/clients/generic.py @@ -26,9 +26,8 @@ class GenericClient(object): self.session = requests.session() self.session.auth = (self.username, self.password) - def _request(self, method='get', params=None, data=None, files=None): + def _request(self, method='get', params={}, data=None, files=None): - if not params: params = {} if time.time() > self.last_time + 1800 or not self.auth: self.last_time = time.time() self._get_auth() @@ -131,7 +130,8 @@ class GenericClient(object): if len(torrent_hash) == 32: torrent_hash = b16encode(b32decode(torrent_hash)).lower() else: - torrent_hash = sha1(bencode.bdecode(result.content)["info"]).hexdigest() + info = bdecode(result.content)["info"] + torrent_hash = sha1(bencode(info)).hexdigest() return torrent_hash diff --git a/sickbeard/clients/rtorrent.py b/sickbeard/clients/rtorrent.py index 438da481..ac39df2c 100644 --- a/sickbeard/clients/rtorrent.py +++ b/sickbeard/clients/rtorrent.py @@ -75,6 +75,34 @@ class rTorrentAPI(GenericClient): except: return False + if not self.auth: + return False + + if not result: + return False + + try: + # Send magnet to rTorrent + torrent = self.auth.load_magnet(result.url, result.hash) + + if not torrent: + return False + + # Set label + if sickbeard.TORRENT_LABEL: + torrent.set_custom(1, sickbeard.TORRENT_LABEL.lower()) + + if sickbeard.TORRENT_PATH: + torrent.set_directory(sickbeard.TORRENT_PATH) + + # Start torrent + torrent.start() + + return True + + except: + return False + def _add_torrent_file(self, result): filedata = None diff --git a/sickbeard/clients/utorrent.py b/sickbeard/clients/utorrent.py index 7b4b427b..ac5f0cac 100644 --- a/sickbeard/clients/utorrent.py +++ b/sickbeard/clients/utorrent.py @@ -29,9 +29,8 @@ class uTorrentAPI(GenericClient): self.url = self.host + 'gui/' - def _request(self, method='get', params=None, files=None): + def _request(self, method='get', params={}, files=None): - if not params: params = {} params.update({'token':self.auth}) return super(uTorrentAPI, self)._request(method=method, params=params, files=files) diff --git a/sickbeard/config.py b/sickbeard/config.py index abed8943..a6764c56 100644 --- a/sickbeard/config.py +++ b/sickbeard/config.py @@ -174,7 +174,7 @@ def change_VERSION_NOTIFY(version_notify): sickbeard.VERSION_NOTIFY = version_notify - if not version_notify: + if version_notify == False: sickbeard.NEWEST_VERSION_STRING = None if oldSetting == False and version_notify == True: @@ -265,7 +265,7 @@ def clean_url(url): url = 'http://' + url if not url.endswith('/'): - url += '/' + url = url + '/' else: url = '' diff --git a/sickbeard/databases/mainDB.py b/sickbeard/databases/mainDB.py index f5b9b61d..a6b73673 100644 --- a/sickbeard/databases/mainDB.py +++ b/sickbeard/databases/mainDB.py @@ -205,7 +205,7 @@ class AddSizeAndSceneNameFields(InitialSchema): except InvalidNameException: continue - if parse_result.series_name and parse_result.season_number is not None and parse_result.episode_numbers and parse_result.release_group: + if parse_result.series_name and parse_result.season_number != None and parse_result.episode_numbers and parse_result.release_group: # if all is well by this point we'll just put the release name into the database self.connection.action("UPDATE tv_episodes SET release_name = ? WHERE episode_id = ?", [cur_name, ep_results[0]["episode_id"]]) break @@ -312,16 +312,16 @@ class Add1080pAndRawHDQualities(AddIMDbInfo): result = old_quality # move fullhdbluray from 1<<5 to 1<<8 if set if(result & (1<<5)): - result &= ~(1 << 5) - result |= 1 << 8 + result = result & ~(1<<5) + result = result | (1<<8) # move hdbluray from 1<<4 to 1<<7 if set if(result & (1<<4)): - result &= ~(1 << 4) - result |= 1 << 7 + result = result & ~(1<<4) + result = result | (1<<7) # move hdwebdl from 1<<3 to 1<<5 if set if(result & (1<<3)): - result &= ~(1 << 3) - result |= 1 << 5 + result = result & ~(1<<3) + result = result | (1<<5) return result diff --git a/sickbeard/db.py b/sickbeard/db.py index a871db62..06ab5301 100644 --- a/sickbeard/db.py +++ b/sickbeard/db.py @@ -70,7 +70,7 @@ class DBConnection: with db_lock: - if query is None: + if query == None: return sqlResult = None @@ -78,7 +78,7 @@ class DBConnection: while attempt < 5: try: - if args is None: + if args == None: logger.log(self.filename + ": " + query, logger.DB) cursor = self.connection.cursor() cursor.execute(query) @@ -109,7 +109,7 @@ class DBConnection: with db_lock: - if querylist is None: + if querylist == None: return sqlResult = [] @@ -153,7 +153,7 @@ class DBConnection: with db_lock: - if query is None: + if query == None: return sqlResult = None @@ -161,7 +161,7 @@ class DBConnection: while attempt < 5: try: - if args is None: + if args == None: logger.log(self.filename + ": " + query, logger.DB) sqlResult = self.connection.execute(query) else: @@ -189,7 +189,7 @@ class DBConnection: sqlResults = self.action(query, args).fetchall() - if sqlResults is None: + if sqlResults == None: return [] return sqlResults diff --git a/sickbeard/encodingKludge.py b/sickbeard/encodingKludge.py index 9cdf9cab..0d54554d 100644 --- a/sickbeard/encodingKludge.py +++ b/sickbeard/encodingKludge.py @@ -38,11 +38,13 @@ def fixStupidEncodings(x, silent=False): logger.log(u"Unknown value passed in, ignoring it: "+str(type(x))+" ("+repr(x)+":"+repr(type(x))+")", logger.DEBUG if silent else logger.ERROR) return None + return None + def fixListEncodings(x): if type(x) != list and type(x) != tuple: return x else: - return filter(lambda x: x is not None, map(fixStupidEncodings, x)) + return filter(lambda x: x != None, map(fixStupidEncodings, x)) def callPeopleStupid(x): try: diff --git a/sickbeard/generic_queue.py b/sickbeard/generic_queue.py index 1e87e4e4..fd72911e 100644 --- a/sickbeard/generic_queue.py +++ b/sickbeard/generic_queue.py @@ -58,10 +58,10 @@ class GenericQueue(object): def run(self): # only start a new task if one isn't already going - if self.thread is None or self.thread.isAlive() == False: + if self.thread == None or self.thread.isAlive() == False: # if the thread is dead then the current item should be finished - if self.currentItem is not None: + if self.currentItem != None: self.currentItem.finish() self.currentItem = None diff --git a/sickbeard/history.py b/sickbeard/history.py index eeaa27b3..4a95655c 100644 --- a/sickbeard/history.py +++ b/sickbeard/history.py @@ -46,7 +46,7 @@ def logSnatch(searchResult): quality = searchResult.quality providerClass = searchResult.provider - if providerClass is not None: + if providerClass != None: provider = providerClass.name else: provider = "unknown" diff --git a/sickbeard/image_cache.py b/sickbeard/image_cache.py index 8f381a31..e3c5c0f0 100644 --- a/sickbeard/image_cache.py +++ b/sickbeard/image_cache.py @@ -261,7 +261,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 is None: + if cur_file_type == 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/metadata/generic.py b/sickbeard/metadata/generic.py index 607e7b6e..d90c661d 100644 --- a/sickbeard/metadata/generic.py +++ b/sickbeard/metadata/generic.py @@ -140,21 +140,21 @@ class GenericMetadata(): def _has_episode_thumb(self, ep_obj): location = self.get_episode_thumb_path(ep_obj) - result = location is not None and ek.ek(os.path.isfile, location) + result = location != None and ek.ek(os.path.isfile, location) if location: logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) return result def _has_season_poster(self, show_obj, season): location = self.get_season_poster_path(show_obj, season) - result = location is not None and ek.ek(os.path.isfile, location) + result = location != None and ek.ek(os.path.isfile, location) if location: logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) return result def _has_season_banner(self, show_obj, season): location = self.get_season_banner_path(show_obj, season) - result = location is not None and ek.ek(os.path.isfile, location) + result = location != None and ek.ek(os.path.isfile, location) if location: logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) return result @@ -595,6 +595,8 @@ class GenericMetadata(): else: return False + return True + def save_season_banners(self, show_obj, season): """ Saves all season banners to disk for the given show. @@ -640,6 +642,8 @@ class GenericMetadata(): else: return False + return True + def save_season_all_poster(self, show_obj, which=None): # use the default season all poster name poster_path = self.get_season_all_poster_path(show_obj) @@ -886,8 +890,8 @@ class GenericMetadata(): with ek.ek(open, metadata_path, 'r') as xmlFileObj: showXML = etree.ElementTree(file=xmlFileObj) - if showXML.findtext('title') is None \ - or (showXML.findtext('tvdbid') is None and showXML.findtext('id') is None): + if showXML.findtext('title') == None\ + or (showXML.findtext('tvdbid') == None and showXML.findtext('id') == None): logger.log(u"Invalid info in tvshow.nfo (missing name or id):" \ + str(showXML.findtext('title')) + " " \ + str(showXML.findtext('indexer')) + " " \ @@ -897,9 +901,9 @@ class GenericMetadata(): name = showXML.findtext('title') indexer = showXML.findtext('indexer') - if showXML.findtext('tvdbid') is not None: + if showXML.findtext('tvdbid') != None: indexer_id = int(showXML.findtext('tvdbid')) - elif showXML.findtext('id') is not None: + elif showXML.findtext('id') != None: indexer_id = int(showXML.findtext('id')) else: logger.log(u"Empty or field in NFO, unable to find a ID", logger.WARNING) diff --git a/sickbeard/metadata/helpers.py b/sickbeard/metadata/helpers.py index 80870d5e..67f9751d 100644 --- a/sickbeard/metadata/helpers.py +++ b/sickbeard/metadata/helpers.py @@ -24,11 +24,11 @@ def getShowImage(url, imgNum=None): image_data = None # @UnusedVariable - if url is None: + if url == None: return None # if they provided a fanart number try to use it instead - if imgNum is not None: + if imgNum != None: tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg" else: tempURL = url diff --git a/sickbeard/metadata/mediabrowser.py b/sickbeard/metadata/mediabrowser.py index 19bcef61..f882c1bc 100644 --- a/sickbeard/metadata/mediabrowser.py +++ b/sickbeard/metadata/mediabrowser.py @@ -261,7 +261,7 @@ class MediaBrowserMetadata(generic.GenericMetadata): indexerid.text = myShow['id'] indexer = etree.SubElement(tv_node, "indexer") - if show_obj.indexer is not None: + if show_obj.indexer != None: indexer.text = show_obj.indexer SeriesName = etree.SubElement(tv_node, "SeriesName") @@ -363,7 +363,7 @@ class MediaBrowserMetadata(generic.GenericMetadata): cur_actor_type.text = "Actor" cur_actor_role = etree.SubElement(cur_actor, "Role") cur_actor_role_text = actor['role'] - if cur_actor_role_text is not None: + if cur_actor_role_text != None: cur_actor_role.text = cur_actor_role_text helpers.indentXML(tv_node) @@ -433,7 +433,7 @@ class MediaBrowserMetadata(generic.GenericMetadata): episode = rootNode EpisodeName = etree.SubElement(episode, "EpisodeName") - if curEpToWrite.name is not None: + if curEpToWrite.name != None: EpisodeName.text = curEpToWrite.name else: EpisodeName.text = "" @@ -462,7 +462,7 @@ class MediaBrowserMetadata(generic.GenericMetadata): MetadataType.text = "Episode" Overview = etree.SubElement(episode, "Overview") - if curEpToWrite.description is not None: + if curEpToWrite.description != None: Overview.text = curEpToWrite.description else: Overview.text = "" @@ -471,7 +471,7 @@ class MediaBrowserMetadata(generic.GenericMetadata): Rating = etree.SubElement(episode, "Rating") if getattr(myEp, 'rating', None) is not None: rating_text = myEp['rating'] - if rating_text is not None: + if rating_text != None: Rating.text = rating_text IMDB_ID = etree.SubElement(episode, "IMDB_ID") diff --git a/sickbeard/metadata/wdtv.py b/sickbeard/metadata/wdtv.py index 263e2428..df3d93bb 100644 --- a/sickbeard/metadata/wdtv.py +++ b/sickbeard/metadata/wdtv.py @@ -229,7 +229,7 @@ class WDTVMetadata(generic.GenericMetadata): seriesName.text = myShow["seriesname"] episodeName = etree.SubElement(episode, "episode_name") - if curEpToWrite.name is not None: + if curEpToWrite.name != None: episodeName.text = curEpToWrite.name seasonNumber = etree.SubElement(episode, "season_number") @@ -264,7 +264,7 @@ class WDTVMetadata(generic.GenericMetadata): director = etree.SubElement(episode, "director") if getattr(myEp, 'director', None) is not None: director_text = myEp['director'] - if director_text is not None: + if director_text != None: director.text = director_text if getattr(myShow, '_actors', None) is not None: @@ -274,11 +274,11 @@ class WDTVMetadata(generic.GenericMetadata): cur_actor_name.text = actor['name'] cur_actor_role = etree.SubElement(cur_actor, "role") cur_actor_role_text = actor['role'] - if cur_actor_role_text is not None: + if cur_actor_role_text != None: cur_actor_role.text = cur_actor_role_text overview = etree.SubElement(episode, "overview") - if curEpToWrite.description is not None: + if curEpToWrite.description != None: overview.text = curEpToWrite.description # Make it purdy diff --git a/sickbeard/metadata/xbmc_12plus.py b/sickbeard/metadata/xbmc_12plus.py index 7eef407f..bfc02190 100644 --- a/sickbeard/metadata/xbmc_12plus.py +++ b/sickbeard/metadata/xbmc_12plus.py @@ -193,12 +193,12 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): cur_actor_role = etree.SubElement(cur_actor, "role") cur_actor_role_text = actor['role'] - if cur_actor_role_text is not None: + if cur_actor_role_text != None: cur_actor_role.text = cur_actor_role_text cur_actor_thumb = etree.SubElement(cur_actor, "thumb") cur_actor_thumb_text = actor['image'] - if cur_actor_thumb_text is not None: + if cur_actor_thumb_text != None: cur_actor_thumb.text = cur_actor_thumb_text # Make it purdy @@ -267,11 +267,11 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): episode = rootNode title = etree.SubElement(episode, "title") - if curEpToWrite.name is not None: + if curEpToWrite.name != None: title.text = curEpToWrite.name showtitle = etree.SubElement(episode, "showtitle") - if curEpToWrite.show.name is not None: + if curEpToWrite.show.name != None: showtitle.text = curEpToWrite.show.name season = etree.SubElement(episode, "season") @@ -290,7 +290,7 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): aired.text = '' plot = etree.SubElement(episode, "plot") - if curEpToWrite.description is not None: + if curEpToWrite.description != None: plot.text = curEpToWrite.description runtime = etree.SubElement(episode, "runtime") @@ -301,18 +301,18 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): displayseason = etree.SubElement(episode, "displayseason") if getattr(myEp, 'airsbefore_season', None) is not None: displayseason_text = myEp['airsbefore_season'] - if displayseason_text is not None: + if displayseason_text != None: displayseason.text = displayseason_text displayepisode = etree.SubElement(episode, "displayepisode") if getattr(myEp, 'airsbefore_episode', None) is not None: displayepisode_text = myEp['airsbefore_episode'] - if displayepisode_text is not None: + if displayepisode_text != None: displayepisode.text = displayepisode_text thumb = etree.SubElement(episode, "thumb") thumb_text = getattr(myEp, 'filename', None) - if thumb_text is not None: + if thumb_text != None: thumb.text = thumb_text watched = etree.SubElement(episode, "watched") @@ -320,17 +320,17 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): credits = etree.SubElement(episode, "credits") credits_text = getattr(myEp, 'writer', None) - if credits_text is not None: + if credits_text != None: credits.text = credits_text director = etree.SubElement(episode, "director") director_text = getattr(myEp, 'director', None) - if director_text is not None: + if director_text != None: director.text = director_text rating = etree.SubElement(episode, "rating") rating_text = getattr(myEp, 'rating', None) - if rating_text is not None: + if rating_text != None: rating.text = rating_text gueststar_text = getattr(myEp, 'gueststars', None) @@ -351,12 +351,12 @@ class XBMC_12PlusMetadata(generic.GenericMetadata): cur_actor_role = etree.SubElement(cur_actor, "role") cur_actor_role_text = actor['role'] - if cur_actor_role_text is not None: + if cur_actor_role_text != None: cur_actor_role.text = cur_actor_role_text cur_actor_thumb = etree.SubElement(cur_actor, "thumb") cur_actor_thumb_text = actor['image'] - if cur_actor_thumb_text is not None: + if cur_actor_thumb_text != None: cur_actor_thumb.text = cur_actor_thumb_text # Make it purdy diff --git a/sickbeard/name_parser/parser.py b/sickbeard/name_parser/parser.py index ab07048a..044d056f 100644 --- a/sickbeard/name_parser/parser.py +++ b/sickbeard/name_parser/parser.py @@ -154,7 +154,7 @@ class NameParser(object): b = getattr(second, attr) # if a is good use it - if a is not None or (type(a) == list and len(a)): + if a != None or (type(a) == list and len(a)): return a # if not use b (if b isn't set it'll just be default) else: @@ -242,7 +242,7 @@ class NameParser(object): final_result.which_regex += dir_name_result.which_regex # if there's no useful info in it then raise an exception - if final_result.season_number is None and not final_result.episode_numbers and final_result.air_date is None and not final_result.series_name: + if final_result.season_number == None and not final_result.episode_numbers and final_result.air_date == None and not final_result.series_name: raise InvalidNameException("Unable to parse " + name.encode(sickbeard.SYS_ENCODING, 'xmlcharrefreplace')) name_parser_cache.add(name, final_result) @@ -363,11 +363,11 @@ class ParseResult(object): return True def __str__(self): - if self.series_name is not None: + if self.series_name != None: to_return = self.series_name + u' - ' else: to_return = u'' - if self.season_number is not None: + if self.season_number != None: to_return += 'S'+str(self.season_number) if self.episode_numbers and len(self.episode_numbers): for e in self.episode_numbers: @@ -386,7 +386,7 @@ class ParseResult(object): return to_return.encode('utf-8') def _is_air_by_date(self): - if self.season_number is None and len(self.episode_numbers) == 0 and self.air_date: + if self.season_number == None and len(self.episode_numbers) == 0 and self.air_date: return True return False air_by_date = property(_is_air_by_date) @@ -397,7 +397,7 @@ class ParseResult(object): tvdb numbering, if necessary. """ if self.air_by_date: return self # scene numbering does not apply to air-by-date - if self.season_number is None: return self # can't work without a season + if self.season_number == None: return self # can't work without a season if len(self.episode_numbers) == 0: return self # need at least one episode indexer_id = NameParser.series_name_to_indexer_id(self.series_name, True, True, False) diff --git a/sickbeard/naming.py b/sickbeard/naming.py index 21eaa86c..f355a97a 100644 --- a/sickbeard/naming.py +++ b/sickbeard/naming.py @@ -65,12 +65,12 @@ def check_force_season_folders(pattern=None, multi=None): Returns true if season folders need to be forced on or false otherwise. """ - if pattern is None: + if pattern == None: pattern = sickbeard.NAMING_PATTERN valid = not validate_name(pattern, None, file_only=True) - if multi is not None: + if multi != None: valid = valid or not validate_name(pattern, multi, file_only=True) return valid @@ -81,13 +81,13 @@ def check_valid_naming(pattern=None, multi=None): Returns true if the naming is valid, false if not. """ - if pattern is None: + if pattern == None: pattern = sickbeard.NAMING_PATTERN logger.log(u"Checking whether the pattern "+pattern+" is valid for a single episode", logger.DEBUG) valid = validate_name(pattern, None) - if multi is not None: + if multi != None: logger.log(u"Checking whether the pattern "+pattern+" is valid for a multi episode", logger.DEBUG) valid = valid and validate_name(pattern, multi) @@ -99,7 +99,7 @@ def check_valid_abd_naming(pattern=None): Returns true if the naming is valid, false if not. """ - if pattern is None: + if pattern == None: pattern = sickbeard.NAMING_PATTERN logger.log(u"Checking whether the pattern "+pattern+" is valid for an air-by-date episode", logger.DEBUG) @@ -156,7 +156,7 @@ def _generate_sample_ep(multi=None, abd=False): else: ep._release_name = 'Show.Name.S02E03.HDTV.XviD-RLSGROUP' - if multi is not None: + if multi != None: ep._name = "Ep Name (1)" ep._release_name = 'Show.Name.S02E03E04E05.HDTV.XviD-RLSGROUP' diff --git a/sickbeard/notifiers/boxcar.py b/sickbeard/notifiers/boxcar.py index 416dc37e..633245f1 100644 --- a/sickbeard/notifiers/boxcar.py +++ b/sickbeard/notifiers/boxcar.py @@ -52,7 +52,7 @@ class BoxcarNotifier: # if this is a subscription notification then act accordingly if subscribe: data = urllib.urlencode({'email': email}) - curUrl += "/subscribe" + curUrl = curUrl + "/subscribe" # for normal requests we need all these parameters else: diff --git a/sickbeard/notifiers/emailnotify.py b/sickbeard/notifiers/emailnotify.py index a943d8f2..f872e75f 100644 --- a/sickbeard/notifiers/emailnotify.py +++ b/sickbeard/notifiers/emailnotify.py @@ -32,145 +32,145 @@ from sickbeard import db from sickbeard.exceptions import ex class EmailNotifier: - def __init__(self): - self.last_err = None + def __init__(self): + self.last_err = None + + def test_notify(self, host, port, smtp_from, use_tls, user, pwd, to): + msg = MIMEText('This is a test message from Sick Beard. If you\'re reading this, the test succeeded.') + msg['Subject'] = 'Sick Beard: Test Message' + msg['From'] = smtp_from + msg['To'] = to + return self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True) - def test_notify(self, host, port, smtp_from, use_tls, user, pwd, to): - msg = MIMEText('This is a test message from Sick Beard. If you\'re reading this, the test succeeded.') - msg['Subject'] = 'Sick Beard: Test Message' - msg['From'] = smtp_from - msg['To'] = to - return self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True) + def notify_snatch(self, ep_name, title="Snatched:"): + """ + Send a notification that an episode was snatched + + ep_name: The name of the episode that was snatched + title: The title of the notification (optional) + """ + if sickbeard.EMAIL_NOTIFY_ONSNATCH: + show = self._parseEp(ep_name) + to = self._generate_recepients(show) + if len(to) == 0: + logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) + else: + try: + msg = MIMEMultipart('alternative') + msg.attach(MIMEText("

    Sick Beard Notification - Snatched

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) + except: + msg = MIMEText(ep_name) + + msg['Subject'] = 'Snatched: ' + ep_name + msg['From'] = sickbeard.EMAIL_FROM + msg['To'] = ','.join(to) + if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): + logger.log("Snatch notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) + else: + logger.log("Snatch notification ERROR: %s" % self.last_err, logger.ERROR) - def notify_snatch(self, ep_name, title="Snatched:"): - """ - Send a notification that an episode was snatched + def notify_download(self, ep_name, title="Completed:"): + """ + Send a notification that an episode was downloaded + + ep_name: The name of the episode that was downloaded + title: The title of the notification (optional) + """ + if sickbeard.EMAIL_NOTIFY_ONDOWNLOAD: + show = self._parseEp(ep_name) + to = self._generate_recepients(show) + if len(to) == 0: + logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) + else: + try: + msg = MIMEMultipart('alternative') + msg.attach(MIMEText("

    Sick Beard Notification - Downloaded

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) + except: + msg = MIMEText(ep_name) + + msg['Subject'] = 'Downloaded: ' + ep_name + msg['From'] = sickbeard.EMAIL_FROM + msg['To'] = ','.join(to) + if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): + logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) + else: + logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) - ep_name: The name of the episode that was snatched - title: The title of the notification (optional) - """ - if sickbeard.EMAIL_NOTIFY_ONSNATCH: - show = self._parseEp(ep_name) - to = self._generate_recepients(show) - if len(to) == 0: - logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) - else: - try: - msg = MIMEMultipart('alternative') - msg.attach(MIMEText("

    Sick Beard Notification - Snatched

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) - except: - msg = MIMEText(ep_name) + def notify_subtitle_download(self, ep_name, lang, title="Downloaded subtitle:"): + """ + Send a notification that an subtitle was downloaded + + ep_name: The name of the episode that was downloaded + lang: Subtitle language wanted + """ + if sickbeard.EMAIL_NOTIFY_ONSUBTITLEDOWNLOAD: + show = self._parseEp(ep_name) + to = self._generate_recepients(show) + if len(to) == 0: + logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) + else: + try: + msg = MIMEMultipart('alternative') + msg.attach(MIMEText("

    Sick Beard Notification - Subtitle Downloaded

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n

    Language: " + lang + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) + except: + msg = MIMEText(ep_name + ": " + lang) + + msg['Subject'] = lang + ' Subtitle Downloaded: ' + ep_name + msg['From'] = sickbeard.EMAIL_FROM + msg['To'] = ','.join(to) + if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): + logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) + else: + logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) - msg['Subject'] = 'Snatched: ' + ep_name - msg['From'] = sickbeard.EMAIL_FROM - msg['To'] = ','.join(to) - if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): - logger.log("Snatch notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) - else: - logger.log("Snatch notification ERROR: %s" % self.last_err, logger.ERROR) + def _generate_recepients(self, show): + addrs = [] - def notify_download(self, ep_name, title="Completed:"): - """ - Send a notification that an episode was downloaded + # Grab the global recipients + for addr in sickbeard.EMAIL_LIST.split(','): + if(len(addr.strip()) > 0): + addrs.append(addr) - ep_name: The name of the episode that was downloaded - title: The title of the notification (optional) - """ - if sickbeard.EMAIL_NOTIFY_ONDOWNLOAD: - show = self._parseEp(ep_name) - to = self._generate_recepients(show) - if len(to) == 0: - logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) - else: - try: - msg = MIMEMultipart('alternative') - msg.attach(MIMEText("

    Sick Beard Notification - Downloaded

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) - except: - msg = MIMEText(ep_name) - - msg['Subject'] = 'Downloaded: ' + ep_name - msg['From'] = sickbeard.EMAIL_FROM - msg['To'] = ','.join(to) - if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): - logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) - else: - logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) - - def notify_subtitle_download(self, ep_name, lang, title="Downloaded subtitle:"): - """ - Send a notification that an subtitle was downloaded - - ep_name: The name of the episode that was downloaded - lang: Subtitle language wanted - """ - if sickbeard.EMAIL_NOTIFY_ONSUBTITLEDOWNLOAD: - show = self._parseEp(ep_name) - to = self._generate_recepients(show) - if len(to) == 0: - logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) - else: - try: - msg = MIMEMultipart('alternative') - msg.attach(MIMEText("

    Sick Beard Notification - Subtitle Downloaded

    \n

    Show: " + re.search("(.+?) -.+", ep_name).group(1) + "

    \n

    Episode: " + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "

    \n

    Language: " + lang + "

    \n\n
    Powered by Sick Beard.
    ", 'html')) - except: - msg = MIMEText(ep_name + ": " + lang) - - msg['Subject'] = lang + ' Subtitle Downloaded: ' + ep_name - msg['From'] = sickbeard.EMAIL_FROM - msg['To'] = ','.join(to) - if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg): - logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG) - else: - logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR) - - def _generate_recepients(self, show): - addrs = [] - - # Grab the global recipients - for addr in sickbeard.EMAIL_LIST.split(','): - if(len(addr.strip()) > 0): - addrs.append(addr) - - # Grab the recipients for the show - mydb = db.DBConnection() - for s in show: - for subs in mydb.select("SELECT notify_list FROM tv_shows WHERE show_name = ?", (s,)): - if subs['notify_list']: - for addr in subs['notify_list'].split(','): - if(len(addr.strip()) > 0): - addrs.append(addr) - - addrs = set(addrs) - logger.log('Notification recepients: %s' % addrs, logger.DEBUG) - return addrs - - def _sendmail(self, host, port, smtp_from, use_tls, user, pwd, to, msg, smtpDebug=False): - logger.log('HOST: %s; PORT: %s; FROM: %s, TLS: %s, USER: %s, PWD: %s, TO: %s' % (host, port, smtp_from, use_tls, user, pwd, to), logger.DEBUG) - srv = smtplib.SMTP(host, int(port)) - if smtpDebug: - srv.set_debuglevel(1) - try: - if (use_tls == '1' or use_tls == True) or (len(user) > 0 and len(pwd) > 0): - srv.ehlo() - logger.log('Sent initial EHLO command!', logger.DEBUG) - if use_tls == '1' or use_tls == True: - srv.starttls() - logger.log('Sent STARTTLS command!', logger.DEBUG) - if len(user) > 0 and len(pwd) > 0: - srv.login(user, pwd) - logger.log('Sent LOGIN command!', logger.DEBUG) - srv.sendmail(smtp_from, to, msg.as_string()) - srv.quit() - return True - except Exception as e: - self.last_err = '%s' % e - return False - - def _parseEp(self, ep_name): - sep = " - " - titles = ep_name.split(sep) - titles.sort(key=len, reverse=True) - logger.log("TITLES: %s" % titles, logger.DEBUG) - return titles + # Grab the recipients for the show + mydb = db.DBConnection() + for s in show: + for subs in mydb.select("SELECT notify_list FROM tv_shows WHERE show_name = ?", (s,)): + if subs['notify_list']: + for addr in subs['notify_list'].split(','): + if(len(addr.strip()) > 0): + addrs.append(addr) + + addrs = set(addrs) + logger.log('Notification recepients: %s' % addrs, logger.DEBUG) + return addrs + + def _sendmail(self, host, port, smtp_from, use_tls, user, pwd, to, msg, smtpDebug=False): + logger.log('HOST: %s; PORT: %s; FROM: %s, TLS: %s, USER: %s, PWD: %s, TO: %s' % (host, port, smtp_from, use_tls, user, pwd, to), logger.DEBUG) + srv = smtplib.SMTP(host, int(port)) + if smtpDebug: + srv.set_debuglevel(1) + try: + if (use_tls == '1' or use_tls == True) or (len(user) > 0 and len(pwd) > 0): + srv.ehlo() + logger.log('Sent initial EHLO command!', logger.DEBUG) + if use_tls == '1' or use_tls == True: + srv.starttls() + logger.log('Sent STARTTLS command!', logger.DEBUG) + if len(user) > 0 and len(pwd) > 0: + srv.login(user, pwd) + logger.log('Sent LOGIN command!', logger.DEBUG) + srv.sendmail(smtp_from, to, msg.as_string()) + srv.quit() + return True + except Exception as e: + self.last_err = '%s' % e + return False + def _parseEp(self, ep_name): + sep = " - " + titles = ep_name.split(sep) + titles.sort(key=len, reverse=True) + logger.log("TITLES: %s" % titles, logger.DEBUG) + return titles + notifier = EmailNotifier diff --git a/sickbeard/notifiers/growl.py b/sickbeard/notifiers/growl.py index ebedb4f4..86d901be 100644 --- a/sickbeard/notifiers/growl.py +++ b/sickbeard/notifiers/growl.py @@ -88,10 +88,10 @@ class GrowlNotifier: if not sickbeard.USE_GROWL and not force: return False - if name is None: + if name == None: name = title - if host is None: + if host == None: hostParts = sickbeard.GROWL_HOST.split(':') else: hostParts = host.split(':') @@ -114,7 +114,7 @@ class GrowlNotifier: opts['priority'] = None opts['debug'] = False - if password is None: + if password == None: opts['password'] = sickbeard.GROWL_PASSWORD else: opts['password'] = password @@ -141,7 +141,7 @@ class GrowlNotifier: def _sendRegistration(self, host=None, password=None, name='Sick Beard Notification'): opts = {} - if host is None: + if host == None: hostParts = sickbeard.GROWL_HOST.split(':') else: hostParts = host.split(':') @@ -155,7 +155,7 @@ class GrowlNotifier: opts['port'] = port - if password is None: + if password == None: opts['password'] = sickbeard.GROWL_PASSWORD else: opts['password'] = password diff --git a/sickbeard/notifiers/nma.py b/sickbeard/notifiers/nma.py index e3bc1557..1c67990f 100644 --- a/sickbeard/notifiers/nma.py +++ b/sickbeard/notifiers/nma.py @@ -27,10 +27,10 @@ class NMA_Notifier: if not sickbeard.USE_NMA and not force: return False - if nma_api is None: + if nma_api == None: nma_api = sickbeard.NMA_API - if nma_priority is None: + if nma_priority == None: nma_priority = sickbeard.NMA_PRIORITY logger.log(u"NMA title: " + title, logger.DEBUG) diff --git a/sickbeard/notifiers/nmjv2.py b/sickbeard/notifiers/nmjv2.py index 15187b04..95dd4436 100644 --- a/sickbeard/notifiers/nmjv2.py +++ b/sickbeard/notifiers/nmjv2.py @@ -65,7 +65,7 @@ class NMJv2Notifier: xml = parseString(response1) time.sleep (300.0 / 1000.0) for node in xml.getElementsByTagName('path'): - xmlTag=node.toxml() + xmlTag=node.toxml(); xmlData=xmlTag.replace('','').replace('','').replace('[=]','') url_db = "http://" + host + ":8008/metadata_database?arg0=check_database&arg1="+ xmlData reqdb = urllib2.Request(url_db) diff --git a/sickbeard/notifiers/prowl.py b/sickbeard/notifiers/prowl.py index 1ece0c8f..4f0e932c 100644 --- a/sickbeard/notifiers/prowl.py +++ b/sickbeard/notifiers/prowl.py @@ -53,10 +53,10 @@ class ProwlNotifier: if not sickbeard.USE_PROWL and not force: return False - if prowl_api is None: + if prowl_api == None: prowl_api = sickbeard.PROWL_API - if prowl_priority is None: + if prowl_priority == None: prowl_priority = sickbeard.PROWL_PRIORITY diff --git a/sickbeard/notifiers/pushalot.py b/sickbeard/notifiers/pushalot.py index 72d8f742..3d3d634d 100644 --- a/sickbeard/notifiers/pushalot.py +++ b/sickbeard/notifiers/pushalot.py @@ -46,7 +46,7 @@ class PushalotNotifier: if not sickbeard.USE_PUSHALOT and not force: return False - if pushalot_authorizationtoken is None: + if pushalot_authorizationtoken == None: pushalot_authorizationtoken = sickbeard.PUSHALOT_AUTHORIZATIONTOKEN logger.log(u"Pushalot event: " + event, logger.DEBUG) diff --git a/sickbeard/notifiers/pushbullet.py b/sickbeard/notifiers/pushbullet.py index a024d3d8..8135c803 100644 --- a/sickbeard/notifiers/pushbullet.py +++ b/sickbeard/notifiers/pushbullet.py @@ -50,9 +50,9 @@ class PushbulletNotifier: if not sickbeard.USE_PUSHBULLET and not force: return False - if pushbullet_api is None: + if pushbullet_api == None: pushbullet_api = sickbeard.PUSHBULLET_API - if pushbullet_device is None: + if pushbullet_device == None: pushbullet_device = sickbeard.PUSHBULLET_DEVICE if method == 'POST': @@ -70,7 +70,7 @@ class PushbulletNotifier: authString = base64.encodestring('%s:' % (pushbullet_api)).replace('\n', '') - if notificationType is None: + if notificationType == None: testMessage = True try: logger.log(u"Testing Pushbullet authentication and retrieving the device list.", logger.DEBUG) diff --git a/sickbeard/notifiers/xbmc.py b/sickbeard/notifiers/xbmc.py index 2c7def38..0013c1e4 100644 --- a/sickbeard/notifiers/xbmc.py +++ b/sickbeard/notifiers/xbmc.py @@ -185,6 +185,8 @@ class XBMCNotifier: logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.DEBUG) return False + return False + ############################################################################## # Legacy HTTP API (pre XBMC 12) methods ############################################################################## @@ -523,7 +525,7 @@ class XBMCNotifier: return True else: logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.ERROR) - result += 1 + result = result + 1 # needed for the 'update xbmc' submenu command # as it only cares of the final result vs the individual ones diff --git a/sickbeard/nzbSplitter.py b/sickbeard/nzbSplitter.py index 61ca86f3..bc8a4a69 100644 --- a/sickbeard/nzbSplitter.py +++ b/sickbeard/nzbSplitter.py @@ -124,7 +124,7 @@ def splitResult(result): return False # bust it up - season = parse_result.season_number if parse_result.season_number is not None else 1 + season = parse_result.season_number if parse_result.season_number != None else 1 separateNZBs, xmlns = getSeasonNZBs(result.name, urlData, season) @@ -143,8 +143,7 @@ def splitResult(result): return False # make sure the result is sane - if (parse_result.season_number is not None and parse_result.season_number != season) or ( - parse_result.season_number is None and season != 1): + if (parse_result.season_number != None and parse_result.season_number != season) or (parse_result.season_number == 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) continue elif len(parse_result.episode_numbers) == 0: diff --git a/sickbeard/nzbget.py b/sickbeard/nzbget.py index f5d78623..076c1ddc 100644 --- a/sickbeard/nzbget.py +++ b/sickbeard/nzbget.py @@ -39,7 +39,7 @@ def sendNZB(nzb, proper = False): nzbgetprio = 0 nzbgetXMLrpc = "http://%(username)s:%(password)s@%(host)s/xmlrpc" - if sickbeard.NZBGET_HOST is None: + if sickbeard.NZBGET_HOST == None: logger.log(u"No NZBget host found in configuration. Please configure it.", logger.ERROR) return False @@ -83,7 +83,7 @@ def sendNZB(nzb, proper = False): if nzb.resultType == "nzb": genProvider = GenericProvider("") data = genProvider.getURL(nzb.url) - if (data is None): + if (data == None): return False # if we get a raw data result thats even better diff --git a/sickbeard/postProcessor.py b/sickbeard/postProcessor.py index 00f0b94c..e4151dcc 100644 --- a/sickbeard/postProcessor.py +++ b/sickbeard/postProcessor.py @@ -171,7 +171,7 @@ class PostProcessor(object): base_name = file_path.rpartition('.')[0] if not base_name_only: - base_name += '.' + base_name = base_name + '.' # don't strip it all and use cwd by accident if not base_name: @@ -476,10 +476,10 @@ class PostProcessor(object): # remember whether it's a proper if parse_result.extra_info: - self.is_proper = re.search('(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) is not None + self.is_proper = re.search('(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) != None # if the result is complete then remember that for later - if parse_result.series_name and parse_result.season_number is not None and parse_result.episode_numbers and parse_result.release_group: + if parse_result.series_name and parse_result.season_number != None and parse_result.episode_numbers and parse_result.release_group: test_name = os.path.basename(name) if test_name == self.nzb_name: self.good_results[self.NZB_NAME] = True @@ -591,7 +591,7 @@ class PostProcessor(object): # if we already did a successful history lookup then keep that indexer_id value if cur_indexer_id and not (self.in_history and indexer_id): indexer_id = cur_indexer_id - if cur_season is not None: + if cur_season != None: season = cur_season if cur_episodes: episodes = cur_episodes @@ -604,7 +604,7 @@ class PostProcessor(object): indexer_lang = None try: showObj = helpers.findCertainShow(sickbeard.showList, indexer_id) - if(showObj is not None): + if(showObj != None): # set the language of the show indexer_lang = showObj.lang self.indexer = showObj.indexer @@ -636,14 +636,14 @@ class PostProcessor(object): continue # if there's no season then we can hopefully just use 1 automatically - elif season is None and indexer_id: + elif season == None and indexer_id: myDB = db.DBConnection() numseasonsSQlResult = myDB.select("SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0", [indexer_id]) - if int(numseasonsSQlResult[0][0]) == 1 and season is None: + if int(numseasonsSQlResult[0][0]) == 1 and season == None: self._log(u"Don't have a season number, but this show appears to only have 1 season, setting seasonnumber to 1...", logger.DEBUG) season = 1 - if indexer_id and season is not None and episodes: + if indexer_id and season != None and episodes: return (indexer_id, season, episodes) return (indexer_id, season, episodes) @@ -689,7 +689,7 @@ class PostProcessor(object): raise exceptions.PostProcessingFailed() # associate all the episodes together under a single root episode - if root_ep is None: + if root_ep == None: root_ep = curEp root_ep.relatedEps = [] elif curEp not in root_ep.relatedEps: @@ -830,14 +830,14 @@ class PostProcessor(object): # try to find the file info (indexer_id, season, episodes) = self._find_info() - if indexer_id and season is not None and episodes: + if indexer_id and season != None and episodes: break self._log(u"Can't find show on " + self.indexer + ", auto trying next indexer in list", logger.WARNING) else: (indexer_id, season, episodes) = self._find_info() - if not indexer_id or season is None or not episodes: + if not indexer_id or season == None or not episodes: self._log(u"Can't find show id from ANY of the indexers or season or episode, skipping", logger.WARNING) return False diff --git a/sickbeard/processTV.py b/sickbeard/processTV.py index 6d91bff4..69840830 100644 --- a/sickbeard/processTV.py +++ b/sickbeard/processTV.py @@ -345,11 +345,11 @@ def delete_files(processPath, notwantedFiles): try: ek.ek(os.chmod,cur_file_path,stat.S_IWRITE) except OSError, e: - returnStr += logHelper(u"Cannot change permissions of " + cur_file_path + ': ' + str(e.strerror), logger.DEBUG) + returnStr += logHelper(u"Cannot change permissions of " + cur_file_path + ': ' + e.strerror, logger.DEBUG) try: ek.ek(os.remove, cur_file_path) except OSError, e: - returnStr += logHelper(u"Unable to delete file " + cur_file + ': ' + str(e.strerror), logger.DEBUG) + returnStr += logHelper(u"Unable to delete file " + cur_file + ': ' + e.strerror, logger.DEBUG) def delete_dir(processPath): diff --git a/sickbeard/properFinder.py b/sickbeard/properFinder.py index 9d302aba..f9d1f3fb 100644 --- a/sickbeard/properFinder.py +++ b/sickbeard/properFinder.py @@ -118,7 +118,7 @@ class ProperFinder(): curProper.season = -1 curProper.episode = parse_result.air_date else: - curProper.season = parse_result.season_number if parse_result.season_number is not None else 1 + curProper.season = parse_result.season_number if parse_result.season_number != None else 1 curProper.episode = parse_result.episode_numbers[0] curProper.quality = Quality.nameQuality(curProper.name) @@ -236,7 +236,7 @@ class ProperFinder(): # get the episode object showObj = helpers.findCertainShow(sickbeard.showList, curProper.indexerid) - if showObj is None: + if showObj == None: logger.log(u"Unable to find the show with indexerid " + str(curProper.indexerid) + " so unable to download the proper", logger.ERROR) continue epObj = showObj.getEpisode(curProper.season, curProper.episode) diff --git a/sickbeard/providers/btn.py b/sickbeard/providers/btn.py index 3111d79d..20f6f624 100644 --- a/sickbeard/providers/btn.py +++ b/sickbeard/providers/btn.py @@ -128,9 +128,8 @@ class BTNProvider(generic.TorrentProvider): return [] - def _api_call(self, apikey, params=None, results_per_page=1000, offset=0): + def _api_call(self, apikey, params={}, results_per_page=1000, offset=0): - if not params: params = {} server = jsonrpclib.Server('http://api.btnapps.net') parsedJSON = {} diff --git a/sickbeard/providers/generic.py b/sickbeard/providers/generic.py index 994fab7e..127e7376 100644 --- a/sickbeard/providers/generic.py +++ b/sickbeard/providers/generic.py @@ -125,7 +125,7 @@ class GenericProvider: data = self.getURL(result.url) - if data is None: + if data == None: return False # use the appropriate watch folder @@ -323,8 +323,7 @@ class GenericProvider: if not show.air_by_date: # this check is meaningless for non-season searches - if (parse_result.season_number is not None and parse_result.season_number != season) or ( - parse_result.season_number is None and season != 1): + if (parse_result.season_number != None and parse_result.season_number != season) or (parse_result.season_number == None and season != 1): logger.log(u"The result " + title + " doesn't seem to be a valid episode for season " + str(season) + ", ignoring", logger.DEBUG) continue diff --git a/sickbeard/providers/kat.py b/sickbeard/providers/kat.py index 730691e9..3365b34c 100644 --- a/sickbeard/providers/kat.py +++ b/sickbeard/providers/kat.py @@ -134,7 +134,7 @@ class KATProvider(generic.TorrentProvider): quality = Quality.sceneQuality(os.path.basename(fileName)) if quality != Quality.UNKNOWN: break - if fileName is not None and quality == Quality.UNKNOWN: + if fileName!=None and quality == Quality.UNKNOWN: quality = Quality.assumeQuality(os.path.basename(fileName)) if quality == Quality.UNKNOWN: diff --git a/sickbeard/providers/nzbs_org_old.py b/sickbeard/providers/nzbs_org_old.py index 20bd1395..33db0b65 100644 --- a/sickbeard/providers/nzbs_org_old.py +++ b/sickbeard/providers/nzbs_org_old.py @@ -81,7 +81,7 @@ class NZBsProvider(generic.NZBProvider): # Pause to avoid 503's time.sleep(5) - if data is None: + if data == None: return [] try: @@ -126,7 +126,7 @@ class NZBsProvider(generic.NZBProvider): resultDate = datetime.datetime.strptime(match.group(1), "%a, %d %b %Y %H:%M:%S") - if date is None or resultDate > date: + if date == None or resultDate > date: results.append(classes.Proper(title, url, resultDate)) return results diff --git a/sickbeard/providers/rsstorrent.py b/sickbeard/providers/rsstorrent.py index 80f160e4..3cb1f2f5 100644 --- a/sickbeard/providers/rsstorrent.py +++ b/sickbeard/providers/rsstorrent.py @@ -33,7 +33,7 @@ from sickbeard.exceptions import ex from lib import requests from bs4 import BeautifulSoup -from lib import bencode +from lib.bencode import bdecode class TorrentRssProvider(generic.TorrentProvider): @@ -116,7 +116,7 @@ class TorrentRssProvider(generic.TorrentProvider): torrent_file = self.getURL(url) try: - bencode.bdecode(torrent_file) + bdecode(torrent_file) except Exception, e: self.dumpHTML(torrent_file) return (False, 'Torrent link is not a valid torrent file: ' + ex(e)) diff --git a/sickbeard/providers/thepiratebay.py b/sickbeard/providers/thepiratebay.py index 50e4011a..4b8a3bbd 100644 --- a/sickbeard/providers/thepiratebay.py +++ b/sickbeard/providers/thepiratebay.py @@ -144,7 +144,7 @@ class ThePirateBayProvider(generic.TorrentProvider): quality = Quality.sceneQuality(os.path.basename(fileName)) if quality != Quality.UNKNOWN: break - if fileName is not None and quality == Quality.UNKNOWN: + if fileName!=None and quality == Quality.UNKNOWN: quality = Quality.assumeQuality(os.path.basename(fileName)) if quality == Quality.UNKNOWN: @@ -254,7 +254,7 @@ class ThePirateBayProvider(generic.TorrentProvider): continue #Accept Torrent only from Good People for every Episode Search - if sickbeard.THEPIRATEBAY_TRUSTED and re.search('(VIP|Trusted|Helper)',torrent.group(0)) is None: + if sickbeard.THEPIRATEBAY_TRUSTED and re.search('(VIP|Trusted|Helper)',torrent.group(0))== None: logger.log(u"ThePirateBay Provider found result " + torrent.group('title') + " but that doesn't seem like a trusted result so I'm ignoring it", logger.DEBUG) continue diff --git a/sickbeard/sab.py b/sickbeard/sab.py index 54044b02..dbb692a1 100644 --- a/sickbeard/sab.py +++ b/sickbeard/sab.py @@ -43,13 +43,13 @@ def sendNZB(nzb): # set up a dict with the URL params in it params = {} - if sickbeard.SAB_USERNAME is not None: + if sickbeard.SAB_USERNAME != None: params['ma_username'] = sickbeard.SAB_USERNAME - if sickbeard.SAB_PASSWORD is not None: + if sickbeard.SAB_PASSWORD != None: params['ma_password'] = sickbeard.SAB_PASSWORD - if sickbeard.SAB_APIKEY is not None: + if sickbeard.SAB_APIKEY != None: params['apikey'] = sickbeard.SAB_APIKEY - if sickbeard.SAB_CATEGORY is not None: + if sickbeard.SAB_CATEGORY != None: params['cat'] = sickbeard.SAB_CATEGORY # use high priority if specified (recently aired episode) @@ -105,7 +105,7 @@ def sendNZB(nzb): return False # this means we couldn't open the connection or something just as bad - if f is None: + if f == None: logger.log(u"No data returned from SABnzbd, NZB not sent", logger.ERROR) return False @@ -173,7 +173,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 is None: + if f == None: logger.log(u"No data returned from SABnzbd", logger.ERROR) return False, "No data returned from SABnzbd" else: diff --git a/sickbeard/scheduler.py b/sickbeard/scheduler.py index c5964819..af9e9924 100644 --- a/sickbeard/scheduler.py +++ b/sickbeard/scheduler.py @@ -45,7 +45,7 @@ class Scheduler: self.abort = False def initThread(self): - if self.thread is None or not self.thread.isAlive(): + if self.thread == None or not self.thread.isAlive(): self.thread = threading.Thread(None, self.runAction, self.threadName) def timeLeft(self): diff --git a/sickbeard/search.py b/sickbeard/search.py index 02672a5f..b48a1bce 100644 --- a/sickbeard/search.py +++ b/sickbeard/search.py @@ -53,7 +53,7 @@ def _downloadResult(result): newResult = False - if resProvider is None: + if resProvider == None: logger.log(u"Invalid provider name - this is a coding error, report it please", logger.ERROR) return False @@ -143,7 +143,7 @@ def snatchEpisode(result, endStatus=SNATCHED): logger.log(u"Unknown result type, unable to download it", logger.ERROR) dlResult = False - if not dlResult: + if dlResult == False: return False if sickbeard.USE_FAILED_DOWNLOADS: @@ -244,7 +244,7 @@ def pickBestResult(results, quality_list=None): logger.log(cur_result.name + u" has previously failed, rejecting it") continue - if not bestResult or bestResult.quality < cur_result.quality != Quality.UNKNOWN: + if not bestResult or bestResult.quality < cur_result.quality and cur_result.quality != Quality.UNKNOWN: bestResult = cur_result elif bestResult.quality == cur_result.quality: if "proper" in cur_result.name.lower() or "repack" in cur_result.name.lower(): diff --git a/sickbeard/searchBacklog.py b/sickbeard/searchBacklog.py index d3ddc141..f63d64ad 100644 --- a/sickbeard/searchBacklog.py +++ b/sickbeard/searchBacklog.py @@ -75,7 +75,7 @@ class BacklogSearcher: else: show_list = sickbeard.showList - if self.amActive: + if self.amActive == True: logger.log(u"Backlog is still running, not starting it again", logger.DEBUG) return @@ -147,7 +147,7 @@ class BacklogSearcher: if len(sqlResults) == 0: lastBacklog = 1 - elif sqlResults[0]["last_backlog"] is None or sqlResults[0]["last_backlog"] == "": + elif sqlResults[0]["last_backlog"] == None or sqlResults[0]["last_backlog"] == "": lastBacklog = 1 else: lastBacklog = int(sqlResults[0]["last_backlog"]) diff --git a/sickbeard/search_queue.py b/sickbeard/search_queue.py index 8a9aa225..eede681d 100644 --- a/sickbeard/search_queue.py +++ b/sickbeard/search_queue.py @@ -110,14 +110,14 @@ class ManualSearchQueueItem(generic_queue.QueueItem): providerModule = foundEpisode.provider if not result: ui.notifications.error('Error while attempting to snatch ' + foundEpisode.name+', check your logs') - elif providerModule is None: + elif providerModule == None: ui.notifications.error('Provider is configured incorrectly, unable to download') self.success = result def finish(self): # don't let this linger if something goes wrong - if self.success is None: + if self.success == None: self.success = False generic_queue.QueueItem.finish(self) @@ -160,7 +160,7 @@ class RSSSearchQueueItem(generic_queue.QueueItem): logger.log(u"ERROR: expected to find a single show matching " + sqlEp["showid"]) return None - if show is None: + if show == None: logger.log(u"Unable to find the show with ID " + str(sqlEp["showid"]) + " in your show list! DB value was " + str(sqlEp), logger.ERROR) return None diff --git a/sickbeard/showUpdater.py b/sickbeard/showUpdater.py index d5cb40fa..46b4d0a3 100644 --- a/sickbeard/showUpdater.py +++ b/sickbeard/showUpdater.py @@ -48,7 +48,7 @@ class ShowUpdater(): hour_diff = update_datetime.time().hour - run_updater_time.hour # if it's less than an interval after the update time then do an update (or if we're forcing it) - if 0 <= hour_diff < self.updateInterval.seconds / 3600 or force: + if hour_diff >= 0 and hour_diff < self.updateInterval.seconds / 3600 or force: logger.log(u"Doing full update on all shows") else: return diff --git a/sickbeard/show_name_helpers.py b/sickbeard/show_name_helpers.py index d7f2d443..32864d73 100644 --- a/sickbeard/show_name_helpers.py +++ b/sickbeard/show_name_helpers.py @@ -194,7 +194,12 @@ def isGoodResult(name, show, log=True): escaped_name = re.sub('\\\\[\\s.-]', '\W+', re.escape(curName)) if show.startyear: escaped_name += "(?:\W+" + str(show.startyear) + ")?" - curRegex = '^' + escaped_name + '\W+(?:(?:S\d[\dE._ -])|(?:\d\d?x)|(?:\d{4}\W\d\d\W\d\d)|(?:(?:part|pt)[\._ -]?(\d|[ivx]))|Season\W+\d+\W+|E\d+\W+|(?:\d{1,3}.+\d{1,}[a-zA-Z]{2}\W+[a-zA-Z]{3,}\W+\d{4}.+))' + curRegex = '^' + escaped_name + '\W+(?:(?:S\d[\dE._ -])|' \ + '(?:\d\d?x)|' \ + '(?:\d{4}\W\d\d\W\d\d)|' \ + '(?:(?:part|pt)[\._ -]?(\d|[ivx]))|' \ + 'Season\W+\d+\W+|E\d+\W+)|' \ + '((.+)[. _-]+)(\d{1,2}[a-zA-Z]{2})[. _-]+([a-zA-Z]{3,})[. _-]+(\d{4})*(.+)([. _-])()((([^- ]+))?)?$' if log: logger.log(u"Checking if show " + name + " matches " + curRegex, logger.DEBUG) diff --git a/sickbeard/show_queue.py b/sickbeard/show_queue.py index 779ca557..c40b79ec 100644 --- a/sickbeard/show_queue.py +++ b/sickbeard/show_queue.py @@ -44,7 +44,7 @@ class ShowQueue(generic_queue.GenericQueue): return show in [x.show for x in self.queue if x.action_id in actions] def _isBeingSomethinged(self, show, actions): - return self.currentItem is not None and show == self.currentItem.show and \ + return self.currentItem != None and show == self.currentItem.show and \ self.currentItem.action_id in actions def isInUpdateQueue(self, show): @@ -75,7 +75,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 is not None and x.isLoading] + return [x for x in self.queue + [self.currentItem] if x != None and x.isLoading] loadingShowList = property(_getLoadingShowList) @@ -205,7 +205,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 is None: + if self.show == None: return self.showDir return self.show.name @@ -216,7 +216,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 is None: + if self.show == None: return True return False @@ -269,9 +269,9 @@ class QueueItemAdd(ShowQueueItem): # set up initial values self.show.location = self.showDir - self.show.subtitles = self.subtitles if self.subtitles is not None else sickbeard.SUBTITLES_DEFAULT + self.show.subtitles = self.subtitles if self.subtitles != 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 is not None else sickbeard.FLATTEN_FOLDERS_DEFAULT + self.show.flatten_folders = self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT self.show.paused = False # be smartish about this @@ -354,7 +354,7 @@ class QueueItemAdd(ShowQueueItem): self.finish() def _finishEarly(self): - if self.show is not None: + if self.show != None: self.show.deleteShow() self.finish() @@ -483,7 +483,7 @@ class QueueItemUpdate(ShowQueueItem): logger.log(u"Unable to get info from " + self.show.indexer + ", the show info will not be refreshed: " + ex(e), logger.ERROR) IndexerEpList = None - if IndexerEpList is None: + if IndexerEpList == None: logger.log(u"No data returned from " + self.show.indexer + ", unable to update this show", logger.ERROR) else: diff --git a/sickbeard/subtitles.py b/sickbeard/subtitles.py index fcdd3d4c..e4b0bfd5 100644 --- a/sickbeard/subtitles.py +++ b/sickbeard/subtitles.py @@ -112,7 +112,7 @@ class SubtitlesFinder(): return rules = self._getRules() - now = datetime.datetime.now() + now = datetime.datetime.now(); for epToSub in sqlResults: if not ek.ek(os.path.isfile, epToSub['location']): logger.log('Episode file does not exist, cannot download subtitles for episode %dx%d of show %s' % (epToSub['season'], epToSub['episode'], epToSub['show_name']), logger.DEBUG) diff --git a/sickbeard/traktWatchListChecker.py b/sickbeard/traktWatchListChecker.py index eda53b61..26f1a3e8 100644 --- a/sickbeard/traktWatchListChecker.py +++ b/sickbeard/traktWatchListChecker.py @@ -86,7 +86,7 @@ class TraktChecker(): Adds a new show with the default settings """ showObj = helpers.findCertainShow(sickbeard.showList, int(indexerid)) - if showObj is not None: + if showObj != None: return logger.log(u"Adding show " + indexerid) root_dirs = sickbeard.ROOT_DIRS.split('|') @@ -106,7 +106,7 @@ class TraktChecker(): Sets an episode to wanted, only is it is currently skipped """ epObj = show.getEpisode(int(s), int(e)) - if epObj is None: + if epObj == None: return with epObj.lock: if epObj.status != SKIPPED: diff --git a/sickbeard/tv.py b/sickbeard/tv.py index a516de4f..a50917e6 100644 --- a/sickbeard/tv.py +++ b/sickbeard/tv.py @@ -88,7 +88,7 @@ class TVShow(object): self.episodes = {} otherShow = helpers.findCertainShow(sickbeard.showList, self.indexerid) - if otherShow is not None: + if otherShow != None: raise exceptions.MultipleShowObjectsException("Can't create a show if it already exists") self.loadFromDB() @@ -132,7 +132,7 @@ class TVShow(object): sql_selection = "SELECT season, episode, " # subselection to detect multi-episodes early, share_location > 0 - sql_selection += " (SELECT COUNT (*) FROM tv_episodes WHERE showid = tve.showid AND season = tve.season AND location != '' AND location = tve.location AND episode != tve.episode) AS share_location " + sql_selection = sql_selection + " (SELECT COUNT (*) FROM tv_episodes WHERE showid = tve.showid AND season = tve.season AND location != '' AND location = tve.location AND episode != tve.episode) AS share_location " sql_selection = sql_selection + " FROM tv_episodes tve WHERE showid = " + str(self.indexerid) @@ -152,10 +152,10 @@ class TVShow(object): sql_selection = sql_selection + " AND airdate >= " + str(min_date.toordinal()) + " AND airdate <= " + str(max_date.toordinal()) if has_location: - sql_selection += " AND location != '' " + sql_selection = sql_selection + " AND location != '' " # need ORDER episode ASC to rename multi-episodes in order S01E01-02 - sql_selection += " ORDER BY season ASC, episode ASC" + sql_selection = sql_selection + " ORDER BY season ASC, episode ASC" results = myDB.select(sql_selection) @@ -186,18 +186,18 @@ class TVShow(object): ep = None - if not episode in self.episodes[season] or self.episodes[season][episode] is None: + if not episode in self.episodes[season] or self.episodes[season][episode] == None: if noCreate: return None logger.log(str(self.indexerid) + u": An object for episode " + str(season) + "x" + str(episode) + " didn't exist in the cache, trying to create it", logger.DEBUG) - if file is not None: + if file != None: ep = TVEpisode(self, season, episode, file) else: ep = TVEpisode(self, season, episode) - if ep is not None: + if ep != None: self.episodes[season][episode] = ep return self.episodes[season][episode] @@ -221,7 +221,7 @@ class TVShow(object): if sql_result: last_airdate = datetime.date.fromordinal(sql_result[0]['airdate']) - if (update_date - graceperiod) <= last_airdate <= (update_date + graceperiod): + if last_airdate >= (update_date - graceperiod) and last_airdate <= (update_date + graceperiod): return True # get next upcoming UNAIRED episode to compare against today + graceperiod @@ -329,7 +329,7 @@ class TVShow(object): curEpisode.release_name = ep_file_name # store the reference in the show - if curEpisode is not None: + if curEpisode != None: if self.subtitles: try: curEpisode.refreshSubtitles() @@ -382,7 +382,7 @@ class TVShow(object): try: curEp = self.getEpisode(curSeason, curEpisode) - # if we found out that the ep is no longer on Indexers then delete it from our database too + # if we found out that the ep is no longer on TVDB then delete it from our database too if deleteEp: curEp.deleteEpisode() @@ -498,7 +498,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 is not None else 1 + season = parse_result.season_number if parse_result.season_number != None else 1 episodes = parse_result.episode_numbers rootEp = None @@ -535,7 +535,7 @@ class TVShow(object): same_file = False curEp = self.getEpisode(season, episode) - if curEp is None: + if curEp == None: try: curEp = self.getEpisode(season, episode, file) except exceptions.EpisodeNotFoundException: @@ -559,7 +559,7 @@ class TVShow(object): curEp.checkForMetaFiles() - if rootEp is None: + if rootEp == None: rootEp = curEp else: if curEp not in rootEp.relatedEps: @@ -600,7 +600,7 @@ class TVShow(object): elif oldStatus not in (SNATCHED, SNATCHED_PROPER): newStatus = DOWNLOADED - if newStatus is not None: + if newStatus != None: with curEp.lock: logger.log(u"STATUS: we have an associated file, so setting the status from " + str(curEp.status) + u" to DOWNLOADED/" + str(Quality.statusFromName(file)), logger.DEBUG) curEp.status = Quality.compositeStatus(newStatus, newQuality) @@ -817,7 +817,7 @@ class TVShow(object): params = [self.indexerid, datetime.date.today().toordinal()] + innerParams + [UNAIRED] sqlResults = myDB.select(query, params) - if sqlResults is None or len(sqlResults) == 0: + if sqlResults == None or len(sqlResults) == 0: logger.log(str(self.indexerid) + u": No episode found... need to implement show status", logger.DEBUG) return [] else: @@ -1046,7 +1046,7 @@ 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 is None: + elif maxBestQuality == None: return Overview.GOOD # if they have one but it's not the best they want then mark it as qual elif curQuality < maxBestQuality: @@ -1236,14 +1236,14 @@ class TVEpisode(object): pass # if we tried loading it from NFO and didn't find the NFO, try the Indexers - if not self.hasnfo: + if self.hasnfo == False: try: result = self.loadFromIndexer(season, episode) except exceptions.EpisodeDeletedException: result = False # if we failed SQL *and* NFO, Indexers then fail - if not result: + if result == False: raise exceptions.EpisodeNotFoundException("Couldn't find episode " + str(season) + "x" + str(episode)) def loadFromDB(self, season, episode): @@ -1346,7 +1346,7 @@ class TVEpisode(object): if getattr(myEp, 'episodename', None) is None: logger.log(u"This episode (" + self.show.name + " - " + str(season) + "x" + str(episode) + ") has no name on " + self.indexer + "") - # if I'm incomplete on Indexers but I once was complete then just delete myself from the DB for now + # if I'm incomplete on TVDB but I once was complete then just delete myself from the DB for now if self.indexerid != -1: self.deleteEpisode() return False @@ -1367,7 +1367,7 @@ class TVEpisode(object): self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2]) except ValueError: logger.log(u"Malformed air date retrieved from " + self.indexer + " ("+self.show.name+" - "+str(season)+"x"+str(episode)+")", logger.ERROR) - # if I'm incomplete on Indexers but I once was complete then just delete myself from the DB for now + # if I'm incomplete on TVDB but I once was complete then just delete myself from the DB for now if self.indexerid != -1: self.deleteEpisode() return False @@ -1607,7 +1607,7 @@ class TVEpisode(object): myDB.upsert("tv_episodes", newValueDict, controlValueDict) def fullPath(self): - if self.location is None or self.location == "": + if self.location == None or self.location == "": return None else: return ek.ek(os.path.join, self.show.location, self.location) @@ -1648,7 +1648,7 @@ class TVEpisode(object): singleName = False break - if curGoodName is None: + if curGoodName == None: curGoodName = match.group(1) elif curGoodName != match.group(1): singleName = False @@ -1754,10 +1754,10 @@ class TVEpisode(object): Manipulates an episode naming pattern and then fills the template in """ - if pattern is None: + if pattern == None: pattern = sickbeard.NAMING_PATTERN - if multi is None: + if multi == None: multi = sickbeard.NAMING_MULTI_EP replace_map = self._replace_map() @@ -1892,7 +1892,7 @@ class TVEpisode(object): Just the folder name of the episode """ - if pattern is None: + if pattern == 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 @@ -1912,7 +1912,7 @@ class TVEpisode(object): Just the filename of the episode, formatted based on the naming settings """ - if pattern is None: + if pattern == 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 @@ -1967,17 +1967,17 @@ class TVEpisode(object): # move related files for cur_related_file in related_files: cur_result = helpers.rename_ep_file(cur_related_file, absolute_proper_path, absolute_current_path_no_ext_length) - if not cur_result: + if cur_result == False: logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_file, logger.ERROR) for cur_related_sub in related_subs: cur_result = helpers.rename_ep_file(cur_related_sub, absolute_proper_subs_path, absolute_current_path_no_ext_length) - if not cur_result: + if cur_result == False: logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_sub, logger.ERROR) # save the ep with self.lock: - if result: + if result != False: self.location = absolute_proper_path + file_ext for relEp in self.relatedEps: relEp.location = absolute_proper_path + file_ext diff --git a/sickbeard/tvcache.py b/sickbeard/tvcache.py index c6b99476..5652c9c8 100644 --- a/sickbeard/tvcache.py +++ b/sickbeard/tvcache.py @@ -195,16 +195,14 @@ class TVCache(): def shouldUpdate(self): # if we've updated recently then skip the update - if datetime.datetime.today() - self.lastUpdate < datetime.timedelta(minutes=self.minTime): logger.log(u"Last update was too soon, using old cache: today()-" + str(self.lastUpdate) + "<" + str(datetime.timedelta(minutes=self.minTime)), logger.DEBUG) return False return True - def _addCacheEntry(self, name, url, season=None, episodes=None, indexer_id=0, quality=None, extraNames=None): + def _addCacheEntry(self, name, url, season=None, episodes=None, indexer_id=0, quality=None, extraNames=[]): - if not extraNames: extraNames = [] myDB = self._getDB() parse_result = None @@ -248,7 +246,7 @@ class TVCache(): indexer_id = name_cache.retrieveNameFromCache(parse_result.series_name) # remember if the cache lookup worked or not so we know whether we should bother updating it later - if indexer_id is None: + if indexer_id == None: logger.log(u"No cache results returned, continuing on with the search", logger.DEBUG) from_cache = False else: @@ -256,7 +254,7 @@ class TVCache(): from_cache = True # if the cache failed, try looking up the show name in the database - if indexer_id is None: + if indexer_id == None: logger.log(u"Trying to look the show up in the show database", logger.DEBUG) showResult = helpers.searchDBForShow(parse_result.series_name) if showResult: @@ -264,7 +262,7 @@ class TVCache(): indexer_id = showResult[1] # if the DB lookup fails then do a comprehensive regex search - if indexer_id is None: + if indexer_id == None: logger.log(u"Couldn't figure out a show name straight from the DB, trying a regex search instead", logger.DEBUG) for curShow in sickbeard.showList: if show_name_helpers.isGoodResult(name, curShow, False): @@ -278,7 +276,7 @@ class TVCache(): name_cache.addNameToCache(parse_result.series_name, indexer_id) # if we came out with indexer_id = None it means we couldn't figure it out at all, just use 0 for that - if indexer_id is None: + if indexer_id == None: indexer_id = 0 # if we found the show then retrieve the show object @@ -293,7 +291,7 @@ class TVCache(): # if we weren't provided with season/episode information then get it from the name that we parsed if not season: - season = parse_result.season_number if parse_result.season_number is not None else 1 + season = parse_result.season_number if parse_result.season_number != None else 1 if not episodes: episodes = parse_result.episode_numbers @@ -302,7 +300,7 @@ class TVCache(): try: lINDEXER_API_PARMS = {'indexer': self.indexer} - if not (indexer_lang == "" or indexer_lang == "en" or indexer_lang is None): + if not (indexer_lang == "" or indexer_lang == "en" or indexer_lang == None): lINDEXER_API_PARMS['language'] = indexer_lang t = indexer_api.indexerApi(**lINDEXER_API_PARMS) @@ -342,7 +340,7 @@ class TVCache(): sql = "SELECT * FROM [" + self.providerID + "] WHERE name LIKE '%.PROPER.%' OR name LIKE '%.REPACK.%'" - if date is not None: + if date != None: sql += " AND time >= " + str(int(time.mktime(date.timetuple()))) #return filter(lambda x: x['indexerid'] != 0, myDB.select(sql)) diff --git a/sickbeard/ui.py b/sickbeard/ui.py index 4b439b86..b8e1b3d3 100644 --- a/sickbeard/ui.py +++ b/sickbeard/ui.py @@ -112,8 +112,7 @@ class Notification(object): class ProgressIndicator(): - def __init__(self, percentComplete=0, currentStatus=None): - if not currentStatus: currentStatus = {'title': ''} + def __init__(self, percentComplete=0, currentStatus={'title': ''}): self.percentComplete = percentComplete self.currentStatus = currentStatus @@ -130,7 +129,7 @@ class ProgressIndicators(): # if any of the progress indicators are done take them off the list for curPI in ProgressIndicators._pi[name]: - if curPI is not None and curPI.percentComplete() == 100: + if curPI != 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 1c9eb398..a60ca71f 100644 --- a/sickbeard/versionChecker.py +++ b/sickbeard/versionChecker.py @@ -511,6 +511,9 @@ class GitUpdateManager(UpdateManager): else: return False + return False + + class SourceUpdateManager(UpdateManager): def __init__(self): diff --git a/sickbeard/webapi.py b/sickbeard/webapi.py index 3518b4b1..683821fa 100644 --- a/sickbeard/webapi.py +++ b/sickbeard/webapi.py @@ -91,7 +91,7 @@ class Api: logger.log(accessMsg, logger.DEBUG) else: logger.log(accessMsg, logger.WARNING) - return outputCallbackDict['default'](_responds(RESULT_DENIED, msg=str(accessMsg))) + return outputCallbackDict['default'](_responds(RESULT_DENIED, msg=accessMsg)) # set the original call_dispatcher as the local _call_dispatcher _call_dispatcher = call_dispatcher @@ -171,7 +171,7 @@ class Api: try: out = json.dumps(dict, indent=self.intent, sort_keys=True) callback = request.params.get('callback') or request.params.get('jsonp') - if callback is not None: + if callback != None: 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) @@ -189,7 +189,7 @@ class Api: else: del kwargs["apikey"] - if not sickbeard.USE_API: + if sickbeard.USE_API != True: msg = u"API :: " + remoteIp + " - SB API Disabled. ACCESS DENIED" return False, msg, args, kwargs elif apiKey == realKey: @@ -223,7 +223,7 @@ def call_dispatcher(args, kwargs): del kwargs["cmd"] outDict = {} - if cmds is not None: + if cmds != None: cmds = cmds.split("|") multiCmds = bool(len(cmds) > 1) for cmd in cmds: @@ -758,14 +758,14 @@ class CMD_ComingEpisodes(ApiCall): status = "missed" elif ep["airdate"] >= next_week: status = "later" - elif today <= ep["airdate"] < next_week: + elif ep["airdate"] >= today and ep["airdate"] < next_week: if ep["airdate"] == today: status = "today" else: status = "soon" # skip unwanted - if self.type is not None and not status in self.type: + if self.type != None and not status in self.type: continue ordinalAirdate = int(ep["airdate"]) @@ -878,7 +878,7 @@ class CMD_EpisodeSearch(ApiCall): 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 is None: #@UndefinedVariable + while ep_queue_item.success == None: #@UndefinedVariable time.sleep(1) # return the correct json value @@ -930,7 +930,7 @@ class CMD_EpisodeSetStatus(ApiCall): ep_list = [] if self.e: epObj = showObj.getEpisode(self.s, self.e) - if epObj is None: + if epObj == None: return _responds(RESULT_FAILURE, msg="Episode not found") ep_list = [epObj] else: @@ -945,7 +945,7 @@ class CMD_EpisodeSetStatus(ApiCall): start_backlog = False ep_segment = None for epObj in ep_list: - if ep_segment is None and self.status == WANTED: + if ep_segment == None and self.status == WANTED: # figure out what segment the episode is in and remember it so we can backlog it if showObj.air_by_date: ep_segment = str(epObj.airdate)[:7] @@ -955,7 +955,7 @@ class CMD_EpisodeSetStatus(ApiCall): with epObj.lock: # don't let them mess up UNAIRED episodes if epObj.status == UNAIRED: - if self.e is not 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 + 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 ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is UNAIRED")) failure = True continue @@ -1051,7 +1051,7 @@ class CMD_Exceptions(ApiCall): """ display scene exceptions for all or a given show """ myDB = db.DBConnection("cache.db", row_type="dict") - if self.indexerid is None: + if self.indexerid == None: sqlResults = myDB.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions") scene_exceptions = {} for row in sqlResults: @@ -1455,7 +1455,7 @@ class CMD_SickBeardPauseBacklog(ApiCall): def run(self): """ pause the backlog search """ - if self.pause: + if self.pause == True: sickbeard.searchQueueScheduler.action.pause_backlog() #@UndefinedVariable return _responds(RESULT_SUCCESS, msg="Backlog paused") else: @@ -1637,10 +1637,10 @@ class CMD_SickBeardSetDefaults(ApiCall): raise ApiError("Status Prohibited") sickbeard.STATUS_DEFAULT = self.status - if self.flatten_folders is not None: + if self.flatten_folders != None: sickbeard.FLATTEN_FOLDERS_DEFAULT = int(self.flatten_folders) - if self.future_show_paused is not None: + if self.future_show_paused != None: sickbeard.COMING_EPS_DISPLAY_PAUSED = int(self.future_show_paused) return _responds(RESULT_SUCCESS, msg="Saved defaults") @@ -2064,13 +2064,16 @@ class CMD_ShowPause(ApiCall): if not showObj: return _responds(RESULT_FAILURE, msg="Show not found") - if self.pause: + if self.pause == True: showObj.paused = 1 return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been paused") else: showObj.paused = 0 return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been unpaused") + return _responds(RESULT_FAILURE, msg=str(showObj.name) + " was unable to be paused") + + class CMD_ShowRefresh(ApiCall): _help = {"desc": "refresh a show in sickbeard", "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, @@ -2157,7 +2160,7 @@ class CMD_ShowSeasons(ApiCall): myDB = db.DBConnection(row_type="dict") - if self.season is None: + if self.season == None: sqlResults = myDB.select("SELECT name, episode, airdate, status, season FROM tv_episodes WHERE showid = ?", [self.indexerid]) seasons = {} for row in sqlResults: @@ -2405,7 +2408,7 @@ class CMD_Shows(ApiCall): if (len(nextEps) != 0): nextAirdate = _ordinal_to_dateForm(nextEps[0].airdate.toordinal()) - if self.paused is not None and bool(self.paused) != bool(curShow.paused): + if self.paused != None and bool(self.paused) != bool(curShow.paused): continue showDict = {"paused": curShow.paused, diff --git a/sickbeard/webserve.py b/sickbeard/webserve.py index f36f6bd9..36af98e7 100644 --- a/sickbeard/webserve.py +++ b/sickbeard/webserve.py @@ -154,17 +154,17 @@ def _genericMessage(subject, message): def _getEpisode(show, season, episode): - if show is None or season is None or episode is None: + if show == None or season == None or episode == None: return "Invalid parameters" showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return "Show not in show list" epObj = showObj.getEpisode(int(season), int(episode)) - if epObj is None: + if epObj == None: return "Episode couldn't be retrieved" return epObj @@ -177,7 +177,7 @@ def ManageMenu(): { 'title': 'Episode Status Management', 'path': 'manage/episodeStatuses/' },] if sickbeard.USE_TORRENTS and sickbeard.TORRENT_METHOD != 'blackhole' \ - and (sickbeard.ENABLE_HTTPS and sickbeard.TORRENT_HOST[:5] == 'https' + and (sickbeard.ENABLE_HTTPS and sickbeard.TORRENT_HOST[:5] == 'https' \ or not sickbeard.ENABLE_HTTPS and sickbeard.TORRENT_HOST[:5] == 'http:'): manageMenu.append({ 'title': 'Manage Torrents', 'path': 'manage/manageTorrents/'}) @@ -438,7 +438,7 @@ class Manage: to_download[cur_indexer_id] = [str(x["season"]) + 'x' + str(x["episode"]) for x in all_eps_results] for epResult in to_download[cur_indexer_id]: - season, episode = epResult.split('x') + season, episode = epResult.split('x'); show = sickbeard.helpers.findCertainShow(sickbeard.showList, int(cur_indexer_id)) subtitles = show.getEpisode(int(season), int(episode)).downloadSubtitles() @@ -569,10 +569,9 @@ class Manage: return _munge(t) @cherrypy.expose - def massEditSubmit(self, paused=None, flatten_folders=None, quality_preset=False, subtitles=None, anyQualities=[], - bestQualities=None, toEdit=None, *args, **kwargs): + def massEditSubmit(self, paused=None, flatten_folders=None, quality_preset=False, subtitles=None, + anyQualities=[], bestQualities=[], toEdit=None, *args, **kwargs): - if not bestQualities: bestQualities = [] dir_map = {} for cur_arg in kwargs: if not cur_arg.startswith('orig_root_dir_'): @@ -636,32 +635,32 @@ class Manage: @cherrypy.expose def massUpdate(self, toUpdate=None, toRefresh=None, toRename=None, toDelete=None, toMetadata=None, toSubtitle=None): - if toUpdate is not None: + if toUpdate != None: toUpdate = toUpdate.split('|') else: toUpdate = [] - if toRefresh is not None: + if toRefresh != None: toRefresh = toRefresh.split('|') else: toRefresh = [] - if toRename is not None: + if toRename != None: toRename = toRename.split('|') else: toRename = [] - if toSubtitle is not None: + if toSubtitle != None: toSubtitle = toSubtitle.split('|') else: toSubtitle = [] - if toDelete is not None: + if toDelete != None: toDelete = toDelete.split('|') else: toDelete = [] - if toMetadata is not None: + if toMetadata != None: toMetadata = toMetadata.split('|') else: toMetadata = [] @@ -679,7 +678,7 @@ class Manage: showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(curShowID)) - if showObj is None: + if showObj == None: continue if curShowID in toDelete: @@ -762,7 +761,7 @@ class Manage: t.webui_url = '/'.join(s.strip('/') for s in (t.webui_url, 'gui/')) if sickbeard.TORRENT_METHOD == 'download_station': if helpers.check_url(t.webui_url + 'download/'): - t.webui_url += 'download/' + t.webui_url = t.webui_url + 'download/' else: t.info_download_station = '

    To have a better experience please set the Download Station alias as download, you can check this setting in the Synology DSM Control Panel > Application Portal. Make sure you allow DSM to be embedded with iFrames too in Control Panel > DSM Settings > Security.


    There is more information about this available here.


    ' @@ -778,7 +777,7 @@ class Manage: else: sqlResults = myDB.select("SELECT * FROM failed LIMIT ?", [limit]) - toRemove = toRemove.split("|") if toRemove is not None else [] + toRemove = toRemove.split("|") if toRemove != None else [] for release in toRemove: myDB.action('DELETE FROM failed WHERE release = ?', [release]) @@ -811,9 +810,9 @@ class History: for sql_result in sqlResults: - if not any((history['show_id'] == sql_result['showid'] - and history['season'] == sql_result['season'] - and history['episode'] == sql_result['episode'] + if not any((history['show_id'] == sql_result['showid'] \ + and history['season'] == sql_result['season'] \ + and history['episode'] == sql_result['episode'] \ and history['quality'] == sql_result['quality'])\ for history in compact): @@ -1180,7 +1179,7 @@ class ConfigPostProcessing: @cherrypy.expose def testNaming(self, pattern=None, multi=None, abd=False): - if multi is not None: + if multi != None: multi = int(multi) result = naming.test_name(pattern, multi, abd) @@ -1191,7 +1190,7 @@ class ConfigPostProcessing: @cherrypy.expose def isNamingValid(self, pattern=None, multi=None, abd=False): - if pattern is None: + if pattern == None: return "invalid" # air by date shows just need one check, we don't need to worry about season folders @@ -1757,7 +1756,7 @@ class ConfigSubtitles: subtitles_finder_frequency = 1 if use_subtitles == "on": - if sickbeard.subtitlesFinderScheduler.thread is None or not sickbeard.subtitlesFinderScheduler.thread.isAlive(): + if sickbeard.subtitlesFinderScheduler.thread == None or not sickbeard.subtitlesFinderScheduler.thread.isAlive(): sickbeard.subtitlesFinderScheduler.silent = False sickbeard.subtitlesFinderScheduler.initThread() else: @@ -1871,7 +1870,7 @@ class HomePostProcess: redirect("/home/postprocess/") else: result = processTV.processDir(dir, nzbName, process_method=process_method, force=force, is_priority=is_priority, failed=failed, type=type, indexer=indexer) - if quiet is not None and int(quiet) == 1: + if quiet != None and int(quiet) == 1: return result result = result.replace("\n","
    \n") @@ -2423,7 +2422,7 @@ class Home: host = config.clean_host(host, default_port=23053) result = notifiers.growl_notifier.test_notify(host, password) - if password is None or password == '': + if password == None or password == '': pw_append = '' else: pw_append = " with password: " + password @@ -2695,12 +2694,12 @@ class Home: @cherrypy.expose def displayShow(self, show=None): - if show is None: + if show == None: return _genericMessage("Error", "Invalid show ID") else: showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Show not in show list") showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.indexerid) @@ -2806,14 +2805,9 @@ class Home: return result['description'] if result else 'Episode not found.' @cherrypy.expose - def editShow(self, show=None, location=None, anyQualities=None, bestQualities=None, exceptions_list=None, - flatten_folders=None, paused=None, directCall=False, air_by_date=None, dvdorder=None, indexerLang=None, - subtitles=None, archive_firstmatch=None): + def editShow(self, show=None, location=None, anyQualities=[], bestQualities=[], exceptions_list=[], flatten_folders=None, paused=None, directCall=False, air_by_date=None, dvdorder=None, indexerLang=None, subtitles=None, archive_firstmatch=None): - if not anyQualities: anyQualities = [] - if not bestQualities: bestQualities = [] - if not exceptions_list: exceptions_list = [] - if show is None: + if show == None: errString = "Invalid show ID: " + str(show) if directCall: return [errString] @@ -2822,7 +2816,7 @@ class Home: showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: errString = "Unable to find the specified show: " + str(show) if directCall: return [errString] @@ -2948,12 +2942,12 @@ class Home: @cherrypy.expose def deleteShow(self, show=None): - if show is None: + if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Unable to find the specified show") if sickbeard.showQueueScheduler.action.isBeingAdded(showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): # @UndefinedVariable @@ -2967,12 +2961,12 @@ class Home: @cherrypy.expose def refreshShow(self, show=None): - if show is None: + if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # force the update from the DB @@ -2989,12 +2983,12 @@ class Home: @cherrypy.expose def updateShow(self, show=None, force=0): - if show is None: + if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # force the update @@ -3012,12 +3006,12 @@ class Home: @cherrypy.expose def subtitleShow(self, show=None, force=0): - if show is None: + if show == None: return _genericMessage("Error", "Invalid show ID") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Unable to find the specified show") # search and download subtitles @@ -3055,7 +3049,7 @@ class Home: @cherrypy.expose def setStatus(self, show=None, eps=None, status=None, direct=False): - if show is None or eps is None or status is None: + if show == None or eps == None or status == None: errMsg = "You must specify a show and at least one episode" if direct: ui.notifications.error('Error', errMsg) @@ -3073,7 +3067,7 @@ class Home: showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: errMsg = "Error", "Show not in show list" if direct: ui.notifications.error('Error', errMsg) @@ -3084,7 +3078,7 @@ class Home: wanted_segments = [] failed_segments = {} - if eps is not None: + if eps != None: sql_l = [] for curEp in eps.split('|'): @@ -3095,7 +3089,7 @@ class Home: epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1])) - if epObj is None: + if epObj == None: return _genericMessage("Error", "Episode couldn't be retrieved") if int(status) in (WANTED, FAILED): @@ -3161,12 +3155,12 @@ class Home: @cherrypy.expose def testRename(self, show=None): - if show is None: + if show == None: return _genericMessage("Error", "You must specify a show") showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if showObj is None: + if showObj == None: return _genericMessage("Error", "Show not in show list") try: @@ -3207,13 +3201,13 @@ class Home: @cherrypy.expose def doRename(self, show=None, eps=None): - if show is None or eps is None: + if show == None or eps == None: errMsg = "You must specify a show and at least one episode" return _genericMessage("Error", errMsg) show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) - if show_obj is None: + if show_obj == None: errMsg = "Error", "Show not in show list" return _genericMessage("Error", errMsg) @@ -3224,7 +3218,7 @@ class Home: myDB = db.DBConnection() - if eps is None: + if eps == None: redirect("/home/displayShow?show=" + show) for curEp in eps.split('|'): @@ -3264,7 +3258,7 @@ class Home: 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 is None: # @UndefinedVariable + while ep_queue_item.success == None: # @UndefinedVariable time.sleep(1) # return the correct json value @@ -3362,7 +3356,7 @@ class Home: 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 is None: # @UndefinedVariable + while ep_queue_item.success == None: # @UndefinedVariable time.sleep(1) # return the correct json value @@ -3642,7 +3636,7 @@ class WebInterface: air_date_time = network_timezones.parse_date_time(episode['airdate'], show["airs"], show['network']) # Create event for episode - ical += 'BEGIN:VEVENT\r\n' + ical = ical + 'BEGIN:VEVENT\r\n' ical = ical + 'DTSTART;VALUE=DATE:' + str(air_date_time.date()).replace("-", "") + '\r\n' ical = ical + 'SUMMARY:' + show['show_name'] + ': ' + episode['name'] + '\r\n' ical = ical + 'UID:Sick-Beard-' + str(datetime.date.today().isoformat()) + '-' + show['show_name'].replace(" ", "-") + '-E' + str(episode['episode']) + 'S' + str(episode['season']) + '\r\n' @@ -3651,7 +3645,7 @@ class WebInterface: else: ical = ical + 'DESCRIPTION:' + show['airs'] + ' on ' + show['network'] + '\r\n' ical = ical + 'LOCATION:' + 'Episode ' + str(episode['episode']) + ' - Season ' + str(episode['season']) + '\r\n' - ical += 'END:VEVENT\r\n' + ical = ical + 'END:VEVENT\r\n' # Ending the iCal ical += 'END:VCALENDAR' diff --git a/sickbeard/webserveInit.py b/sickbeard/webserveInit.py index 724869bb..130be29f 100644 --- a/sickbeard/webserveInit.py +++ b/sickbeard/webserveInit.py @@ -27,8 +27,7 @@ from sickbeard.webserve import WebInterface from sickbeard.helpers import create_https_certificates -def initWebServer(options=None): - if not options: options = {} +def initWebServer(options = {}): options.setdefault('port', 8081) options.setdefault('host', '0.0.0.0') options.setdefault('log_dir', None)