1
0
mirror of https://github.com/moparisthebest/SickRage synced 2025-01-07 03:48:02 -05:00

Code cleanup and regex fix for "no repeats" error

This commit is contained in:
echel0n 2014-03-20 10:51:21 -07:00
parent 3665a1f69b
commit 8ecd5a196d
80 changed files with 955 additions and 910 deletions

View File

@ -37,7 +37,7 @@ $(document).ready(function() {
$('.dir_check').each(function(i,w){ $('.dir_check').each(function(i,w){
if ($(w).is(':checked')) { if ($(w).is(':checked')) {
if (url.length) if (url.length)
url += '&' url += '&';
url += 'rootDir=' + encodeURIComponent($(w).attr('id')); url += 'rootDir=' + encodeURIComponent($(w).attr('id'));
} }
}); });

View File

@ -10,7 +10,7 @@
if (data.result != "failure" && data.result != "No subtitles downloaded") { if (data.result != "failure" && data.result != "No subtitles downloaded") {
// clear and update the subtitles column with new informations // clear and update the subtitles column with new informations
var subtitles = data.subtitles.split(','); var subtitles = data.subtitles.split(',');
subtitles_td.empty() subtitles_td.empty();
$.each(subtitles,function(index, language){ $.each(subtitles,function(index, language){
if (language != "" && language != "und") { if (language != "" && language != "und") {
if (index != subtitles.length - 1) { if (index != subtitles.length - 1) {

View File

@ -238,8 +238,8 @@ $(document).ready(function () {
config_arr.push(show_metadata ? '1' : '0'); config_arr.push(show_metadata ? '1' : '0');
config_arr.push(episode_metadata ? '1' : '0'); config_arr.push(episode_metadata ? '1' : '0');
config_arr.push(fanart ? '1' : '0'); config_arr.push(fanart ? '1' : '0');
config_arr.push(poster ? '1' : '0'); config_arr.push(poster ? '1' : '0');
config_arr.push(banner ? '1' : '0'); config_arr.push(banner ? '1' : '0');
config_arr.push(episode_thumbnails ? '1' : '0'); config_arr.push(episode_thumbnails ? '1' : '0');
config_arr.push(season_posters ? '1' : '0'); config_arr.push(season_posters ? '1' : '0');
config_arr.push(season_banners ? '1' : '0'); config_arr.push(season_banners ? '1' : '0');
@ -274,7 +274,7 @@ $(document).ready(function () {
$(this).showHideMetadata(); $(this).showHideMetadata();
} }
} };
$(this).refreshMetadataConfig(true); $(this).refreshMetadataConfig(true);
$('img[title]').qtip( { $('img[title]').qtip( {
@ -295,7 +295,7 @@ $(document).ready(function () {
position: { position: {
viewport: $(window), viewport: $(window),
at: 'top center', at: 'top center',
my: 'bottom center', my: 'bottom center'
}, },
style: { style: {
tip: { tip: {
@ -315,7 +315,7 @@ $(document).ready(function () {
position: { position: {
viewport: $(window), viewport: $(window),
at: 'center left', at: 'center left',
my: 'center right', my: 'center right'
}, },
style: { style: {
tip: { tip: {

View File

@ -1,40 +1,40 @@
$(document).ready(function(){ $(document).ready(function(){
$.fn.showHideProviders = function() { $.fn.showHideProviders = function () {
$('.providerDiv').each(function(){ $('.providerDiv').each(function () {
var providerName = $(this).attr('id'); var providerName = $(this).attr('id');
var selectedProvider = $('#editAProvider :selected').val(); var selectedProvider = $('#editAProvider :selected').val();
if (selectedProvider+'Div' == providerName) if (selectedProvider + 'Div' == providerName)
$(this).show(); $(this).show();
else else
$(this).hide(); $(this).hide();
}); });
} };
$.fn.addProvider = function (id, name, url, key, isDefault, showProvider) { $.fn.addProvider = function (id, name, url, key, isDefault, showProvider) {
url = $.trim(url); url = $.trim(url);
if (!url) if (!url)
return; return;
if (!/^https?:\/\//i.test(url)) if (!/^https?:\/\//i.test(url))
url = "http://" + url; url = "http://" + url;
if (url.match('/$') == null) if (url.match('/$') == null)
url = url + '/'; url = url + '/';
var newData = [isDefault, [name, url, key]]; var newData = [isDefault, [name, url, key]];
newznabProviders[id] = newData; newznabProviders[id] = newData;
if (!isDefault){ if (!isDefault) {
$('#editANewznabProvider').addOption(id, name); $('#editANewznabProvider').addOption(id, name);
$(this).populateNewznabSection(); $(this).populateNewznabSection();
} }
if ($('#provider_order_list > #'+id).length == 0 && showProvider != false) { if ($('#provider_order_list > #' + id).length == 0 && showProvider != false) {
var toAdd = '<li class="ui-state-default" id="'+id+'"> <input type="checkbox" id="enable_'+id+'" class="provider_enabler" CHECKED> <a href="'+url+'" class="imgLink" target="_new"><img src="'+sbRoot+'/images/providers/newznab.png" alt="'+name+'" width="16" height="16"></a> '+name+'</li>' var toAdd = '<li class="ui-state-default" id="' + id + '"> <input type="checkbox" id="enable_' + id + '" class="provider_enabler" CHECKED> <a href="' + url + '" class="imgLink" target="_new"><img src="' + sbRoot + '/images/providers/newznab.png" alt="' + name + '" width="16" height="16"></a> ' + name + '</li>'
$('#provider_order_list').append(toAdd); $('#provider_order_list').append(toAdd);
$('#provider_order_list').sortable("refresh"); $('#provider_order_list').sortable("refresh");
@ -42,7 +42,7 @@ $(document).ready(function(){
$(this).makeNewznabProviderString(); $(this).makeNewznabProviderString();
} };
$.fn.addTorrentRssProvider = function (id, name, url) { $.fn.addTorrentRssProvider = function (id, name, url) {
@ -52,8 +52,8 @@ $(document).ready(function(){
$('#editATorrentRssProvider').addOption(id, name); $('#editATorrentRssProvider').addOption(id, name);
$(this).populateTorrentRssSection(); $(this).populateTorrentRssSection();
if ($('#provider_order_list > #'+id).length == 0) { if ($('#provider_order_list > #' + id).length == 0) {
var toAdd = '<li class="ui-state-default" id="'+id+'"> <input type="checkbox" id="enable_'+id+'" class="provider_enabler" CHECKED> <a href="'+url+'" class="imgLink" target="_new"><img src="'+sbRoot+'/images/providers/torrentrss.png" alt="'+name+'" width="16" height="16"></a> '+name+'</li>' var toAdd = '<li class="ui-state-default" id="' + id + '"> <input type="checkbox" id="enable_' + id + '" class="provider_enabler" CHECKED> <a href="' + url + '" class="imgLink" target="_new"><img src="' + sbRoot + '/images/providers/torrentrss.png" alt="' + name + '" width="16" height="16"></a> ' + name + '</li>'
$('#provider_order_list').append(toAdd); $('#provider_order_list').append(toAdd);
$('#provider_order_list').sortable("refresh"); $('#provider_order_list').sortable("refresh");
@ -61,7 +61,7 @@ $(document).ready(function(){
$(this).makeTorrentRssProviderString(); $(this).makeTorrentRssProviderString();
} };
$.fn.updateProvider = function (id, url, key) { $.fn.updateProvider = function (id, url, key) {
@ -72,38 +72,38 @@ $(document).ready(function(){
$(this).makeNewznabProviderString(); $(this).makeNewznabProviderString();
} };
$.fn.deleteProvider = function (id) { $.fn.deleteProvider = function (id) {
$('#editANewznabProvider').removeOption(id); $('#editANewznabProvider').removeOption(id);
delete newznabProviders[id]; delete newznabProviders[id];
$(this).populateNewznabSection(); $(this).populateNewznabSection();
$('li').remove('#'+id); $('li').remove('#' + id);
$(this).makeNewznabProviderString(); $(this).makeNewznabProviderString();
} };
$.fn.updateTorrentRssProvider = function (id, url) { $.fn.updateTorrentRssProvider = function (id, url) {
torrentRssProviders[id][1] = url; torrentRssProviders[id][1] = url;
$(this).populateTorrentRssSection(); $(this).populateTorrentRssSection();
$(this).makeTorrentRssProviderString(); $(this).makeTorrentRssProviderString();
} };
$.fn.deleteTorrentRssProvider = function (id) { $.fn.deleteTorrentRssProvider = function (id) {
$('#editATorrentRssProvider').removeOption(id); $('#editATorrentRssProvider').removeOption(id);
delete torrentRssProviders[id]; delete torrentRssProviders[id];
$(this).populateTorrentRssSection(); $(this).populateTorrentRssSection();
$('li').remove('#'+id); $('li').remove('#' + id);
$(this).makeTorrentRssProviderString(); $(this).makeTorrentRssProviderString();
} };
$.fn.populateNewznabSection = function() { $.fn.populateNewznabSection = function () {
var selectedProvider = $('#editANewznabProvider :selected').val(); var selectedProvider = $('#editANewznabProvider :selected').val();
if (selectedProvider == 'addNewznab') { if (selectedProvider == 'addNewznab') {
var data = ['','','']; var data = ['', '', ''];
var isDefault = 0; var isDefault = 0;
$('#newznab_add_div').show(); $('#newznab_add_div').show();
$('#newznab_update_div').hide(); $('#newznab_update_div').hide();
@ -134,9 +134,9 @@ $(document).ready(function(){
} }
} }
} };
$.fn.makeNewznabProviderString = function() { $.fn.makeNewznabProviderString = function () {
var provStrings = new Array(); var provStrings = new Array();
@ -146,14 +146,14 @@ $(document).ready(function(){
$('#newznab_string').val(provStrings.join('!!!')) $('#newznab_string').val(provStrings.join('!!!'))
} };
$.fn.populateTorrentRssSection = function() { $.fn.populateTorrentRssSection = function () {
var selectedProvider = $('#editATorrentRssProvider :selected').val(); var selectedProvider = $('#editATorrentRssProvider :selected').val();
if (selectedProvider == 'addTorrentRss') { if (selectedProvider == 'addTorrentRss') {
var data = ['','','','']; var data = ['', '', '', ''];
$('#torrentrss_add_div').show(); $('#torrentrss_add_div').show();
$('#torrentrss_update_div').hide(); $('#torrentrss_update_div').hide();
} else { } else {
@ -180,9 +180,9 @@ $(document).ready(function(){
$('#torrentrss_delete').removeAttr("disabled"); $('#torrentrss_delete').removeAttr("disabled");
} }
} };
$.fn.makeTorrentRssProviderString = function() { $.fn.makeTorrentRssProviderString = function () {
var provStrings = new Array(); var provStrings = new Array();
for (var id in torrentRssProviders) { for (var id in torrentRssProviders) {
@ -191,19 +191,19 @@ $(document).ready(function(){
$('#torrentrss_string').val(provStrings.join('!!!')) $('#torrentrss_string').val(provStrings.join('!!!'))
} };
$.fn.refreshProviderList = function() { $.fn.refreshProviderList = function () {
var idArr = $("#provider_order_list").sortable('toArray'); var idArr = $("#provider_order_list").sortable('toArray');
var finalArr = new Array(); var finalArr = new Array();
$.each(idArr, function(key, val) { $.each(idArr, function (key, val) {
var checked = + $('#enable_'+val).prop('checked') ? '1' : '0'; var checked = +$('#enable_' + val).prop('checked') ? '1' : '0';
finalArr.push(val + ':' + checked); finalArr.push(val + ':' + checked);
}); });
$("#provider_order").val(finalArr.join(' ')); $("#provider_order").val(finalArr.join(' '));
} };
$.fn.hideConfigTab = function () { $.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_id = $(this).find("input").attr('id').replace("enable_", "") + "Div";
var config_form = '<div id="config"><form id="configForm_tip" action="saveProviders" method="post"><fieldset class="component-group-list tip_scale"><div class="providerDiv_tip">' + $("div[id*="+config_id+"]").html() + '</div></fieldset></form></div>' var config_form = '<div id="config"><form id="configForm_tip" action="saveProviders" method="post"><fieldset class="component-group-list tip_scale"><div class="providerDiv_tip">' + $("div[id*=" + config_id + "]").html() + '</div></fieldset></form></div>'
var provider_name = $.trim($(this).text()).replace('*','') var provider_name = $.trim($(this).text()).replace('*', '')
if ($("div[id*="+config_id+"]").length == 0) { if ($("div[id*=" + config_id + "]").length == 0) {
return false return false
} }
$(this).qtip({ $(this).qtip({
overwrite: true, overwrite: true,
position: { position: {
adjust: { adjust: {
x: 0, y: 0, x: 0, y: 0
}, },
my: 'left top', my: 'left top',
at: 'top right', at: 'top right'
}, },
show: { show: {
event: 'mouseenter', // Show it on click... event: 'mouseenter', // Show it on click...
target: false, target: false,
solo: true, solo: true,
delay: 90, delay: 90,
effect: true, effect: true
}, },
hide: { hide: {
fixed: true, fixed: true,
delay: 900, delay: 900
}, },
content: { content: {
text: config_form, text: config_form,
title: { title: {
text: provider_name + ' Config', text: provider_name + ' Config',
button: true button: true
} }
}, },
style: { style: {
border: { border: {
@ -272,11 +272,11 @@ $(document).ready(function(){
background: '#FFF', background: '#FFF',
padding: 15, padding: 15,
tip: true, // Give it a speech bubble tip with automatic corner detection 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 newznabProviders = new Array();
var torrentRssProviders = new Array(); var torrentRssProviders = new Array();
@ -390,7 +390,7 @@ $(document).ready(function(){
var name = $('#torrentrss_name').val(); var name = $('#torrentrss_name').val();
var url = $('#torrentrss_url').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 // send to the form with ajax, get a return value
$.getJSON(sbRoot + '/config/providers/canAddTorrentRssProvider', params, $.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_ratio = $('.providerDiv_tip #' + provider_id + '_seed_ratio').prop('value');
var seed_time = $('.providerDiv_tip #'+provider_id+'_seed_time').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 process_met = $('.providerDiv_tip #' + provider_id + '_process_method').prop('value');
var option_string = $('.providerDiv_tip #'+provider_id+'_option_string'); var option_string = $('.providerDiv_tip #' + provider_id + '_option_string');
option_string.val([seed_ratio, seed_time, process_met].join('|')) option_string.val([seed_ratio, seed_time, process_met].join('|'))
} };
$(this).on('change', '.seed_option', function(){ $(this).on('change', '.seed_option', function(){

View File

@ -8,8 +8,8 @@ $(document).ready(function(){
$('#no-torrents').hide(); $('#no-torrents').hide();
} }
$.fn.nzb_method_handler = function() { $.fn.nzb_method_handler = function () {
var selectedProvider = $('#nzb_method :selected').val(); var selectedProvider = $('#nzb_method :selected').val();
if (selectedProvider == "blackhole") { if (selectedProvider == "blackhole") {
@ -32,28 +32,28 @@ $(document).ready(function(){
$('#nzbget_settings').hide(); $('#nzbget_settings').hide();
} }
} };
$.fn.torrent_method_handler = function () {
$.fn.torrent_method_handler = function() {
var selectedProvider = $('#torrent_method :selected').val(); var selectedProvider = $('#torrent_method :selected').val();
if (selectedProvider == "blackhole") { if (selectedProvider == "blackhole") {
$('#t_blackhole_settings').show(); $('#t_blackhole_settings').show();
$('#torrent_settings').hide(); $('#torrent_settings').hide();
} else if (selectedProvider == "utorrent") { } else if (selectedProvider == "utorrent") {
$('#t_blackhole_settings').hide(); $('#t_blackhole_settings').hide();
$('#torrent_settings').show(); $('#torrent_settings').show();
$('#Torrent_username').show() $('#Torrent_username').show();
$('#Torrent_Path').hide(); $('#Torrent_Path').hide();
$('#Torrent_Ratio').hide(); $('#Torrent_Ratio').hide();
$('#Torrent_High_Bandwidth').hide(); $('#Torrent_High_Bandwidth').hide();
$('#Torrent_Label').show() $('#Torrent_Label').show();
$('#host_desc').text('uTorrent Host'); $('#host_desc').text('uTorrent Host');
$('#username_desc').text('uTorrent Username'); $('#username_desc').text('uTorrent Username');
$('#password_desc').text('uTorrent Password'); $('#password_desc').text('uTorrent Password');
$('#label_desc').text('uTorrent Label'); $('#label_desc').text('uTorrent Label');
} else if (selectedProvider == "transmission"){ } else if (selectedProvider == "transmission") {
$('#t_blackhole_settings').hide(); $('#t_blackhole_settings').hide();
$('#torrent_settings').show(); $('#torrent_settings').show();
$('#Torrent_username').show(); $('#Torrent_username').show();
@ -65,10 +65,10 @@ $(document).ready(function(){
$('#username_desc').text('Transmission Username'); $('#username_desc').text('Transmission Username');
$('#password_desc').text('Transmission Password'); $('#password_desc').text('Transmission Password');
$('#directory_desc').text('Transmission Directory'); $('#directory_desc').text('Transmission Directory');
} else if (selectedProvider == "deluge"){ } else if (selectedProvider == "deluge") {
$('#t_blackhole_settings').hide(); $('#t_blackhole_settings').hide();
$('#torrent_settings').show(); $('#torrent_settings').show();
$('#Torrent_Label').show(); $('#Torrent_Label').show();
$('#Torrent_username').hide(); $('#Torrent_username').hide();
$('#Torrent_Path').show(); $('#Torrent_Path').show();
$('#Torrent_Ratio').show(); $('#Torrent_Ratio').show();
@ -78,10 +78,10 @@ $(document).ready(function(){
$('#password_desc').text('Deluge Password'); $('#password_desc').text('Deluge Password');
$('#label_desc').text('Deluge Label'); $('#label_desc').text('Deluge Label');
$('#directory_desc').text('Deluge Directory'); $('#directory_desc').text('Deluge Directory');
} else if (selectedProvider == "download_station"){ } else if (selectedProvider == "download_station") {
$('#t_blackhole_settings').hide(); $('#t_blackhole_settings').hide();
$('#torrent_settings').show(); $('#torrent_settings').show();
$('#Torrent_Label').hide(); $('#Torrent_Label').hide();
$('#Torrent_username').show(); $('#Torrent_username').show();
$('#Torrent_Paused').hide(); $('#Torrent_Paused').hide();
$('#Torrent_Path').hide(); $('#Torrent_Path').hide();
@ -92,10 +92,10 @@ $(document).ready(function(){
$('#password_desc').text('Synology Password'); $('#password_desc').text('Synology Password');
$('#label_desc').text('Synology Label'); $('#label_desc').text('Synology Label');
$('#directory_desc').text('Synology Directory'); $('#directory_desc').text('Synology Directory');
} else if (selectedProvider == "rtorrent"){ } else if (selectedProvider == "rtorrent") {
$('#t_blackhole_settings').hide(); $('#t_blackhole_settings').hide();
$('#torrent_settings').show(); $('#torrent_settings').show();
$('#Torrent_Label').show(); $('#Torrent_Label').show();
$('#Torrent_username').show(); $('#Torrent_username').show();
$('#Torrent_Paused').hide(); $('#Torrent_Paused').hide();
$('#Torrent_Path').show(); $('#Torrent_Path').show();
@ -107,7 +107,7 @@ $(document).ready(function(){
$('#label_desc').text('rTorrent Label'); $('#label_desc').text('rTorrent Label');
$('#directory_desc').text('rTorrent Directory'); $('#directory_desc').text('rTorrent Directory');
} }
} };
$('#nzb_method').change($(this).nzb_method_handler); $('#nzb_method').change($(this).nzb_method_handler);

View File

@ -1,48 +1,48 @@
$(document).ready(function(){ $(document).ready(function(){
$.fn.showHideServices = function() { $.fn.showHideServices = function () {
$('.serviceDiv').each(function(){ $('.serviceDiv').each(function () {
var serviceName = $(this).attr('id'); var serviceName = $(this).attr('id');
var selectedService = $('#editAService :selected').val(); var selectedService = $('#editAService :selected').val();
if (selectedService+'Div' == serviceName) if (selectedService + 'Div' == serviceName)
$(this).show(); $(this).show();
else else
$(this).hide(); $(this).hide();
}); });
} };
$.fn.addService = function (id, name, url, key, isDefault, showService) { $.fn.addService = function (id, name, url, key, isDefault, showService) {
if (url.match('/$') == null) if (url.match('/$') == null)
url = url + '/' url = url + '/';
var newData = [isDefault, [name, url, key]]; var newData = [isDefault, [name, url, key]];
if ($('#service_order_list > #'+id).length == 0 && showService != false) { if ($('#service_order_list > #' + id).length == 0 && showService != false) {
var toAdd = '<li class="ui-state-default" id="'+id+'"> <input type="checkbox" id="enable_'+id+'" class="service_enabler" CHECKED> <a href="'+url+'" class="imgLink" target="_new"><img src="'+sbRoot+'/images/services/newznab.gif" alt="'+name+'" width="16" height="16"></a> '+name+'</li>' var toAdd = '<li class="ui-state-default" id="' + id + '"> <input type="checkbox" id="enable_' + id + '" class="service_enabler" CHECKED> <a href="' + url + '" class="imgLink" target="_new"><img src="' + sbRoot + '/images/services/newznab.gif" alt="' + name + '" width="16" height="16"></a> ' + name + '</li>';
$('#service_order_list').append(toAdd); $('#service_order_list').append(toAdd);
$('#service_order_list').sortable("refresh"); $('#service_order_list').sortable("refresh");
} }
} };
$.fn.deleteService = function (id) { $.fn.deleteService = function (id) {
$('#service_order_list > #'+id).remove(); $('#service_order_list > #' + id).remove();
} };
$.fn.refreshServiceList = function() { $.fn.refreshServiceList = function () {
var idArr = $("#service_order_list").sortable('toArray'); var idArr = $("#service_order_list").sortable('toArray');
var finalArr = new Array(); var finalArr = new Array();
$.each(idArr, function(key, val) { $.each(idArr, function (key, val) {
var checked = + $('#enable_'+val).prop('checked') ? '1' : '0'; var checked = +$('#enable_' + val).prop('checked') ? '1' : '0';
finalArr.push(val + ':' + checked); finalArr.push(val + ':' + checked);
}); });
$("#service_order").val(finalArr.join(' ')); $("#service_order").val(finalArr.join(' '));
} };
$('#editAService').change(function(){ $('#editAService').change(function(){
$(this).showHideServices(); $(this).showHideServices();

View File

@ -25,8 +25,8 @@ $(document).ready(function(){
}); });
$('#changeStatus').click(function(){ $('#changeStatus').click(function(){
var sbRoot = $('#sbRoot').val() var sbRoot = $('#sbRoot').val();
var epArr = new Array() var epArr = new Array();
$('.epCheck').each(function() { $('.epCheck').each(function() {
@ -37,9 +37,9 @@ $(document).ready(function(){
}); });
if (epArr.length == 0) 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 window.location.href = url
}); });
@ -49,7 +49,7 @@ $(document).ready(function(){
var seasNo = $(seasCheck).attr('id'); var seasNo = $(seasCheck).attr('id');
$('.epCheck:visible').each(function(){ $('.epCheck:visible').each(function(){
var epParts = $(this).attr('id').split('x') var epParts = $(this).attr('id').split('x');
if (epParts[0] == seasNo) { if (epParts[0] == seasNo) {
this.checked = seasCheck.checked this.checked = seasCheck.checked
@ -103,19 +103,19 @@ $(document).ready(function(){
// handle the show selection dropbox // handle the show selection dropbox
$('#pickShow').change(function(){ $('#pickShow').change(function(){
var sbRoot = $('#sbRoot').val() var sbRoot = $('#sbRoot').val();
var val = $(this).attr('value') var val = $(this).attr('value');
if (val == 0) if (val == 0)
return return;
url = sbRoot+'/home/displayShow?show='+val url = sbRoot + '/home/displayShow?show=' + val;
window.location.href = url window.location.href = url
}); });
// show/hide different types of rows when the checkboxes are changed // show/hide different types of rows when the checkboxes are changed
$("#checkboxControls input").change(function(e){ $("#checkboxControls input").change(function(e){
var whichClass = $(this).attr('id') var whichClass = $(this).attr('id');
$(this).showHideRows(whichClass) $(this).showHideRows(whichClass);
return return;
$('tr.'+whichClass).each(function(i){ $('tr.'+whichClass).each(function(i){
$(this).toggle(); $(this).toggle();
}); });
@ -133,10 +133,10 @@ $(document).ready(function(){
}); });
}); });
$.fn.showHideRows = function(whichClass){ $.fn.showHideRows = function (whichClass) {
var status = $('#checkboxControls > input, #'+whichClass).prop('checked') var status = $('#checkboxControls > input, #' + whichClass).prop('checked');
$("tr."+whichClass).each(function(e){ $("tr." + whichClass).each(function (e) {
if (status) { if (status) {
$(this).show(); $(this).show();
} else { } else {
@ -145,22 +145,22 @@ $(document).ready(function(){
}); });
// hide season headers with no episodes under them // hide season headers with no episodes under them
$('tr.seasonheader').each(function(){ $('tr.seasonheader').each(function () {
var numRows = 0 var numRows = 0;
var seasonNo = $(this).attr('id') var seasonNo = $(this).attr('id');
$('tr.'+seasonNo+' :visible').each(function(){ $('tr.' + seasonNo + ' :visible').each(function () {
numRows++ numRows++
}) });
if (numRows == 0) { if (numRows == 0) {
$(this).hide() $(this).hide();
$('#'+seasonNo+'-cols').hide() $('#' + seasonNo + '-cols').hide()
} else { } else {
$(this).show() $(this).show();
$('#'+seasonNo+'-cols').show() $('#' + seasonNo + '-cols').show()
} }
}); });
} };
function setEpisodeSceneNumbering(forSeason, forEpisode, sceneSeason, sceneEpisode) { function setEpisodeSceneNumbering(forSeason, forEpisode, sceneSeason, sceneEpisode) {
var sbRoot = $('#sbRoot').val(); var sbRoot = $('#sbRoot').val();

View File

@ -1,7 +1,8 @@
$(document).ready(function(){ $(document).ready(function(){
$('#submitMassRemove').click(function(){ $('#submitMassRemove').click(function(){
var removeArr = new Array() var removeArr = new Array();
;
$('.removeCheck').each(function() { $('.removeCheck').each(function() {
if (this.checked == true) { if (this.checked == true) {
@ -12,7 +13,7 @@ $(document).ready(function(){
if (removeArr.length == 0) if (removeArr.length == 0)
return false return false
url = sbRoot + '/manage/failedDownloads?toRemove='+removeArr.join('|') url = sbRoot + '/manage/failedDownloads?toRemove=' + removeArr.join('|');
window.location.href = url window.location.href = url

View File

@ -10,203 +10,211 @@
function formtowizard(options){ function formtowizard(options){
this.setting=jQuery.extend({persistsection:false, revealfx:['slide', 500], oninit:function(){}, onpagechangestart:function(){}}, options) this.setting = jQuery.extend({persistsection: false, revealfx: ['slide', 500], oninit: function () {
this.currentsection=-1 }, onpagechangestart: function () {
}}, options);
this.currentsection = -1;
this.init(this.setting) 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) 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 $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 var $startelement = $theform.find(':first-child'); //reference first element inside form
for (var i=0; i<arr.length; i++){ //loop thru "break" elements 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) 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('<fieldset class="sectionwrap" />') //wrap these elements with fieldset element $fieldsetelements.add($fieldsetelements.next()).wrapAll('<fieldset class="sectionwrap" />'); //wrap these elements with fieldset element
$startelement=$theform.find('fieldset.sectionwrap').eq(i).prepend('<legend class="legendStep">'+arr[i].legend+'</legend>').next() //increment startelement to begin at the end of the just inserted fieldset element $startelement = $theform.find('fieldset.sectionwrap').eq(i).prepend('<legend class="legendStep">' + arr[i].legend + '</legend>').next(); //increment startelement to begin at the end of the just inserted fieldset element
} }
}, },
loadsection:function(rawi, bypasshooks){ loadsection: function (rawi, bypasshooks) {
var thiswizard=this 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) //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)) 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 doload = (doload === false) ? false : true; //unless doload is explicitly false, set to true
if (!bypasshooks && this.setting.validate){ if (!bypasshooks && this.setting.validate) {
var outcome=this.validate(this.currentsection) var outcome = this.validate(this.currentsection);
if (outcome===false) if (outcome === false)
doload=false doload = false
} }
var i=(rawi=="prev")? this.currentsection-1 : (rawi=="next")? this.currentsection+1 : parseInt(rawi) //get index of next section to show 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 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 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 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"){ if (this.setting.revealfx[0] == "slide") {
this.sections.$sections.css("visibility", "visible") 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.$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 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){ 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) 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") thiswizard.sections.$sections.eq(thissec).css("visibility", "hidden")
}) })
}) })
} }
else if (this.setting.revealfx[0]=="fade"){ //if fx is "fade" 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(){ this.sections.$sections.eq(this.currentsection).hide().end().eq(i).fadeIn(this.setting.revealfx[1], function () {
if (document.all && this.style && this.style.removeAttribute) if (document.all && this.style && this.style.removeAttribute)
this.style.removeAttribute('filter') //fix IE clearType problem this.style.removeAttribute('filter'); //fix IE clearType problem
}) })
} }
else{ else {
this.sections.$sections.eq(this.currentsection).hide().end().eq(i).show() 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.$status.text("Page " + (i + 1) + " of " + this.sections.count); //update current page status text
this.paginatediv.$navlinks.css('visibility', 'visible') this.paginatediv.$navlinks.css('visibility', 'visible');
if (i==0) //hide "prev" link if (i == 0) //hide "prev" link
this.paginatediv.$navlinks.eq(0).css('visibility', 'hidden') this.paginatediv.$navlinks.eq(0).css('visibility', 'hidden');
else if (i==this.sections.count-1) //hide "next" link else if (i == this.sections.count - 1) //hide "next" link
this.paginatediv.$navlinks.eq(1).css('visibility', 'hidden') this.paginatediv.$navlinks.eq(1).css('visibility', 'hidden');
if (this.setting.persistsection) //enable persistence? if (this.setting.persistsection) //enable persistence?
formtowizard.routines.setCookie(this.setting.formid+"_persist", i) formtowizard.routines.setCookie(this.setting.formid + "_persist", i);
this.currentsection=i this.currentsection = i;
if(i === 0) { setTimeout(function() { $('#nameToSearch').focus(); }, 250); } if (i === 0) {
} setTimeout(function () {
}, $('#nameToSearch').focus();
}, 250);
}
}
},
addvalidatefields:function(){ addvalidatefields: function () {
var $=jQuery, setting=this.setting, theform=this.$theform.get(0), validatefields=[] var $ = jQuery, setting = this.setting, theform = this.$theform.get(0), validatefields = [];
var validatefields=setting.validate //array of form element ids to validate var validatefields = setting.validate; //array of form element ids to validate
for (var i=0; i<validatefields.length; i++){ for (var i = 0; i < validatefields.length; i++) {
var el=theform.elements[validatefields[i]] //reference form element var el = theform.elements[validatefields[i]]; //reference form element
if (el){ //if element is defined if (el) { //if element is defined
var $section=$(el).parents('fieldset.sectionwrap:eq(0)') //find fieldset.sectionwrap this form element belongs to var $section = $(el).parents('fieldset.sectionwrap:eq(0)'); //find fieldset.sectionwrap this form element belongs to
if ($section.length==1){ //if element is within a fieldset.sectionwrap element if ($section.length == 1) { //if element is within a fieldset.sectionwrap element
$section.data('elements').push(el) //cache this element inside corresponding section $section.data('elements').push(el); //cache this element inside corresponding section
} }
} }
} }
}, },
validate:function(section){ validate: function (section) {
var elements=this.sections.$sections.eq(section).data('elements') //reference elements within this section that should be validated 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"] var validated = true, invalidtext = ["Please fill out the following fields:\n"];
function invalidate(el){
validated=false function invalidate(el) {
invalidtext.push("- "+ (el.id || el.name)) validated = false;
} invalidtext.push("- " + (el.id || el.name))
for (var i=0; i<elements.length; i++){ }
if (/(text)/.test(elements[i].type) && elements[i].value==""){ //text and textarea elements
invalidate(elements[i]) for (var i = 0; i < elements.length; i++) {
} if (/(text)/.test(elements[i].type) && elements[i].value == "") { //text and textarea elements
else if (/(select)/.test(elements[i].type) && (elements[i].selectedIndex==-1 || elements[i].options[elements[i].selectedIndex].text=="")){ //select elements invalidate(elements[i])
invalidate(elements[i]) }
} else if (/(select)/.test(elements[i].type) && (elements[i].selectedIndex == -1 || elements[i].options[elements[i].selectedIndex].text == "")) { //select elements
else if (elements[i].type==undefined && elements[i].length>0){ //radio and checkbox elements invalidate(elements[i])
var onechecked=false }
for (var r=0; r<elements[i].length; r++){ else if (elements[i].type == undefined && elements[i].length > 0) { //radio and checkbox elements
if (elements[i][r].checked==true){ var onechecked = false;
onechecked=true for (var r = 0; r < elements[i].length; r++) {
break if (elements[i][r].checked == true) {
} onechecked = true;
} break
if (!onechecked){ }
invalidate(elements[i][0]) }
} if (!onechecked) {
} invalidate(elements[i][0])
} }
if (!validated) }
alert(invalidtext.join('\n')) }
return validated if (!validated)
}, alert(invalidtext.join('\n'));
return validated
},
init:function(setting){ init: function (setting) {
var thiswizard=this var thiswizard = this;
jQuery(function($){ //on document.ready jQuery(function ($) { //on document.ready
var $theform=$('#'+setting.formid) var $theform = $('#' + setting.formid);
if ($theform.length==0) //if form with specified ID doesn't exist, try name attribute instead if ($theform.length == 0) //if form with specified ID doesn't exist, try name attribute instead
$theform=$('form[name='+setting.formid+']') $theform = $('form[name=' + setting.formid + ']');
if (setting.manualfieldsets && setting.manualfieldsets.length>0) if (setting.manualfieldsets && setting.manualfieldsets.length > 0)
thiswizard.createfieldsets($theform, setting.manualfieldsets) thiswizard.createfieldsets($theform, setting.manualfieldsets);
var $stepsguide=$('<div class="stepsguide" />') //create Steps Container to house the "steps" text var $stepsguide = $('<div class="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 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 if (setting.revealfx[0] == "slide") { //create outer DIV that will house all the fieldset.sectionwrap elements
$sectionswrapper=$('<div style="position:relative;overflow:hidden;"></div>').insertBefore($sections.eq(0)) //add DIV above the first fieldset.sectionwrap element $sectionswrapper = $('<div style="position:relative;overflow:hidden;"></div>').insertBefore($sections.eq(0)); //add DIV above the first fieldset.sectionwrap element
$sectionswrapper_inner=$('<div style="position:absolute;left:0;top:0;"></div>') //create inner DIV of $sectionswrapper that will scroll to reveal a fieldset element $sectionswrapper_inner = $('<div style="position:absolute;left:0;top:0;"></div>'); //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 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) $sections.slice(1).each(function (i) { //loop through $sections (starting from 2nd one)
maxfieldsetwidth=Math.max($(this).outerWidth(), maxfieldsetwidth) maxfieldsetwidth = Math.max($(this).outerWidth(), maxfieldsetwidth)
}) });
maxfieldsetwidth+=2 //add 2px to final width to reveal fieldset border (if not removed via CSS) maxfieldsetwidth += 2; //add 2px to final width to reveal fieldset border (if not removed via CSS)
thiswizard.maxfieldsetwidth=maxfieldsetwidth thiswizard.maxfieldsetwidth = maxfieldsetwidth;
$sections.each(function(i){ //loop through $sections again $sections.each(function (i) { //loop through $sections again
var $section=$(this) var $section = $(this);
if (setting.revealfx[0]=="slide"){ 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('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) $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: //create each "step" DIV and add it to main Steps Container:
var $thestep=$('<div class="step disabledstep" />').data('section', i).html('Step '+(i+1)+'<div class="smalltext">'+$section.find('legend:eq(0)').text()+'<p></p></div>').appendTo($stepsguide) var $thestep = $('<div class="step disabledstep" />').data('section', i).html('Step ' + (i + 1) + '<div class="smalltext">' + $section.find('legend:eq(0)').text() + '<p></p></div>').appendTo($stepsguide);
$thestep.click(function(){ //assign behavior to each step div $thestep.click(function () { //assign behavior to each step div
thiswizard.loadsection($(this).data('section')) thiswizard.loadsection($(this).data('section'))
}) })
}) });
if (setting.revealfx[0]=="slide"){ if (setting.revealfx[0] == "slide") {
$sectionswrapper.width(maxfieldsetwidth) //set fieldset wrapper to width of widest fieldset $sectionswrapper.width(maxfieldsetwidth); //set fieldset wrapper to width of widest fieldset
$sectionswrapper.append($sectionswrapper_inner) //add $sectionswrapper_inner as a child of $sectionswrapper $sectionswrapper.append($sectionswrapper_inner); //add $sectionswrapper_inner as a child of $sectionswrapper
} }
$theform.prepend($stepsguide) //add $thesteps div to the beginning of the form $theform.prepend($stepsguide); //add $thesteps div to the beginning of the form
//$stepsguide.insertBefore($sectionswrapper) //add Steps Container before sectionswrapper container //$stepsguide.insertBefore($sectionswrapper) //add Steps Container before sectionswrapper container
var $thesteps=$stepsguide.find('div.step') var $thesteps = $stepsguide.find('div.step');
//create pagination DIV and add it to end of form: //create pagination DIV and add it to end of form:
var $paginatediv=$('<div class="formpaginate" style="overflow:hidden;"><span class="prev" style="float:left">Prev</span> <span class="status">Step 1 of </span> <span class="next" style="float:right">Next</span></div>') var $paginatediv = $('<div class="formpaginate" style="overflow:hidden;"><span class="prev" style="float:left">Prev</span> <span class="status">Step 1 of </span> <span class="next" style="float:right">Next</span></div>');
$theform.append($paginatediv) $theform.append($paginatediv);
thiswizard.$theform=$theform thiswizard.$theform = $theform;
if (setting.revealfx[0]=="slide"){ 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 = {$outerwrapper: $sectionswrapper, $innerwrapper: $sectionswrapper_inner, $sections: $sections, count: $sections.length}; //remember various parts of section container
thiswizard.sections.$sections.show() thiswizard.sections.$sections.show()
} }
else{ else {
thiswizard.sections={$sections:$sections, count:$sections.length} //remember various parts of section container thiswizard.sections = {$sections: $sections, count: $sections.length}; //remember various parts of section container
} }
thiswizard.$thesteps=$thesteps //remember this ref 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: $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 thiswizard.paginatediv.$main.click(function (e) { //assign behavior to pagination buttons
if (/(prev)|(next)/.test(e.target.className)) if (/(prev)|(next)/.test(e.target.className))
thiswizard.loadsection(e.target.className) thiswizard.loadsection(e.target.className)
}) });
var i=(setting.persistsection)? formtowizard.routines.getCookie(setting.formid+"_persist") : 0 var i = (setting.persistsection) ? formtowizard.routines.getCookie(setting.formid + "_persist") : 0;
thiswizard.loadsection(i||0, true) //show the first section thiswizard.loadsection(i || 0, true); //show the first section
thiswizard.setting.oninit($, i, $sections.eq(i)) //call oninit event handler thiswizard.setting.oninit($, i, $sections.eq(i)); //call oninit event handler
if (setting.validate){ //if validate array defined if (setting.validate) { //if validate array defined
thiswizard.addvalidatefields() //seek out and cache form elements that should be validated thiswizard.addvalidatefields(); //seek out and cache form elements that should be validated
thiswizard.$theform.submit(function(){ thiswizard.$theform.submit(function () {
var returnval=true var returnval = true;
for (var i=0; i<thiswizard.sections.count; i++){ for (var i = 0; i < thiswizard.sections.count; i++) {
if (!thiswizard.validate(i)){ if (!thiswizard.validate(i)) {
thiswizard.loadsection(i, true) thiswizard.loadsection(i, true);
returnval=false returnval = false;
break break
} }
} }
return returnval //allow or disallow form submission return returnval; //allow or disallow form submission
}) })
} }
}) })
} }
} };
formtowizard.routines={ formtowizard.routines = {
getCookie:function(Name){ getCookie: function (Name) {
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair var re = new RegExp(Name + "=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value return document.cookie.match(re)[0].split("=")[1]; //return its value
return null return null
}, },
setCookie:function(name, value){ setCookie: function (name, value) {
document.cookie = name+"=" + value + ";path=/" document.cookie = name + "=" + value + ";path=/"
} }
} };

View File

@ -2,50 +2,52 @@
//** Available/ usage terms at http://www.dynamicdrive.com/ (April 11th, 09') //** Available/ usage terms at http://www.dynamicdrive.com/ (April 11th, 09')
//** Updated Nov 10th, 09'- Fixed anchor jumping issue in IE7 //** Updated Nov 10th, 09'- Fixed anchor jumping issue in IE7
var bookmarkscroll={ var bookmarkscroll = {
setting: {duration:1000, yoffset:-50}, //{duration_of_scroll_milliseconds, offset_from_target_element_to_rest} setting: {duration: 1000, yoffset: -50}, //{duration_of_scroll_milliseconds, offset_from_target_element_to_rest}
topkeyword: '#top', //keyword used in your anchors and scrollTo() to cause script to scroll page to very top topkeyword: '#top', //keyword used in your anchors and scrollTo() to cause script to scroll page to very top
scrollTo:function(dest, options, hash){ scrollTo: function (dest, options, hash) {
var $=jQuery, options=options || {} 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 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)){ 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(){ 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) //** if ($dest!==0 && hash)
//** location.hash=hash //** location.hash=hash
}) })
} }
}, },
urlparamselect:function(){ urlparamselect: function () {
var param=window.location.search.match(/scrollto=[\w\-_,]+/i) //search for scrollto=divid var param = window.location.search.match(/scrollto=[\w\-_,]+/i); //search for scrollto=divid
return (param)? param[0].split('=')[1] : null 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()
})
}
}
})
})
}
}
bookmarkscroll.init() 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();

View File

@ -5,72 +5,75 @@
//** 2) Fixes scroll animation not working in Opera. //** 2) Fixes scroll animation not working in Opera.
var scrolltotop={ var scrolltotop = {
//startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control //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). //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]}, setting: {startline: 100, scrollto: 0, scrollduration: 1000, fadeduration: [500, 100]},
controlHTML: top_image_html,//set in inc_top.tmpl so it can be $sbRooted 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 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 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(){ scrollup: function () {
if (!this.cssfixedsupport) //if control is positioned using JavaScript if (!this.cssfixedsupport) //if control is positioned using JavaScript
this.$control.css({opacity:0}) //hide control immediately after clicking it this.$control.css({opacity: 0}); //hide control immediately after clicking it
var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto) 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 if (typeof dest == "string" && jQuery('#' + dest).length == 1) //check element set by string exists
dest=jQuery('#'+dest).offset().top dest = jQuery('#' + dest).offset().top;
else else
dest=0 dest = 0;
this.$body.animate({scrollTop: dest}, this.setting.scrollduration); this.$body.animate({scrollTop: dest}, this.setting.scrollduration);
}, },
keepfixed:function(){ keepfixed: function () {
var $window=jQuery(window) var $window = jQuery(window);
var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx var controlx = $window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx;
var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety var controly = $window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety;
this.$control.css({left:controlx+'px', top:controly+'px'}) this.$control.css({left: controlx + 'px', top: controly + 'px'})
}, },
togglecontrol:function(){ togglecontrol: function () {
var scrolltop=jQuery(window).scrollTop() var scrolltop = jQuery(window).scrollTop();
if (!this.cssfixedsupport) if (!this.cssfixedsupport)
this.keepfixed() this.keepfixed();
this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false this.state.shouldvisible = (scrolltop >= this.setting.startline) ? true : false;
if (this.state.shouldvisible && !this.state.isvisible){ if (this.state.shouldvisible && !this.state.isvisible) {
this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0]) this.$control.stop().animate({opacity: 1}, this.setting.fadeduration[0]);
this.state.isvisible=true this.state.isvisible = true
} }
else if (this.state.shouldvisible==false && this.state.isvisible){ else if (this.state.shouldvisible == false && this.state.isvisible) {
this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1]) this.$control.stop().animate({opacity: 0}, this.setting.fadeduration[1]);
this.state.isvisible=false 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=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>')
.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() 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 = $('<div id="topcontrol">' + mainobj.controlHTML + '</div>')
.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();

View File

@ -96,29 +96,29 @@ var KEY = {
// Additional public (exposed) methods // Additional public (exposed) methods
var 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 || {}); var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () { return this.each(function () {
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings)); $(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
}); });
}, },
clear: function() { clear: function () {
this.data("tokenInputObject").clear(); this.data("tokenInputObject").clear();
return this; return this;
}, },
add: function(item) { add: function (item) {
this.data("tokenInputObject").add(item); this.data("tokenInputObject").add(item);
return this; return this;
}, },
remove: function(item) { remove: function (item) {
this.data("tokenInputObject").remove(item); this.data("tokenInputObject").remove(item);
return this; return this;
}, },
get: function() { get: function () {
return this.data("tokenInputObject").getTokens(); return this.data("tokenInputObject").getTokens();
} }
} };
// Expose the .tokenInput function to jQuery as a plugin // Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) { $.fn.tokenInput = function (method) {
@ -384,20 +384,20 @@ $.TokenList = function (input, url_or_data, settings) {
// Public functions // Public functions
// //
this.clear = function() { this.clear = function () {
token_list.children("li").each(function() { token_list.children("li").each(function () {
if ($(this).children("input").length === 0) { if ($(this).children("input").length === 0) {
delete_token($(this)); delete_token($(this));
} }
}); });
} };
this.add = function(item) { this.add = function (item) {
add_token(item); add_token(item);
} };
this.remove = function(item) { this.remove = function (item) {
token_list.children("li").each(function() { token_list.children("li").each(function () {
if ($(this).children("input").length === 0) { if ($(this).children("input").length === 0) {
var currToken = $(this).data("tokeninput"); var currToken = $(this).data("tokeninput");
var match = true; var match = true;
@ -412,11 +412,11 @@ $.TokenList = function (input, url_or_data, settings) {
} }
} }
}); });
} };
this.getTokens = function() { this.getTokens = function () {
return saved_tokens; return saved_tokens;
} };
// //
// Private functions // Private functions

View File

@ -13,7 +13,7 @@ $(document).ready(function() {
row += ' <td><input type="checkbox" class="'+indexer_id+'-epcheck" name="'+indexer_id+'-'+season+'x'+episode+'"'+checked+'></td>'; row += ' <td><input type="checkbox" class="'+indexer_id+'-epcheck" name="'+indexer_id+'-'+season+'x'+episode+'"'+checked+'></td>';
row += ' <td>'+season+'x'+episode+'</td>'; row += ' <td>'+season+'x'+episode+'</td>';
row += ' <td style="width: 100%">'+name+'</td>'; row += ' <td style="width: 100%">'+name+'</td>';
row += ' </tr>' row += ' </tr>';
return row; return row;
} }

View File

@ -12,13 +12,13 @@ $(document).ready(function() {
row += ' <td style="width: 1%;">'+season+'x'+episode+'</td>'; row += ' <td style="width: 1%;">'+season+'x'+episode+'</td>';
row += ' <td>'+name+'</td>'; row += ' <td>'+name+'</td>';
row += ' <td style="float: right;">'; row += ' <td style="float: right;">';
subtitles = subtitles.split(',') subtitles = subtitles.split(',');
for (i in subtitles) for (i in subtitles)
{ {
row += ' <img src="/images/flags/'+subtitles[i]+'.png" width="16" height="11" alt="'+subtitles[i]+'" />&nbsp;'; row += ' <img src="/images/flags/'+subtitles[i]+'.png" width="16" height="11" alt="'+subtitles[i]+'" />&nbsp;';
} }
row += ' </td>'; row += ' </td>';
row += ' </tr>' row += ' </tr>';
return row; return row;
} }

View File

@ -1,7 +1,7 @@
$(document).ready(function(){ $(document).ready(function(){
$('#submitMassEdit').click(function(){ $('#submitMassEdit').click(function(){
var editArr = new Array() var editArr = new Array();
$('.editCheck').each(function() { $('.editCheck').each(function() {
if (this.checked == true) { if (this.checked == true) {
@ -19,12 +19,12 @@ $(document).ready(function(){
$('#submitMassUpdate').click(function(){ $('#submitMassUpdate').click(function(){
var updateArr = new Array() var updateArr = new Array();
var refreshArr = new Array() var refreshArr = new Array();
var renameArr = new Array() var renameArr = new Array();
var subtitleArr = new Array() var subtitleArr = new Array();
var deleteArr = new Array() var deleteArr = new Array();
var metadataArr = new Array() var metadataArr = new Array();
$('.updateCheck').each(function() { $('.updateCheck').each(function() {
if (this.checked == true) { if (this.checked == true) {

View File

@ -112,10 +112,10 @@ $(document).ready(function() {
console.log('setting default to '+which); console.log('setting default to '+which);
if (which != undefined && !which.length) if (which != undefined && !which.length)
return return;
if ($('#whichDefaultRootDir').val() == which && force != true) if ($('#whichDefaultRootDir').val() == which && force != true)
return return;
// put an asterisk on the text // put an asterisk on the text
if ($('#'+which).text().charAt(0) != '*') if ($('#'+which).text().charAt(0) != '*')
@ -141,7 +141,7 @@ $(document).ready(function() {
function refreshRootDirs() { function refreshRootDirs() {
if (!$("#rootDirs").length) if (!$("#rootDirs").length)
return return;
var do_disable = 'true'; var do_disable = 'true';
@ -150,7 +150,7 @@ $(document).ready(function() {
// if nothing's selected then select the default // if nothing's selected then select the default
if (!$("#rootDirs option:selected").length && $('#whichDefaultRootDir').val().length) 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 something's selected then we have some behavior to figure out
if ($("#rootDirs option:selected").length) { if ($("#rootDirs option:selected").length) {
@ -183,7 +183,7 @@ $(document).ready(function() {
// set up buttons on page load // set up buttons on page load
syncOptionIDs(); syncOptionIDs();
setDefault($('#whichDefaultRootDir').val(), true) setDefault($('#whichDefaultRootDir').val(), true);
refreshRootDirs(); refreshRootDirs();
}); });

View File

@ -4,7 +4,7 @@ $(document).ready(function(){
var seasNo = $(seasCheck).attr('id'); var seasNo = $(seasCheck).attr('id');
$('.epCheck:visible').each(function(){ $('.epCheck:visible').each(function(){
var epParts = $(this).attr('id').split('x') var epParts = $(this).attr('id').split('x');
if (epParts[0] == seasNo) { if (epParts[0] == seasNo) {
this.checked = seasCheck.checked this.checked = seasCheck.checked
@ -13,7 +13,7 @@ $(document).ready(function(){
}); });
$('input[type=submit]').click(function(){ $('input[type=submit]').click(function(){
var epArr = new Array() var epArr = new Array();
$('.epCheck').each(function() { $('.epCheck').each(function() {
if (this.checked == true) { if (this.checked == true) {

16
lib/bencode/PKG-INFO Normal file
View File

@ -0,0 +1,16 @@
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

21
lib/bencode/README.txt Normal file
View File

@ -0,0 +1,21 @@
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

View File

@ -1 +1 @@
from bencode import * # not empty

View File

@ -66,8 +66,8 @@ def bdecode(x):
r, l = decode_func[x[0]](x, 0) r, l = decode_func[x[0]](x, 0)
except (IndexError, KeyError, ValueError): except (IndexError, KeyError, ValueError):
raise BTFailure("not a valid bencoded string") raise BTFailure("not a valid bencoded string")
# if l != len(x): if l != len(x):
# raise BTFailure("invalid bencoded value (data after valid prefix)") raise BTFailure("invalid bencoded value (data after valid prefix)")
return r return r
from types import StringType, IntType, LongType, DictType, ListType, TupleType from types import StringType, IntType, LongType, DictType, ListType, TupleType

5
lib/bencode/setup.cfg Normal file
View File

@ -0,0 +1,5 @@
[egg_info]
tag_build =
tag_date = 0
tag_svn_revision = 0

22
lib/bencode/setup.py Normal file
View File

@ -0,0 +1,22 @@
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.
""",
)

View File

@ -1630,13 +1630,13 @@ def launchBrowser(startPort=None):
def getEpList(epIDs, showid=None): def getEpList(epIDs, showid=None):
if epIDs == None or len(epIDs) == 0: if epIDs is None or len(epIDs) == 0:
return [] return []
query = "SELECT * FROM tv_episodes WHERE indexerid in (%s)" % (",".join(['?']*len(epIDs)),) query = "SELECT * FROM tv_episodes WHERE indexerid in (%s)" % (",".join(['?']*len(epIDs)),)
params = epIDs params = epIDs
if showid != None: if showid is not None:
query += " AND showid = ?" query += " AND showid = ?"
params.append(showid) params.append(showid)

View File

@ -94,7 +94,7 @@ class SearchResult:
def __str__(self): def __str__(self):
if self.provider == None: if self.provider is None:
return "Invalid provider, unable to print self" return "Invalid provider, unable to print self"
myString = self.provider.name + " @ " + self.url + "\n" myString = self.provider.name + " @ " + self.url + "\n"
@ -166,7 +166,7 @@ class Proper:
self.episode = -1 self.episode = -1
def __str__(self): def __str__(self):
return str(self.date)+" "+self.name+" "+str(self.season)+"x"+str(self.episode)+" of "+str(self.indexerid+" from "+self.indexer) return str(self.date)+" "+self.name+" "+str(self.season)+"x"+str(self.episode)+" of "+str(self.indexerid)+" from "+str(self.indexer)
class ErrorViewer(): class ErrorViewer():

View File

@ -132,7 +132,7 @@ class DelugeAPI(GenericClient):
self._request(method='post', data=post_data) self._request(method='post', data=post_data)
labels = self.response.json()['result'] labels = self.response.json()['result']
if labels != None: if labels is not None:
if label not in labels: if label not in labels:
logger.log(self.name + ': ' + label +u" label does not exist in Deluge we must add it", logger.DEBUG) 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', post_data = json.dumps({"method": 'label.add',

View File

@ -26,8 +26,9 @@ class GenericClient(object):
self.session = requests.session() self.session = requests.session()
self.session.auth = (self.username, self.password) self.session.auth = (self.username, self.password)
def _request(self, method='get', params={}, data=None, files=None): def _request(self, method='get', params=None, data=None, files=None):
if not params: params = {}
if time.time() > self.last_time + 1800 or not self.auth: if time.time() > self.last_time + 1800 or not self.auth:
self.last_time = time.time() self.last_time = time.time()
self._get_auth() self._get_auth()
@ -130,8 +131,7 @@ class GenericClient(object):
if len(torrent_hash) == 32: if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).lower() torrent_hash = b16encode(b32decode(torrent_hash)).lower()
else: else:
info = bdecode(result.content)["info"] torrent_hash = sha1(bencode.bdecode(result.content)["info"]).hexdigest()
torrent_hash = sha1(bencode(info)).hexdigest()
return torrent_hash return torrent_hash

View File

@ -75,34 +75,6 @@ class rTorrentAPI(GenericClient):
except: except:
return False 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): def _add_torrent_file(self, result):
filedata = None filedata = None

View File

@ -29,8 +29,9 @@ class uTorrentAPI(GenericClient):
self.url = self.host + 'gui/' self.url = self.host + 'gui/'
def _request(self, method='get', params={}, files=None): def _request(self, method='get', params=None, files=None):
if not params: params = {}
params.update({'token':self.auth}) params.update({'token':self.auth})
return super(uTorrentAPI, self)._request(method=method, params=params, files=files) return super(uTorrentAPI, self)._request(method=method, params=params, files=files)

View File

@ -174,7 +174,7 @@ def change_VERSION_NOTIFY(version_notify):
sickbeard.VERSION_NOTIFY = version_notify sickbeard.VERSION_NOTIFY = version_notify
if version_notify == False: if not version_notify:
sickbeard.NEWEST_VERSION_STRING = None sickbeard.NEWEST_VERSION_STRING = None
if oldSetting == False and version_notify == True: if oldSetting == False and version_notify == True:
@ -265,7 +265,7 @@ def clean_url(url):
url = 'http://' + url url = 'http://' + url
if not url.endswith('/'): if not url.endswith('/'):
url = url + '/' url += '/'
else: else:
url = '' url = ''

View File

@ -205,7 +205,7 @@ class AddSizeAndSceneNameFields(InitialSchema):
except InvalidNameException: except InvalidNameException:
continue continue
if parse_result.series_name and parse_result.season_number != None and parse_result.episode_numbers and parse_result.release_group: if parse_result.series_name and parse_result.season_number is not 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 # 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"]]) self.connection.action("UPDATE tv_episodes SET release_name = ? WHERE episode_id = ?", [cur_name, ep_results[0]["episode_id"]])
break break
@ -312,16 +312,16 @@ class Add1080pAndRawHDQualities(AddIMDbInfo):
result = old_quality result = old_quality
# move fullhdbluray from 1<<5 to 1<<8 if set # move fullhdbluray from 1<<5 to 1<<8 if set
if(result & (1<<5)): if(result & (1<<5)):
result = result & ~(1<<5) result &= ~(1 << 5)
result = result | (1<<8) result |= 1 << 8
# move hdbluray from 1<<4 to 1<<7 if set # move hdbluray from 1<<4 to 1<<7 if set
if(result & (1<<4)): if(result & (1<<4)):
result = result & ~(1<<4) result &= ~(1 << 4)
result = result | (1<<7) result |= 1 << 7
# move hdwebdl from 1<<3 to 1<<5 if set # move hdwebdl from 1<<3 to 1<<5 if set
if(result & (1<<3)): if(result & (1<<3)):
result = result & ~(1<<3) result &= ~(1 << 3)
result = result | (1<<5) result |= 1 << 5
return result return result

View File

@ -70,7 +70,7 @@ class DBConnection:
with db_lock: with db_lock:
if query == None: if query is None:
return return
sqlResult = None sqlResult = None
@ -78,7 +78,7 @@ class DBConnection:
while attempt < 5: while attempt < 5:
try: try:
if args == None: if args is None:
logger.log(self.filename + ": " + query, logger.DB) logger.log(self.filename + ": " + query, logger.DB)
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.execute(query) cursor.execute(query)
@ -109,7 +109,7 @@ class DBConnection:
with db_lock: with db_lock:
if querylist == None: if querylist is None:
return return
sqlResult = [] sqlResult = []
@ -153,7 +153,7 @@ class DBConnection:
with db_lock: with db_lock:
if query == None: if query is None:
return return
sqlResult = None sqlResult = None
@ -161,7 +161,7 @@ class DBConnection:
while attempt < 5: while attempt < 5:
try: try:
if args == None: if args is None:
logger.log(self.filename + ": " + query, logger.DB) logger.log(self.filename + ": " + query, logger.DB)
sqlResult = self.connection.execute(query) sqlResult = self.connection.execute(query)
else: else:
@ -189,7 +189,7 @@ class DBConnection:
sqlResults = self.action(query, args).fetchall() sqlResults = self.action(query, args).fetchall()
if sqlResults == None: if sqlResults is None:
return [] return []
return sqlResults return sqlResults

View File

@ -38,13 +38,11 @@ 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) 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
return None
def fixListEncodings(x): def fixListEncodings(x):
if type(x) != list and type(x) != tuple: if type(x) != list and type(x) != tuple:
return x return x
else: else:
return filter(lambda x: x != None, map(fixStupidEncodings, x)) return filter(lambda x: x is not None, map(fixStupidEncodings, x))
def callPeopleStupid(x): def callPeopleStupid(x):
try: try:

View File

@ -58,10 +58,10 @@ class GenericQueue(object):
def run(self): def run(self):
# only start a new task if one isn't already going # only start a new task if one isn't already going
if self.thread == None or self.thread.isAlive() == False: if self.thread is None or self.thread.isAlive() == False:
# if the thread is dead then the current item should be finished # if the thread is dead then the current item should be finished
if self.currentItem != None: if self.currentItem is not None:
self.currentItem.finish() self.currentItem.finish()
self.currentItem = None self.currentItem = None

View File

@ -46,7 +46,7 @@ def logSnatch(searchResult):
quality = searchResult.quality quality = searchResult.quality
providerClass = searchResult.provider providerClass = searchResult.provider
if providerClass != None: if providerClass is not None:
provider = providerClass.name provider = providerClass.name
else: else:
provider = "unknown" provider = "unknown"

View File

@ -261,7 +261,7 @@ class ImageCache:
cur_file_name = os.path.abspath(cur_provider.get_poster_path(show_obj)) cur_file_name = os.path.abspath(cur_provider.get_poster_path(show_obj))
cur_file_type = self.which_type(cur_file_name) cur_file_type = self.which_type(cur_file_name)
if cur_file_type == None: if cur_file_type is None:
logger.log(u"Unable to retrieve image type, not using the image from "+str(cur_file_name), logger.WARNING) logger.log(u"Unable to retrieve image type, not using the image from "+str(cur_file_name), logger.WARNING)
continue continue

View File

@ -140,21 +140,21 @@ class GenericMetadata():
def _has_episode_thumb(self, ep_obj): def _has_episode_thumb(self, ep_obj):
location = self.get_episode_thumb_path(ep_obj) location = self.get_episode_thumb_path(ep_obj)
result = location != None and ek.ek(os.path.isfile, location) result = location is not None and ek.ek(os.path.isfile, location)
if location: if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result return result
def _has_season_poster(self, show_obj, season): def _has_season_poster(self, show_obj, season):
location = self.get_season_poster_path(show_obj, season) location = self.get_season_poster_path(show_obj, season)
result = location != None and ek.ek(os.path.isfile, location) result = location is not None and ek.ek(os.path.isfile, location)
if location: if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result return result
def _has_season_banner(self, show_obj, season): def _has_season_banner(self, show_obj, season):
location = self.get_season_banner_path(show_obj, season) location = self.get_season_banner_path(show_obj, season)
result = location != None and ek.ek(os.path.isfile, location) result = location is not None and ek.ek(os.path.isfile, location)
if location: if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG) logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result return result
@ -595,8 +595,6 @@ class GenericMetadata():
else: else:
return False return False
return True
def save_season_banners(self, show_obj, season): def save_season_banners(self, show_obj, season):
""" """
Saves all season banners to disk for the given show. Saves all season banners to disk for the given show.
@ -642,8 +640,6 @@ class GenericMetadata():
else: else:
return False return False
return True
def save_season_all_poster(self, show_obj, which=None): def save_season_all_poster(self, show_obj, which=None):
# use the default season all poster name # use the default season all poster name
poster_path = self.get_season_all_poster_path(show_obj) poster_path = self.get_season_all_poster_path(show_obj)
@ -890,8 +886,8 @@ class GenericMetadata():
with ek.ek(open, metadata_path, 'r') as xmlFileObj: with ek.ek(open, metadata_path, 'r') as xmlFileObj:
showXML = etree.ElementTree(file=xmlFileObj) showXML = etree.ElementTree(file=xmlFileObj)
if showXML.findtext('title') == None\ if showXML.findtext('title') is None \
or (showXML.findtext('tvdbid') == None and showXML.findtext('id') == None): or (showXML.findtext('tvdbid') is None and showXML.findtext('id') is None):
logger.log(u"Invalid info in tvshow.nfo (missing name or id):" \ logger.log(u"Invalid info in tvshow.nfo (missing name or id):" \
+ str(showXML.findtext('title')) + " " \ + str(showXML.findtext('title')) + " " \
+ str(showXML.findtext('indexer')) + " " \ + str(showXML.findtext('indexer')) + " " \
@ -901,9 +897,9 @@ class GenericMetadata():
name = showXML.findtext('title') name = showXML.findtext('title')
indexer = showXML.findtext('indexer') indexer = showXML.findtext('indexer')
if showXML.findtext('tvdbid') != None: if showXML.findtext('tvdbid') is not None:
indexer_id = int(showXML.findtext('tvdbid')) indexer_id = int(showXML.findtext('tvdbid'))
elif showXML.findtext('id') != None: elif showXML.findtext('id') is not None:
indexer_id = int(showXML.findtext('id')) indexer_id = int(showXML.findtext('id'))
else: else:
logger.log(u"Empty <id> or <tvdbid> field in NFO, unable to find a ID", logger.WARNING) logger.log(u"Empty <id> or <tvdbid> field in NFO, unable to find a ID", logger.WARNING)

View File

@ -24,11 +24,11 @@ def getShowImage(url, imgNum=None):
image_data = None # @UnusedVariable image_data = None # @UnusedVariable
if url == None: if url is None:
return None return None
# if they provided a fanart number try to use it instead # if they provided a fanart number try to use it instead
if imgNum != None: if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg" tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg"
else: else:
tempURL = url tempURL = url

View File

@ -261,7 +261,7 @@ class MediaBrowserMetadata(generic.GenericMetadata):
indexerid.text = myShow['id'] indexerid.text = myShow['id']
indexer = etree.SubElement(tv_node, "indexer") indexer = etree.SubElement(tv_node, "indexer")
if show_obj.indexer != None: if show_obj.indexer is not None:
indexer.text = show_obj.indexer indexer.text = show_obj.indexer
SeriesName = etree.SubElement(tv_node, "SeriesName") SeriesName = etree.SubElement(tv_node, "SeriesName")
@ -363,7 +363,7 @@ class MediaBrowserMetadata(generic.GenericMetadata):
cur_actor_type.text = "Actor" cur_actor_type.text = "Actor"
cur_actor_role = etree.SubElement(cur_actor, "Role") cur_actor_role = etree.SubElement(cur_actor, "Role")
cur_actor_role_text = actor['role'] cur_actor_role_text = actor['role']
if cur_actor_role_text != None: if cur_actor_role_text is not None:
cur_actor_role.text = cur_actor_role_text cur_actor_role.text = cur_actor_role_text
helpers.indentXML(tv_node) helpers.indentXML(tv_node)
@ -433,7 +433,7 @@ class MediaBrowserMetadata(generic.GenericMetadata):
episode = rootNode episode = rootNode
EpisodeName = etree.SubElement(episode, "EpisodeName") EpisodeName = etree.SubElement(episode, "EpisodeName")
if curEpToWrite.name != None: if curEpToWrite.name is not None:
EpisodeName.text = curEpToWrite.name EpisodeName.text = curEpToWrite.name
else: else:
EpisodeName.text = "" EpisodeName.text = ""
@ -462,7 +462,7 @@ class MediaBrowserMetadata(generic.GenericMetadata):
MetadataType.text = "Episode" MetadataType.text = "Episode"
Overview = etree.SubElement(episode, "Overview") Overview = etree.SubElement(episode, "Overview")
if curEpToWrite.description != None: if curEpToWrite.description is not None:
Overview.text = curEpToWrite.description Overview.text = curEpToWrite.description
else: else:
Overview.text = "" Overview.text = ""
@ -471,7 +471,7 @@ class MediaBrowserMetadata(generic.GenericMetadata):
Rating = etree.SubElement(episode, "Rating") Rating = etree.SubElement(episode, "Rating")
if getattr(myEp, 'rating', None) is not None: if getattr(myEp, 'rating', None) is not None:
rating_text = myEp['rating'] rating_text = myEp['rating']
if rating_text != None: if rating_text is not None:
Rating.text = rating_text Rating.text = rating_text
IMDB_ID = etree.SubElement(episode, "IMDB_ID") IMDB_ID = etree.SubElement(episode, "IMDB_ID")

View File

@ -229,7 +229,7 @@ class WDTVMetadata(generic.GenericMetadata):
seriesName.text = myShow["seriesname"] seriesName.text = myShow["seriesname"]
episodeName = etree.SubElement(episode, "episode_name") episodeName = etree.SubElement(episode, "episode_name")
if curEpToWrite.name != None: if curEpToWrite.name is not None:
episodeName.text = curEpToWrite.name episodeName.text = curEpToWrite.name
seasonNumber = etree.SubElement(episode, "season_number") seasonNumber = etree.SubElement(episode, "season_number")
@ -264,7 +264,7 @@ class WDTVMetadata(generic.GenericMetadata):
director = etree.SubElement(episode, "director") director = etree.SubElement(episode, "director")
if getattr(myEp, 'director', None) is not None: if getattr(myEp, 'director', None) is not None:
director_text = myEp['director'] director_text = myEp['director']
if director_text != None: if director_text is not None:
director.text = director_text director.text = director_text
if getattr(myShow, '_actors', None) is not None: if getattr(myShow, '_actors', None) is not None:
@ -274,11 +274,11 @@ class WDTVMetadata(generic.GenericMetadata):
cur_actor_name.text = actor['name'] cur_actor_name.text = actor['name']
cur_actor_role = etree.SubElement(cur_actor, "role") cur_actor_role = etree.SubElement(cur_actor, "role")
cur_actor_role_text = actor['role'] cur_actor_role_text = actor['role']
if cur_actor_role_text != None: if cur_actor_role_text is not None:
cur_actor_role.text = cur_actor_role_text cur_actor_role.text = cur_actor_role_text
overview = etree.SubElement(episode, "overview") overview = etree.SubElement(episode, "overview")
if curEpToWrite.description != None: if curEpToWrite.description is not None:
overview.text = curEpToWrite.description overview.text = curEpToWrite.description
# Make it purdy # Make it purdy

View File

@ -193,12 +193,12 @@ class XBMC_12PlusMetadata(generic.GenericMetadata):
cur_actor_role = etree.SubElement(cur_actor, "role") cur_actor_role = etree.SubElement(cur_actor, "role")
cur_actor_role_text = actor['role'] cur_actor_role_text = actor['role']
if cur_actor_role_text != None: if cur_actor_role_text is not None:
cur_actor_role.text = cur_actor_role_text cur_actor_role.text = cur_actor_role_text
cur_actor_thumb = etree.SubElement(cur_actor, "thumb") cur_actor_thumb = etree.SubElement(cur_actor, "thumb")
cur_actor_thumb_text = actor['image'] cur_actor_thumb_text = actor['image']
if cur_actor_thumb_text != None: if cur_actor_thumb_text is not None:
cur_actor_thumb.text = cur_actor_thumb_text cur_actor_thumb.text = cur_actor_thumb_text
# Make it purdy # Make it purdy
@ -267,11 +267,11 @@ class XBMC_12PlusMetadata(generic.GenericMetadata):
episode = rootNode episode = rootNode
title = etree.SubElement(episode, "title") title = etree.SubElement(episode, "title")
if curEpToWrite.name != None: if curEpToWrite.name is not None:
title.text = curEpToWrite.name title.text = curEpToWrite.name
showtitle = etree.SubElement(episode, "showtitle") showtitle = etree.SubElement(episode, "showtitle")
if curEpToWrite.show.name != None: if curEpToWrite.show.name is not None:
showtitle.text = curEpToWrite.show.name showtitle.text = curEpToWrite.show.name
season = etree.SubElement(episode, "season") season = etree.SubElement(episode, "season")
@ -290,7 +290,7 @@ class XBMC_12PlusMetadata(generic.GenericMetadata):
aired.text = '' aired.text = ''
plot = etree.SubElement(episode, "plot") plot = etree.SubElement(episode, "plot")
if curEpToWrite.description != None: if curEpToWrite.description is not None:
plot.text = curEpToWrite.description plot.text = curEpToWrite.description
runtime = etree.SubElement(episode, "runtime") runtime = etree.SubElement(episode, "runtime")
@ -301,18 +301,18 @@ class XBMC_12PlusMetadata(generic.GenericMetadata):
displayseason = etree.SubElement(episode, "displayseason") displayseason = etree.SubElement(episode, "displayseason")
if getattr(myEp, 'airsbefore_season', None) is not None: if getattr(myEp, 'airsbefore_season', None) is not None:
displayseason_text = myEp['airsbefore_season'] displayseason_text = myEp['airsbefore_season']
if displayseason_text != None: if displayseason_text is not None:
displayseason.text = displayseason_text displayseason.text = displayseason_text
displayepisode = etree.SubElement(episode, "displayepisode") displayepisode = etree.SubElement(episode, "displayepisode")
if getattr(myEp, 'airsbefore_episode', None) is not None: if getattr(myEp, 'airsbefore_episode', None) is not None:
displayepisode_text = myEp['airsbefore_episode'] displayepisode_text = myEp['airsbefore_episode']
if displayepisode_text != None: if displayepisode_text is not None:
displayepisode.text = displayepisode_text displayepisode.text = displayepisode_text
thumb = etree.SubElement(episode, "thumb") thumb = etree.SubElement(episode, "thumb")
thumb_text = getattr(myEp, 'filename', None) thumb_text = getattr(myEp, 'filename', None)
if thumb_text != None: if thumb_text is not None:
thumb.text = thumb_text thumb.text = thumb_text
watched = etree.SubElement(episode, "watched") watched = etree.SubElement(episode, "watched")
@ -320,17 +320,17 @@ class XBMC_12PlusMetadata(generic.GenericMetadata):
credits = etree.SubElement(episode, "credits") credits = etree.SubElement(episode, "credits")
credits_text = getattr(myEp, 'writer', None) credits_text = getattr(myEp, 'writer', None)
if credits_text != None: if credits_text is not None:
credits.text = credits_text credits.text = credits_text
director = etree.SubElement(episode, "director") director = etree.SubElement(episode, "director")
director_text = getattr(myEp, 'director', None) director_text = getattr(myEp, 'director', None)
if director_text != None: if director_text is not None:
director.text = director_text director.text = director_text
rating = etree.SubElement(episode, "rating") rating = etree.SubElement(episode, "rating")
rating_text = getattr(myEp, 'rating', None) rating_text = getattr(myEp, 'rating', None)
if rating_text != None: if rating_text is not None:
rating.text = rating_text rating.text = rating_text
gueststar_text = getattr(myEp, 'gueststars', None) 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 = etree.SubElement(cur_actor, "role")
cur_actor_role_text = actor['role'] cur_actor_role_text = actor['role']
if cur_actor_role_text != None: if cur_actor_role_text is not None:
cur_actor_role.text = cur_actor_role_text cur_actor_role.text = cur_actor_role_text
cur_actor_thumb = etree.SubElement(cur_actor, "thumb") cur_actor_thumb = etree.SubElement(cur_actor, "thumb")
cur_actor_thumb_text = actor['image'] cur_actor_thumb_text = actor['image']
if cur_actor_thumb_text != None: if cur_actor_thumb_text is not None:
cur_actor_thumb.text = cur_actor_thumb_text cur_actor_thumb.text = cur_actor_thumb_text
# Make it purdy # Make it purdy

View File

@ -154,7 +154,7 @@ class NameParser(object):
b = getattr(second, attr) b = getattr(second, attr)
# if a is good use it # if a is good use it
if a != None or (type(a) == list and len(a)): if a is not None or (type(a) == list and len(a)):
return a return a
# if not use b (if b isn't set it'll just be default) # if not use b (if b isn't set it'll just be default)
else: else:
@ -242,7 +242,7 @@ class NameParser(object):
final_result.which_regex += dir_name_result.which_regex final_result.which_regex += dir_name_result.which_regex
# if there's no useful info in it then raise an exception # if there's no useful info in it then raise an exception
if final_result.season_number == None and not final_result.episode_numbers and final_result.air_date == None and not final_result.series_name: 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:
raise InvalidNameException("Unable to parse " + name.encode(sickbeard.SYS_ENCODING, 'xmlcharrefreplace')) raise InvalidNameException("Unable to parse " + name.encode(sickbeard.SYS_ENCODING, 'xmlcharrefreplace'))
name_parser_cache.add(name, final_result) name_parser_cache.add(name, final_result)
@ -363,11 +363,11 @@ class ParseResult(object):
return True return True
def __str__(self): def __str__(self):
if self.series_name != None: if self.series_name is not None:
to_return = self.series_name + u' - ' to_return = self.series_name + u' - '
else: else:
to_return = u'' to_return = u''
if self.season_number != None: if self.season_number is not None:
to_return += 'S'+str(self.season_number) to_return += 'S'+str(self.season_number)
if self.episode_numbers and len(self.episode_numbers): if self.episode_numbers and len(self.episode_numbers):
for e in self.episode_numbers: for e in self.episode_numbers:
@ -386,7 +386,7 @@ class ParseResult(object):
return to_return.encode('utf-8') return to_return.encode('utf-8')
def _is_air_by_date(self): def _is_air_by_date(self):
if self.season_number == None and len(self.episode_numbers) == 0 and self.air_date: if self.season_number is None and len(self.episode_numbers) == 0 and self.air_date:
return True return True
return False return False
air_by_date = property(_is_air_by_date) air_by_date = property(_is_air_by_date)
@ -397,7 +397,7 @@ class ParseResult(object):
tvdb numbering, if necessary. tvdb numbering, if necessary.
""" """
if self.air_by_date: return self # scene numbering does not apply to air-by-date if self.air_by_date: return self # scene numbering does not apply to air-by-date
if self.season_number == None: return self # can't work without a season if self.season_number is None: return self # can't work without a season
if len(self.episode_numbers) == 0: return self # need at least one episode 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) indexer_id = NameParser.series_name_to_indexer_id(self.series_name, True, True, False)

View File

@ -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. Returns true if season folders need to be forced on or false otherwise.
""" """
if pattern == None: if pattern is None:
pattern = sickbeard.NAMING_PATTERN pattern = sickbeard.NAMING_PATTERN
valid = not validate_name(pattern, None, file_only=True) valid = not validate_name(pattern, None, file_only=True)
if multi != None: if multi is not None:
valid = valid or not validate_name(pattern, multi, file_only=True) valid = valid or not validate_name(pattern, multi, file_only=True)
return valid return valid
@ -81,13 +81,13 @@ def check_valid_naming(pattern=None, multi=None):
Returns true if the naming is valid, false if not. Returns true if the naming is valid, false if not.
""" """
if pattern == None: if pattern is None:
pattern = sickbeard.NAMING_PATTERN pattern = sickbeard.NAMING_PATTERN
logger.log(u"Checking whether the pattern "+pattern+" is valid for a single episode", logger.DEBUG) logger.log(u"Checking whether the pattern "+pattern+" is valid for a single episode", logger.DEBUG)
valid = validate_name(pattern, None) valid = validate_name(pattern, None)
if multi != None: if multi is not None:
logger.log(u"Checking whether the pattern "+pattern+" is valid for a multi episode", logger.DEBUG) logger.log(u"Checking whether the pattern "+pattern+" is valid for a multi episode", logger.DEBUG)
valid = valid and validate_name(pattern, multi) 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. Returns true if the naming is valid, false if not.
""" """
if pattern == None: if pattern is None:
pattern = sickbeard.NAMING_PATTERN pattern = sickbeard.NAMING_PATTERN
logger.log(u"Checking whether the pattern "+pattern+" is valid for an air-by-date episode", logger.DEBUG) 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: else:
ep._release_name = 'Show.Name.S02E03.HDTV.XviD-RLSGROUP' ep._release_name = 'Show.Name.S02E03.HDTV.XviD-RLSGROUP'
if multi != None: if multi is not None:
ep._name = "Ep Name (1)" ep._name = "Ep Name (1)"
ep._release_name = 'Show.Name.S02E03E04E05.HDTV.XviD-RLSGROUP' ep._release_name = 'Show.Name.S02E03E04E05.HDTV.XviD-RLSGROUP'

View File

@ -52,7 +52,7 @@ class BoxcarNotifier:
# if this is a subscription notification then act accordingly # if this is a subscription notification then act accordingly
if subscribe: if subscribe:
data = urllib.urlencode({'email': email}) data = urllib.urlencode({'email': email})
curUrl = curUrl + "/subscribe" curUrl += "/subscribe"
# for normal requests we need all these parameters # for normal requests we need all these parameters
else: else:

View File

@ -32,145 +32,145 @@ from sickbeard import db
from sickbeard.exceptions import ex from sickbeard.exceptions import ex
class EmailNotifier: class EmailNotifier:
def __init__(self): def __init__(self):
self.last_err = None 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 notify_snatch(self, ep_name, title="Snatched:"): 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.')
Send a notification that an episode was snatched msg['Subject'] = 'Sick Beard: Test Message'
msg['From'] = smtp_from
ep_name: The name of the episode that was snatched msg['To'] = to
title: The title of the notification (optional) return self._sendmail(host, port, smtp_from, use_tls, user, pwd, [to], msg, True)
"""
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("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Snatched</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", '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_download(self, ep_name, title="Completed:"): def notify_snatch(self, ep_name, title="Snatched:"):
""" """
Send a notification that an episode was downloaded Send a notification that an episode was snatched
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("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Downloaded</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", '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:"): ep_name: The name of the episode that was snatched
""" title: The title of the notification (optional)
Send a notification that an subtitle was downloaded """
if sickbeard.EMAIL_NOTIFY_ONSNATCH:
ep_name: The name of the episode that was downloaded show = self._parseEp(ep_name)
lang: Subtitle language wanted to = self._generate_recepients(show)
""" if len(to) == 0:
if sickbeard.EMAIL_NOTIFY_ONSUBTITLEDOWNLOAD: logger.log('Skipping email notify because there are no configured recepients', logger.WARNING)
show = self._parseEp(ep_name) else:
to = self._generate_recepients(show) try:
if len(to) == 0: msg = MIMEMultipart('alternative')
logger.log('Skipping email notify because there are no configured recepients', logger.WARNING) msg.attach(MIMEText("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Snatched</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", 'html'))
else: except:
try: msg = MIMEText(ep_name)
msg = MIMEMultipart('alternative')
msg.attach(MIMEText("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Subtitle Downloaded</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n<p>Language: <b>" + lang + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", '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): msg['Subject'] = 'Snatched: ' + ep_name
addrs = [] 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)
# Grab the global recipients def notify_download(self, ep_name, title="Completed:"):
for addr in sickbeard.EMAIL_LIST.split(','): """
if(len(addr.strip()) > 0): Send a notification that an episode was downloaded
addrs.append(addr)
# Grab the recipients for the show ep_name: The name of the episode that was downloaded
mydb = db.DBConnection() title: The title of the notification (optional)
for s in show: """
for subs in mydb.select("SELECT notify_list FROM tv_shows WHERE show_name = ?", (s,)): if sickbeard.EMAIL_NOTIFY_ONDOWNLOAD:
if subs['notify_list']: show = self._parseEp(ep_name)
for addr in subs['notify_list'].split(','): to = self._generate_recepients(show)
if(len(addr.strip()) > 0): if len(to) == 0:
addrs.append(addr) logger.log('Skipping email notify because there are no configured recepients', logger.WARNING)
else:
addrs = set(addrs) try:
logger.log('Notification recepients: %s' % addrs, logger.DEBUG) msg = MIMEMultipart('alternative')
return addrs msg.attach(MIMEText("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Downloaded</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", 'html'))
except:
def _sendmail(self, host, port, smtp_from, use_tls, user, pwd, to, msg, smtpDebug=False): msg = MIMEText(ep_name)
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)) msg['Subject'] = 'Downloaded: ' + ep_name
if smtpDebug: msg['From'] = sickbeard.EMAIL_FROM
srv.set_debuglevel(1) msg['To'] = ','.join(to)
try: if self._sendmail(sickbeard.EMAIL_HOST, sickbeard.EMAIL_PORT, sickbeard.EMAIL_FROM, sickbeard.EMAIL_TLS, sickbeard.EMAIL_USER, sickbeard.EMAIL_PASSWORD, to, msg):
if (use_tls == '1' or use_tls == True) or (len(user) > 0 and len(pwd) > 0): logger.log("Download notification sent to [%s] for '%s'" % (to, ep_name), logger.DEBUG)
srv.ehlo() else:
logger.log('Sent initial EHLO command!', logger.DEBUG) logger.log("Download notification ERROR: %s" % self.last_err, logger.ERROR)
if use_tls == '1' or use_tls == True:
srv.starttls() def notify_subtitle_download(self, ep_name, lang, title="Downloaded subtitle:"):
logger.log('Sent STARTTLS command!', logger.DEBUG) """
if len(user) > 0 and len(pwd) > 0: Send a notification that an subtitle was downloaded
srv.login(user, pwd)
logger.log('Sent LOGIN command!', logger.DEBUG) ep_name: The name of the episode that was downloaded
srv.sendmail(smtp_from, to, msg.as_string()) lang: Subtitle language wanted
srv.quit() """
return True if sickbeard.EMAIL_NOTIFY_ONSUBTITLEDOWNLOAD:
except Exception as e: show = self._parseEp(ep_name)
self.last_err = '%s' % e to = self._generate_recepients(show)
return False 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("<body style='font-family:Helvetica, Arial, sans-serif;'><h3>Sick Beard Notification - Subtitle Downloaded</h3>\n<p>Show: <b>" + re.search("(.+?) -.+", ep_name).group(1) + "</b></p>\n<p>Episode: <b>" + re.search(".+ - (.+?-.+) -.+", ep_name).group(1) + "</b></p>\n<p>Language: <b>" + lang + "</b></p>\n\n<footer style='margin-top: 2.5em; padding: .7em 0; color: #777; border-top: #BBB solid 1px;'>Powered by Sick Beard.</footer></body>", '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
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 notifier = EmailNotifier

View File

@ -88,10 +88,10 @@ class GrowlNotifier:
if not sickbeard.USE_GROWL and not force: if not sickbeard.USE_GROWL and not force:
return False return False
if name == None: if name is None:
name = title name = title
if host == None: if host is None:
hostParts = sickbeard.GROWL_HOST.split(':') hostParts = sickbeard.GROWL_HOST.split(':')
else: else:
hostParts = host.split(':') hostParts = host.split(':')
@ -114,7 +114,7 @@ class GrowlNotifier:
opts['priority'] = None opts['priority'] = None
opts['debug'] = False opts['debug'] = False
if password == None: if password is None:
opts['password'] = sickbeard.GROWL_PASSWORD opts['password'] = sickbeard.GROWL_PASSWORD
else: else:
opts['password'] = password opts['password'] = password
@ -141,7 +141,7 @@ class GrowlNotifier:
def _sendRegistration(self, host=None, password=None, name='Sick Beard Notification'): def _sendRegistration(self, host=None, password=None, name='Sick Beard Notification'):
opts = {} opts = {}
if host == None: if host is None:
hostParts = sickbeard.GROWL_HOST.split(':') hostParts = sickbeard.GROWL_HOST.split(':')
else: else:
hostParts = host.split(':') hostParts = host.split(':')
@ -155,7 +155,7 @@ class GrowlNotifier:
opts['port'] = port opts['port'] = port
if password == None: if password is None:
opts['password'] = sickbeard.GROWL_PASSWORD opts['password'] = sickbeard.GROWL_PASSWORD
else: else:
opts['password'] = password opts['password'] = password

View File

@ -27,10 +27,10 @@ class NMA_Notifier:
if not sickbeard.USE_NMA and not force: if not sickbeard.USE_NMA and not force:
return False return False
if nma_api == None: if nma_api is None:
nma_api = sickbeard.NMA_API nma_api = sickbeard.NMA_API
if nma_priority == None: if nma_priority is None:
nma_priority = sickbeard.NMA_PRIORITY nma_priority = sickbeard.NMA_PRIORITY
logger.log(u"NMA title: " + title, logger.DEBUG) logger.log(u"NMA title: " + title, logger.DEBUG)

View File

@ -65,7 +65,7 @@ class NMJv2Notifier:
xml = parseString(response1) xml = parseString(response1)
time.sleep (300.0 / 1000.0) time.sleep (300.0 / 1000.0)
for node in xml.getElementsByTagName('path'): for node in xml.getElementsByTagName('path'):
xmlTag=node.toxml(); xmlTag=node.toxml()
xmlData=xmlTag.replace('<path>','').replace('</path>','').replace('[=]','') xmlData=xmlTag.replace('<path>','').replace('</path>','').replace('[=]','')
url_db = "http://" + host + ":8008/metadata_database?arg0=check_database&arg1="+ xmlData url_db = "http://" + host + ":8008/metadata_database?arg0=check_database&arg1="+ xmlData
reqdb = urllib2.Request(url_db) reqdb = urllib2.Request(url_db)

View File

@ -53,10 +53,10 @@ class ProwlNotifier:
if not sickbeard.USE_PROWL and not force: if not sickbeard.USE_PROWL and not force:
return False return False
if prowl_api == None: if prowl_api is None:
prowl_api = sickbeard.PROWL_API prowl_api = sickbeard.PROWL_API
if prowl_priority == None: if prowl_priority is None:
prowl_priority = sickbeard.PROWL_PRIORITY prowl_priority = sickbeard.PROWL_PRIORITY

View File

@ -46,7 +46,7 @@ class PushalotNotifier:
if not sickbeard.USE_PUSHALOT and not force: if not sickbeard.USE_PUSHALOT and not force:
return False return False
if pushalot_authorizationtoken == None: if pushalot_authorizationtoken is None:
pushalot_authorizationtoken = sickbeard.PUSHALOT_AUTHORIZATIONTOKEN pushalot_authorizationtoken = sickbeard.PUSHALOT_AUTHORIZATIONTOKEN
logger.log(u"Pushalot event: " + event, logger.DEBUG) logger.log(u"Pushalot event: " + event, logger.DEBUG)

View File

@ -50,9 +50,9 @@ class PushbulletNotifier:
if not sickbeard.USE_PUSHBULLET and not force: if not sickbeard.USE_PUSHBULLET and not force:
return False return False
if pushbullet_api == None: if pushbullet_api is None:
pushbullet_api = sickbeard.PUSHBULLET_API pushbullet_api = sickbeard.PUSHBULLET_API
if pushbullet_device == None: if pushbullet_device is None:
pushbullet_device = sickbeard.PUSHBULLET_DEVICE pushbullet_device = sickbeard.PUSHBULLET_DEVICE
if method == 'POST': if method == 'POST':
@ -70,7 +70,7 @@ class PushbulletNotifier:
authString = base64.encodestring('%s:' % (pushbullet_api)).replace('\n', '') authString = base64.encodestring('%s:' % (pushbullet_api)).replace('\n', '')
if notificationType == None: if notificationType is None:
testMessage = True testMessage = True
try: try:
logger.log(u"Testing Pushbullet authentication and retrieving the device list.", logger.DEBUG) logger.log(u"Testing Pushbullet authentication and retrieving the device list.", logger.DEBUG)

View File

@ -185,8 +185,6 @@ class XBMCNotifier:
logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.DEBUG) logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.DEBUG)
return False return False
return False
############################################################################## ##############################################################################
# Legacy HTTP API (pre XBMC 12) methods # Legacy HTTP API (pre XBMC 12) methods
############################################################################## ##############################################################################
@ -525,7 +523,7 @@ class XBMCNotifier:
return True return True
else: else:
logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.ERROR) logger.log(u"Failed to detect XBMC version for '" + host + "', check configuration and try again.", logger.ERROR)
result = result + 1 result += 1
# needed for the 'update xbmc' submenu command # needed for the 'update xbmc' submenu command
# as it only cares of the final result vs the individual ones # as it only cares of the final result vs the individual ones

View File

@ -124,7 +124,7 @@ def splitResult(result):
return False return False
# bust it up # bust it up
season = parse_result.season_number if parse_result.season_number != None else 1 season = parse_result.season_number if parse_result.season_number is not None else 1
separateNZBs, xmlns = getSeasonNZBs(result.name, urlData, season) separateNZBs, xmlns = getSeasonNZBs(result.name, urlData, season)
@ -143,7 +143,8 @@ def splitResult(result):
return False return False
# make sure the result is sane # make sure the result is sane
if (parse_result.season_number != None and parse_result.season_number != season) or (parse_result.season_number == None and season != 1): if (parse_result.season_number is not None and parse_result.season_number != season) or (
parse_result.season_number is None and season != 1):
logger.log(u"Found " + newNZB + " inside " + result.name + " but it doesn't seem to belong to the same season, ignoring it", logger.WARNING) logger.log(u"Found " + newNZB + " inside " + result.name + " but it doesn't seem to belong to the same season, ignoring it", logger.WARNING)
continue continue
elif len(parse_result.episode_numbers) == 0: elif len(parse_result.episode_numbers) == 0:

View File

@ -39,7 +39,7 @@ def sendNZB(nzb, proper = False):
nzbgetprio = 0 nzbgetprio = 0
nzbgetXMLrpc = "http://%(username)s:%(password)s@%(host)s/xmlrpc" nzbgetXMLrpc = "http://%(username)s:%(password)s@%(host)s/xmlrpc"
if sickbeard.NZBGET_HOST == None: if sickbeard.NZBGET_HOST is None:
logger.log(u"No NZBget host found in configuration. Please configure it.", logger.ERROR) logger.log(u"No NZBget host found in configuration. Please configure it.", logger.ERROR)
return False return False
@ -83,7 +83,7 @@ def sendNZB(nzb, proper = False):
if nzb.resultType == "nzb": if nzb.resultType == "nzb":
genProvider = GenericProvider("") genProvider = GenericProvider("")
data = genProvider.getURL(nzb.url) data = genProvider.getURL(nzb.url)
if (data == None): if (data is None):
return False return False
# if we get a raw data result thats even better # if we get a raw data result thats even better

View File

@ -171,7 +171,7 @@ class PostProcessor(object):
base_name = file_path.rpartition('.')[0] base_name = file_path.rpartition('.')[0]
if not base_name_only: if not base_name_only:
base_name = base_name + '.' base_name += '.'
# don't strip it all and use cwd by accident # don't strip it all and use cwd by accident
if not base_name: if not base_name:
@ -476,10 +476,10 @@ class PostProcessor(object):
# remember whether it's a proper # remember whether it's a proper
if parse_result.extra_info: if parse_result.extra_info:
self.is_proper = re.search('(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) != None self.is_proper = re.search('(^|[\. _-])(proper|repack)([\. _-]|$)', parse_result.extra_info, re.I) is not None
# if the result is complete then remember that for later # if the result is complete then remember that for later
if parse_result.series_name and parse_result.season_number != None and parse_result.episode_numbers and parse_result.release_group: if parse_result.series_name and parse_result.season_number is not None and parse_result.episode_numbers and parse_result.release_group:
test_name = os.path.basename(name) test_name = os.path.basename(name)
if test_name == self.nzb_name: if test_name == self.nzb_name:
self.good_results[self.NZB_NAME] = True 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 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): if cur_indexer_id and not (self.in_history and indexer_id):
indexer_id = cur_indexer_id indexer_id = cur_indexer_id
if cur_season != None: if cur_season is not None:
season = cur_season season = cur_season
if cur_episodes: if cur_episodes:
episodes = cur_episodes episodes = cur_episodes
@ -604,7 +604,7 @@ class PostProcessor(object):
indexer_lang = None indexer_lang = None
try: try:
showObj = helpers.findCertainShow(sickbeard.showList, indexer_id) showObj = helpers.findCertainShow(sickbeard.showList, indexer_id)
if(showObj != None): if(showObj is not None):
# set the language of the show # set the language of the show
indexer_lang = showObj.lang indexer_lang = showObj.lang
self.indexer = showObj.indexer self.indexer = showObj.indexer
@ -636,14 +636,14 @@ class PostProcessor(object):
continue continue
# if there's no season then we can hopefully just use 1 automatically # if there's no season then we can hopefully just use 1 automatically
elif season == None and indexer_id: elif season is None and indexer_id:
myDB = db.DBConnection() myDB = db.DBConnection()
numseasonsSQlResult = myDB.select("SELECT COUNT(DISTINCT season) as numseasons FROM tv_episodes WHERE showid = ? and season != 0", [indexer_id]) 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 == None: if int(numseasonsSQlResult[0][0]) == 1 and season is None:
self._log(u"Don't have a season number, but this show appears to only have 1 season, setting seasonnumber to 1...", logger.DEBUG) 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 season = 1
if indexer_id and season != None and episodes: if indexer_id and season is not None and episodes:
return (indexer_id, season, episodes) return (indexer_id, season, episodes)
return (indexer_id, season, episodes) return (indexer_id, season, episodes)
@ -689,7 +689,7 @@ class PostProcessor(object):
raise exceptions.PostProcessingFailed() raise exceptions.PostProcessingFailed()
# associate all the episodes together under a single root episode # associate all the episodes together under a single root episode
if root_ep == None: if root_ep is None:
root_ep = curEp root_ep = curEp
root_ep.relatedEps = [] root_ep.relatedEps = []
elif curEp not in root_ep.relatedEps: elif curEp not in root_ep.relatedEps:
@ -830,14 +830,14 @@ class PostProcessor(object):
# try to find the file info # try to find the file info
(indexer_id, season, episodes) = self._find_info() (indexer_id, season, episodes) = self._find_info()
if indexer_id and season != None and episodes: if indexer_id and season is not None and episodes:
break break
self._log(u"Can't find show on " + self.indexer + ", auto trying next indexer in list", logger.WARNING) self._log(u"Can't find show on " + self.indexer + ", auto trying next indexer in list", logger.WARNING)
else: else:
(indexer_id, season, episodes) = self._find_info() (indexer_id, season, episodes) = self._find_info()
if not indexer_id or season == None or not episodes: if not indexer_id or season is None or not episodes:
self._log(u"Can't find show id from ANY of the indexers or season or episode, skipping", logger.WARNING) self._log(u"Can't find show id from ANY of the indexers or season or episode, skipping", logger.WARNING)
return False return False

View File

@ -345,11 +345,11 @@ def delete_files(processPath, notwantedFiles):
try: try:
ek.ek(os.chmod,cur_file_path,stat.S_IWRITE) ek.ek(os.chmod,cur_file_path,stat.S_IWRITE)
except OSError, e: except OSError, e:
returnStr += logHelper(u"Cannot change permissions of " + cur_file_path + ': ' + e.strerror, logger.DEBUG) returnStr += logHelper(u"Cannot change permissions of " + cur_file_path + ': ' + str(e.strerror), logger.DEBUG)
try: try:
ek.ek(os.remove, cur_file_path) ek.ek(os.remove, cur_file_path)
except OSError, e: except OSError, e:
returnStr += logHelper(u"Unable to delete file " + cur_file + ': ' + e.strerror, logger.DEBUG) returnStr += logHelper(u"Unable to delete file " + cur_file + ': ' + str(e.strerror), logger.DEBUG)
def delete_dir(processPath): def delete_dir(processPath):

View File

@ -118,7 +118,7 @@ class ProperFinder():
curProper.season = -1 curProper.season = -1
curProper.episode = parse_result.air_date curProper.episode = parse_result.air_date
else: else:
curProper.season = parse_result.season_number if parse_result.season_number != None else 1 curProper.season = parse_result.season_number if parse_result.season_number is not None else 1
curProper.episode = parse_result.episode_numbers[0] curProper.episode = parse_result.episode_numbers[0]
curProper.quality = Quality.nameQuality(curProper.name) curProper.quality = Quality.nameQuality(curProper.name)
@ -236,7 +236,7 @@ class ProperFinder():
# get the episode object # get the episode object
showObj = helpers.findCertainShow(sickbeard.showList, curProper.indexerid) showObj = helpers.findCertainShow(sickbeard.showList, curProper.indexerid)
if showObj == None: if showObj is None:
logger.log(u"Unable to find the show with indexerid " + str(curProper.indexerid) + " so unable to download the proper", logger.ERROR) logger.log(u"Unable to find the show with indexerid " + str(curProper.indexerid) + " so unable to download the proper", logger.ERROR)
continue continue
epObj = showObj.getEpisode(curProper.season, curProper.episode) epObj = showObj.getEpisode(curProper.season, curProper.episode)

View File

@ -128,8 +128,9 @@ class BTNProvider(generic.TorrentProvider):
return [] return []
def _api_call(self, apikey, params={}, results_per_page=1000, offset=0): def _api_call(self, apikey, params=None, results_per_page=1000, offset=0):
if not params: params = {}
server = jsonrpclib.Server('http://api.btnapps.net') server = jsonrpclib.Server('http://api.btnapps.net')
parsedJSON = {} parsedJSON = {}

View File

@ -125,7 +125,7 @@ class GenericProvider:
data = self.getURL(result.url) data = self.getURL(result.url)
if data == None: if data is None:
return False return False
# use the appropriate watch folder # use the appropriate watch folder
@ -323,7 +323,8 @@ class GenericProvider:
if not show.air_by_date: if not show.air_by_date:
# this check is meaningless for non-season searches # this check is meaningless for non-season searches
if (parse_result.season_number != None and parse_result.season_number != season) or (parse_result.season_number == None and season != 1): if (parse_result.season_number is not None and parse_result.season_number != season) or (
parse_result.season_number is None and season != 1):
logger.log(u"The result " + title + " doesn't seem to be a valid episode for season " + str(season) + ", ignoring", logger.DEBUG) logger.log(u"The result " + title + " doesn't seem to be a valid episode for season " + str(season) + ", ignoring", logger.DEBUG)
continue continue

View File

@ -134,7 +134,7 @@ class KATProvider(generic.TorrentProvider):
quality = Quality.sceneQuality(os.path.basename(fileName)) quality = Quality.sceneQuality(os.path.basename(fileName))
if quality != Quality.UNKNOWN: break if quality != Quality.UNKNOWN: break
if fileName!=None and quality == Quality.UNKNOWN: if fileName is not None and quality == Quality.UNKNOWN:
quality = Quality.assumeQuality(os.path.basename(fileName)) quality = Quality.assumeQuality(os.path.basename(fileName))
if quality == Quality.UNKNOWN: if quality == Quality.UNKNOWN:

View File

@ -81,7 +81,7 @@ class NZBsProvider(generic.NZBProvider):
# Pause to avoid 503's # Pause to avoid 503's
time.sleep(5) time.sleep(5)
if data == None: if data is None:
return [] return []
try: try:
@ -126,7 +126,7 @@ class NZBsProvider(generic.NZBProvider):
resultDate = datetime.datetime.strptime(match.group(1), "%a, %d %b %Y %H:%M:%S") resultDate = datetime.datetime.strptime(match.group(1), "%a, %d %b %Y %H:%M:%S")
if date == None or resultDate > date: if date is None or resultDate > date:
results.append(classes.Proper(title, url, resultDate)) results.append(classes.Proper(title, url, resultDate))
return results return results

View File

@ -33,7 +33,7 @@ from sickbeard.exceptions import ex
from lib import requests from lib import requests
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from lib.bencode import bdecode from lib import bencode
class TorrentRssProvider(generic.TorrentProvider): class TorrentRssProvider(generic.TorrentProvider):
@ -116,7 +116,7 @@ class TorrentRssProvider(generic.TorrentProvider):
torrent_file = self.getURL(url) torrent_file = self.getURL(url)
try: try:
bdecode(torrent_file) bencode.bdecode(torrent_file)
except Exception, e: except Exception, e:
self.dumpHTML(torrent_file) self.dumpHTML(torrent_file)
return (False, 'Torrent link is not a valid torrent file: ' + ex(e)) return (False, 'Torrent link is not a valid torrent file: ' + ex(e))

View File

@ -144,7 +144,7 @@ class ThePirateBayProvider(generic.TorrentProvider):
quality = Quality.sceneQuality(os.path.basename(fileName)) quality = Quality.sceneQuality(os.path.basename(fileName))
if quality != Quality.UNKNOWN: break if quality != Quality.UNKNOWN: break
if fileName!=None and quality == Quality.UNKNOWN: if fileName is not None and quality == Quality.UNKNOWN:
quality = Quality.assumeQuality(os.path.basename(fileName)) quality = Quality.assumeQuality(os.path.basename(fileName))
if quality == Quality.UNKNOWN: if quality == Quality.UNKNOWN:
@ -254,7 +254,7 @@ class ThePirateBayProvider(generic.TorrentProvider):
continue continue
#Accept Torrent only from Good People for every Episode Search #Accept Torrent only from Good People for every Episode Search
if sickbeard.THEPIRATEBAY_TRUSTED and re.search('(VIP|Trusted|Helper)',torrent.group(0))== None: if sickbeard.THEPIRATEBAY_TRUSTED and re.search('(VIP|Trusted|Helper)',torrent.group(0)) is 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) 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 continue

View File

@ -43,13 +43,13 @@ def sendNZB(nzb):
# set up a dict with the URL params in it # set up a dict with the URL params in it
params = {} params = {}
if sickbeard.SAB_USERNAME != None: if sickbeard.SAB_USERNAME is not None:
params['ma_username'] = sickbeard.SAB_USERNAME params['ma_username'] = sickbeard.SAB_USERNAME
if sickbeard.SAB_PASSWORD != None: if sickbeard.SAB_PASSWORD is not None:
params['ma_password'] = sickbeard.SAB_PASSWORD params['ma_password'] = sickbeard.SAB_PASSWORD
if sickbeard.SAB_APIKEY != None: if sickbeard.SAB_APIKEY is not None:
params['apikey'] = sickbeard.SAB_APIKEY params['apikey'] = sickbeard.SAB_APIKEY
if sickbeard.SAB_CATEGORY != None: if sickbeard.SAB_CATEGORY is not None:
params['cat'] = sickbeard.SAB_CATEGORY params['cat'] = sickbeard.SAB_CATEGORY
# use high priority if specified (recently aired episode) # use high priority if specified (recently aired episode)
@ -105,7 +105,7 @@ def sendNZB(nzb):
return False return False
# this means we couldn't open the connection or something just as bad # this means we couldn't open the connection or something just as bad
if f == None: if f is None:
logger.log(u"No data returned from SABnzbd, NZB not sent", logger.ERROR) logger.log(u"No data returned from SABnzbd, NZB not sent", logger.ERROR)
return False return False
@ -173,7 +173,7 @@ def _sabURLOpenSimple(url):
except httplib.InvalidURL, e: except httplib.InvalidURL, e:
logger.log(u"Invalid SAB host, check your config: " + ex(e), logger.ERROR) logger.log(u"Invalid SAB host, check your config: " + ex(e), logger.ERROR)
return False, "Invalid SAB host" return False, "Invalid SAB host"
if f == None: if f is None:
logger.log(u"No data returned from SABnzbd", logger.ERROR) logger.log(u"No data returned from SABnzbd", logger.ERROR)
return False, "No data returned from SABnzbd" return False, "No data returned from SABnzbd"
else: else:

View File

@ -45,7 +45,7 @@ class Scheduler:
self.abort = False self.abort = False
def initThread(self): def initThread(self):
if self.thread == None or not self.thread.isAlive(): if self.thread is None or not self.thread.isAlive():
self.thread = threading.Thread(None, self.runAction, self.threadName) self.thread = threading.Thread(None, self.runAction, self.threadName)
def timeLeft(self): def timeLeft(self):

View File

@ -53,7 +53,7 @@ def _downloadResult(result):
newResult = False newResult = False
if resProvider == None: if resProvider is None:
logger.log(u"Invalid provider name - this is a coding error, report it please", logger.ERROR) logger.log(u"Invalid provider name - this is a coding error, report it please", logger.ERROR)
return False return False
@ -143,7 +143,7 @@ def snatchEpisode(result, endStatus=SNATCHED):
logger.log(u"Unknown result type, unable to download it", logger.ERROR) logger.log(u"Unknown result type, unable to download it", logger.ERROR)
dlResult = False dlResult = False
if dlResult == False: if not dlResult:
return False return False
if sickbeard.USE_FAILED_DOWNLOADS: 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") logger.log(cur_result.name + u" has previously failed, rejecting it")
continue continue
if not bestResult or bestResult.quality < cur_result.quality and cur_result.quality != Quality.UNKNOWN: if not bestResult or bestResult.quality < cur_result.quality != Quality.UNKNOWN:
bestResult = cur_result bestResult = cur_result
elif bestResult.quality == cur_result.quality: elif bestResult.quality == cur_result.quality:
if "proper" in cur_result.name.lower() or "repack" in cur_result.name.lower(): if "proper" in cur_result.name.lower() or "repack" in cur_result.name.lower():

View File

@ -75,7 +75,7 @@ class BacklogSearcher:
else: else:
show_list = sickbeard.showList show_list = sickbeard.showList
if self.amActive == True: if self.amActive:
logger.log(u"Backlog is still running, not starting it again", logger.DEBUG) logger.log(u"Backlog is still running, not starting it again", logger.DEBUG)
return return
@ -147,7 +147,7 @@ class BacklogSearcher:
if len(sqlResults) == 0: if len(sqlResults) == 0:
lastBacklog = 1 lastBacklog = 1
elif sqlResults[0]["last_backlog"] == None or sqlResults[0]["last_backlog"] == "": elif sqlResults[0]["last_backlog"] is None or sqlResults[0]["last_backlog"] == "":
lastBacklog = 1 lastBacklog = 1
else: else:
lastBacklog = int(sqlResults[0]["last_backlog"]) lastBacklog = int(sqlResults[0]["last_backlog"])

View File

@ -110,14 +110,14 @@ class ManualSearchQueueItem(generic_queue.QueueItem):
providerModule = foundEpisode.provider providerModule = foundEpisode.provider
if not result: if not result:
ui.notifications.error('Error while attempting to snatch ' + foundEpisode.name+', check your logs') ui.notifications.error('Error while attempting to snatch ' + foundEpisode.name+', check your logs')
elif providerModule == None: elif providerModule is None:
ui.notifications.error('Provider is configured incorrectly, unable to download') ui.notifications.error('Provider is configured incorrectly, unable to download')
self.success = result self.success = result
def finish(self): def finish(self):
# don't let this linger if something goes wrong # don't let this linger if something goes wrong
if self.success == None: if self.success is None:
self.success = False self.success = False
generic_queue.QueueItem.finish(self) 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"]) logger.log(u"ERROR: expected to find a single show matching " + sqlEp["showid"])
return None return None
if show == None: if show is 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) 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 return None

View File

@ -48,7 +48,7 @@ class ShowUpdater():
hour_diff = update_datetime.time().hour - run_updater_time.hour 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 it's less than an interval after the update time then do an update (or if we're forcing it)
if hour_diff >= 0 and hour_diff < self.updateInterval.seconds / 3600 or force: if 0 <= hour_diff < self.updateInterval.seconds / 3600 or force:
logger.log(u"Doing full update on all shows") logger.log(u"Doing full update on all shows")
else: else:
return return

View File

@ -194,12 +194,7 @@ def isGoodResult(name, show, log=True):
escaped_name = re.sub('\\\\[\\s.-]', '\W+', re.escape(curName)) escaped_name = re.sub('\\\\[\\s.-]', '\W+', re.escape(curName))
if show.startyear: if show.startyear:
escaped_name += "(?:\W+" + str(show.startyear) + ")?" escaped_name += "(?:\W+" + str(show.startyear) + ")?"
curRegex = '^' + escaped_name + '\W+(?:(?:S\d[\dE._ -])|' \ 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}.+))'
'(?:\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: if log:
logger.log(u"Checking if show " + name + " matches " + curRegex, logger.DEBUG) logger.log(u"Checking if show " + name + " matches " + curRegex, logger.DEBUG)

View File

@ -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] return show in [x.show for x in self.queue if x.action_id in actions]
def _isBeingSomethinged(self, show, actions): def _isBeingSomethinged(self, show, actions):
return self.currentItem != None and show == self.currentItem.show and \ return self.currentItem is not None and show == self.currentItem.show and \
self.currentItem.action_id in actions self.currentItem.action_id in actions
def isInUpdateQueue(self, show): def isInUpdateQueue(self, show):
@ -75,7 +75,7 @@ class ShowQueue(generic_queue.GenericQueue):
return self._isBeingSomethinged(show, (ShowQueueActions.SUBTITLE,)) return self._isBeingSomethinged(show, (ShowQueueActions.SUBTITLE,))
def _getLoadingShowList(self): def _getLoadingShowList(self):
return [x for x in self.queue + [self.currentItem] if x != None and x.isLoading] return [x for x in self.queue + [self.currentItem] if x is not None and x.isLoading]
loadingShowList = property(_getLoadingShowList) loadingShowList = property(_getLoadingShowList)
@ -205,7 +205,7 @@ class QueueItemAdd(ShowQueueItem):
Returns the show name if there is a show object created, if not returns Returns the show name if there is a show object created, if not returns
the dir that the show is being added to. the dir that the show is being added to.
""" """
if self.show == None: if self.show is None:
return self.showDir return self.showDir
return self.show.name 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 Returns True if we've gotten far enough to have a show object, or False
if we still only know the folder name. if we still only know the folder name.
""" """
if self.show == None: if self.show is None:
return True return True
return False return False
@ -269,9 +269,9 @@ class QueueItemAdd(ShowQueueItem):
# set up initial values # set up initial values
self.show.location = self.showDir self.show.location = self.showDir
self.show.subtitles = self.subtitles if self.subtitles != None else sickbeard.SUBTITLES_DEFAULT self.show.subtitles = self.subtitles if self.subtitles is not None else sickbeard.SUBTITLES_DEFAULT
self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT
self.show.flatten_folders = self.flatten_folders if self.flatten_folders != None else sickbeard.FLATTEN_FOLDERS_DEFAULT self.show.flatten_folders = self.flatten_folders if self.flatten_folders is not None else sickbeard.FLATTEN_FOLDERS_DEFAULT
self.show.paused = False self.show.paused = False
# be smartish about this # be smartish about this
@ -354,7 +354,7 @@ class QueueItemAdd(ShowQueueItem):
self.finish() self.finish()
def _finishEarly(self): def _finishEarly(self):
if self.show != None: if self.show is not None:
self.show.deleteShow() self.show.deleteShow()
self.finish() 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) logger.log(u"Unable to get info from " + self.show.indexer + ", the show info will not be refreshed: " + ex(e), logger.ERROR)
IndexerEpList = None IndexerEpList = None
if IndexerEpList == None: if IndexerEpList is None:
logger.log(u"No data returned from " + self.show.indexer + ", unable to update this show", logger.ERROR) logger.log(u"No data returned from " + self.show.indexer + ", unable to update this show", logger.ERROR)
else: else:

View File

@ -112,7 +112,7 @@ class SubtitlesFinder():
return return
rules = self._getRules() rules = self._getRules()
now = datetime.datetime.now(); now = datetime.datetime.now()
for epToSub in sqlResults: for epToSub in sqlResults:
if not ek.ek(os.path.isfile, epToSub['location']): 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) 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)

View File

@ -86,7 +86,7 @@ class TraktChecker():
Adds a new show with the default settings Adds a new show with the default settings
""" """
showObj = helpers.findCertainShow(sickbeard.showList, int(indexerid)) showObj = helpers.findCertainShow(sickbeard.showList, int(indexerid))
if showObj != None: if showObj is not None:
return return
logger.log(u"Adding show " + indexerid) logger.log(u"Adding show " + indexerid)
root_dirs = sickbeard.ROOT_DIRS.split('|') root_dirs = sickbeard.ROOT_DIRS.split('|')
@ -106,7 +106,7 @@ class TraktChecker():
Sets an episode to wanted, only is it is currently skipped Sets an episode to wanted, only is it is currently skipped
""" """
epObj = show.getEpisode(int(s), int(e)) epObj = show.getEpisode(int(s), int(e))
if epObj == None: if epObj is None:
return return
with epObj.lock: with epObj.lock:
if epObj.status != SKIPPED: if epObj.status != SKIPPED:

View File

@ -88,7 +88,7 @@ class TVShow(object):
self.episodes = {} self.episodes = {}
otherShow = helpers.findCertainShow(sickbeard.showList, self.indexerid) otherShow = helpers.findCertainShow(sickbeard.showList, self.indexerid)
if otherShow != None: if otherShow is not None:
raise exceptions.MultipleShowObjectsException("Can't create a show if it already exists") raise exceptions.MultipleShowObjectsException("Can't create a show if it already exists")
self.loadFromDB() self.loadFromDB()
@ -132,7 +132,7 @@ class TVShow(object):
sql_selection = "SELECT season, episode, " sql_selection = "SELECT season, episode, "
# subselection to detect multi-episodes early, share_location > 0 # subselection to detect multi-episodes early, share_location > 0
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 += " (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) 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()) sql_selection = sql_selection + " AND airdate >= " + str(min_date.toordinal()) + " AND airdate <= " + str(max_date.toordinal())
if has_location: if has_location:
sql_selection = sql_selection + " AND location != '' " sql_selection += " AND location != '' "
# need ORDER episode ASC to rename multi-episodes in order S01E01-02 # need ORDER episode ASC to rename multi-episodes in order S01E01-02
sql_selection = sql_selection + " ORDER BY season ASC, episode ASC" sql_selection += " ORDER BY season ASC, episode ASC"
results = myDB.select(sql_selection) results = myDB.select(sql_selection)
@ -186,18 +186,18 @@ class TVShow(object):
ep = None ep = None
if not episode in self.episodes[season] or self.episodes[season][episode] == None: if not episode in self.episodes[season] or self.episodes[season][episode] is None:
if noCreate: if noCreate:
return None 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) 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 != None: if file is not None:
ep = TVEpisode(self, season, episode, file) ep = TVEpisode(self, season, episode, file)
else: else:
ep = TVEpisode(self, season, episode) ep = TVEpisode(self, season, episode)
if ep != None: if ep is not None:
self.episodes[season][episode] = ep self.episodes[season][episode] = ep
return self.episodes[season][episode] return self.episodes[season][episode]
@ -221,7 +221,7 @@ class TVShow(object):
if sql_result: if sql_result:
last_airdate = datetime.date.fromordinal(sql_result[0]['airdate']) last_airdate = datetime.date.fromordinal(sql_result[0]['airdate'])
if last_airdate >= (update_date - graceperiod) and last_airdate <= (update_date + graceperiod): if (update_date - graceperiod) <= last_airdate <= (update_date + graceperiod):
return True return True
# get next upcoming UNAIRED episode to compare against today + graceperiod # get next upcoming UNAIRED episode to compare against today + graceperiod
@ -329,7 +329,7 @@ class TVShow(object):
curEpisode.release_name = ep_file_name curEpisode.release_name = ep_file_name
# store the reference in the show # store the reference in the show
if curEpisode != None: if curEpisode is not None:
if self.subtitles: if self.subtitles:
try: try:
curEpisode.refreshSubtitles() curEpisode.refreshSubtitles()
@ -382,7 +382,7 @@ class TVShow(object):
try: try:
curEp = self.getEpisode(curSeason, curEpisode) curEp = self.getEpisode(curSeason, curEpisode)
# if we found out that the ep is no longer on TVDB then delete it from our database too # if we found out that the ep is no longer on Indexers then delete it from our database too
if deleteEp: if deleteEp:
curEp.deleteEpisode() curEp.deleteEpisode()
@ -498,7 +498,7 @@ class TVShow(object):
return None return None
# for now lets assume that any episode in the show dir belongs to that show # for now lets assume that any episode in the show dir belongs to that show
season = parse_result.season_number if parse_result.season_number != None else 1 season = parse_result.season_number if parse_result.season_number is not None else 1
episodes = parse_result.episode_numbers episodes = parse_result.episode_numbers
rootEp = None rootEp = None
@ -535,7 +535,7 @@ class TVShow(object):
same_file = False same_file = False
curEp = self.getEpisode(season, episode) curEp = self.getEpisode(season, episode)
if curEp == None: if curEp is None:
try: try:
curEp = self.getEpisode(season, episode, file) curEp = self.getEpisode(season, episode, file)
except exceptions.EpisodeNotFoundException: except exceptions.EpisodeNotFoundException:
@ -559,7 +559,7 @@ class TVShow(object):
curEp.checkForMetaFiles() curEp.checkForMetaFiles()
if rootEp == None: if rootEp is None:
rootEp = curEp rootEp = curEp
else: else:
if curEp not in rootEp.relatedEps: if curEp not in rootEp.relatedEps:
@ -600,7 +600,7 @@ class TVShow(object):
elif oldStatus not in (SNATCHED, SNATCHED_PROPER): elif oldStatus not in (SNATCHED, SNATCHED_PROPER):
newStatus = DOWNLOADED newStatus = DOWNLOADED
if newStatus != None: if newStatus is not None:
with curEp.lock: 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) 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) curEp.status = Quality.compositeStatus(newStatus, newQuality)
@ -817,7 +817,7 @@ class TVShow(object):
params = [self.indexerid, datetime.date.today().toordinal()] + innerParams + [UNAIRED] params = [self.indexerid, datetime.date.today().toordinal()] + innerParams + [UNAIRED]
sqlResults = myDB.select(query, params) sqlResults = myDB.select(query, params)
if sqlResults == None or len(sqlResults) == 0: if sqlResults is None or len(sqlResults) == 0:
logger.log(str(self.indexerid) + u": No episode found... need to implement show status", logger.DEBUG) logger.log(str(self.indexerid) + u": No episode found... need to implement show status", logger.DEBUG)
return [] return []
else: else:
@ -1046,7 +1046,7 @@ class TVShow(object):
elif epStatus in (SNATCHED, SNATCHED_PROPER, SNATCHED_BEST): elif epStatus in (SNATCHED, SNATCHED_PROPER, SNATCHED_BEST):
return Overview.SNATCHED return Overview.SNATCHED
# if they don't want re-downloads then we call it good if they have anything # if they don't want re-downloads then we call it good if they have anything
elif maxBestQuality == None: elif maxBestQuality is None:
return Overview.GOOD return Overview.GOOD
# if they have one but it's not the best they want then mark it as qual # if they have one but it's not the best they want then mark it as qual
elif curQuality < maxBestQuality: elif curQuality < maxBestQuality:
@ -1236,14 +1236,14 @@ class TVEpisode(object):
pass pass
# if we tried loading it from NFO and didn't find the NFO, try the Indexers # if we tried loading it from NFO and didn't find the NFO, try the Indexers
if self.hasnfo == False: if not self.hasnfo:
try: try:
result = self.loadFromIndexer(season, episode) result = self.loadFromIndexer(season, episode)
except exceptions.EpisodeDeletedException: except exceptions.EpisodeDeletedException:
result = False result = False
# if we failed SQL *and* NFO, Indexers then fail # if we failed SQL *and* NFO, Indexers then fail
if result == False: if not result:
raise exceptions.EpisodeNotFoundException("Couldn't find episode " + str(season) + "x" + str(episode)) raise exceptions.EpisodeNotFoundException("Couldn't find episode " + str(season) + "x" + str(episode))
def loadFromDB(self, season, episode): def loadFromDB(self, season, episode):
@ -1346,7 +1346,7 @@ class TVEpisode(object):
if getattr(myEp, 'episodename', None) is None: 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 + "") logger.log(u"This episode (" + self.show.name + " - " + str(season) + "x" + str(episode) + ") has no name on " + self.indexer + "")
# if I'm incomplete on TVDB but I once was complete then just delete myself from the DB for now # if I'm incomplete on Indexers but I once was complete then just delete myself from the DB for now
if self.indexerid != -1: if self.indexerid != -1:
self.deleteEpisode() self.deleteEpisode()
return False return False
@ -1367,7 +1367,7 @@ class TVEpisode(object):
self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2]) self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2])
except ValueError: except ValueError:
logger.log(u"Malformed air date retrieved from " + self.indexer + " ("+self.show.name+" - "+str(season)+"x"+str(episode)+")", logger.ERROR) 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 TVDB but I once was complete then just delete myself from the DB for now # if I'm incomplete on Indexers but I once was complete then just delete myself from the DB for now
if self.indexerid != -1: if self.indexerid != -1:
self.deleteEpisode() self.deleteEpisode()
return False return False
@ -1607,7 +1607,7 @@ class TVEpisode(object):
myDB.upsert("tv_episodes", newValueDict, controlValueDict) myDB.upsert("tv_episodes", newValueDict, controlValueDict)
def fullPath(self): def fullPath(self):
if self.location == None or self.location == "": if self.location is None or self.location == "":
return None return None
else: else:
return ek.ek(os.path.join, self.show.location, self.location) return ek.ek(os.path.join, self.show.location, self.location)
@ -1648,7 +1648,7 @@ class TVEpisode(object):
singleName = False singleName = False
break break
if curGoodName == None: if curGoodName is None:
curGoodName = match.group(1) curGoodName = match.group(1)
elif curGoodName != match.group(1): elif curGoodName != match.group(1):
singleName = False singleName = False
@ -1754,10 +1754,10 @@ class TVEpisode(object):
Manipulates an episode naming pattern and then fills the template in Manipulates an episode naming pattern and then fills the template in
""" """
if pattern == None: if pattern is None:
pattern = sickbeard.NAMING_PATTERN pattern = sickbeard.NAMING_PATTERN
if multi == None: if multi is None:
multi = sickbeard.NAMING_MULTI_EP multi = sickbeard.NAMING_MULTI_EP
replace_map = self._replace_map() replace_map = self._replace_map()
@ -1892,7 +1892,7 @@ class TVEpisode(object):
Just the folder name of the episode Just the folder name of the episode
""" """
if pattern == None: if pattern is None:
# we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep # 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: if self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and not self.relatedEps:
pattern = sickbeard.NAMING_ABD_PATTERN pattern = sickbeard.NAMING_ABD_PATTERN
@ -1912,7 +1912,7 @@ class TVEpisode(object):
Just the filename of the episode, formatted based on the naming settings Just the filename of the episode, formatted based on the naming settings
""" """
if pattern == None: if pattern is None:
# we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep # 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: if self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and not self.relatedEps:
pattern = sickbeard.NAMING_ABD_PATTERN pattern = sickbeard.NAMING_ABD_PATTERN
@ -1967,17 +1967,17 @@ class TVEpisode(object):
# move related files # move related files
for cur_related_file in 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) cur_result = helpers.rename_ep_file(cur_related_file, absolute_proper_path, absolute_current_path_no_ext_length)
if cur_result == False: if not cur_result:
logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_file, logger.ERROR) logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_file, logger.ERROR)
for cur_related_sub in related_subs: 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) cur_result = helpers.rename_ep_file(cur_related_sub, absolute_proper_subs_path, absolute_current_path_no_ext_length)
if cur_result == False: if not cur_result:
logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_sub, logger.ERROR) logger.log(str(self.indexerid) + u": Unable to rename file " + cur_related_sub, logger.ERROR)
# save the ep # save the ep
with self.lock: with self.lock:
if result != False: if result:
self.location = absolute_proper_path + file_ext self.location = absolute_proper_path + file_ext
for relEp in self.relatedEps: for relEp in self.relatedEps:
relEp.location = absolute_proper_path + file_ext relEp.location = absolute_proper_path + file_ext

View File

@ -195,14 +195,16 @@ class TVCache():
def shouldUpdate(self): def shouldUpdate(self):
# if we've updated recently then skip the update # if we've updated recently then skip the update
if datetime.datetime.today() - self.lastUpdate < datetime.timedelta(minutes=self.minTime): 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) 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 False
return True return True
def _addCacheEntry(self, name, url, season=None, episodes=None, indexer_id=0, quality=None, extraNames=[]): def _addCacheEntry(self, name, url, season=None, episodes=None, indexer_id=0, quality=None, extraNames=None):
if not extraNames: extraNames = []
myDB = self._getDB() myDB = self._getDB()
parse_result = None parse_result = None
@ -246,7 +248,7 @@ class TVCache():
indexer_id = name_cache.retrieveNameFromCache(parse_result.series_name) 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 # remember if the cache lookup worked or not so we know whether we should bother updating it later
if indexer_id == None: if indexer_id is None:
logger.log(u"No cache results returned, continuing on with the search", logger.DEBUG) logger.log(u"No cache results returned, continuing on with the search", logger.DEBUG)
from_cache = False from_cache = False
else: else:
@ -254,7 +256,7 @@ class TVCache():
from_cache = True from_cache = True
# if the cache failed, try looking up the show name in the database # if the cache failed, try looking up the show name in the database
if indexer_id == None: if indexer_id is None:
logger.log(u"Trying to look the show up in the show database", logger.DEBUG) logger.log(u"Trying to look the show up in the show database", logger.DEBUG)
showResult = helpers.searchDBForShow(parse_result.series_name) showResult = helpers.searchDBForShow(parse_result.series_name)
if showResult: if showResult:
@ -262,7 +264,7 @@ class TVCache():
indexer_id = showResult[1] indexer_id = showResult[1]
# if the DB lookup fails then do a comprehensive regex search # if the DB lookup fails then do a comprehensive regex search
if indexer_id == None: if indexer_id is None:
logger.log(u"Couldn't figure out a show name straight from the DB, trying a regex search instead", logger.DEBUG) 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: for curShow in sickbeard.showList:
if show_name_helpers.isGoodResult(name, curShow, False): if show_name_helpers.isGoodResult(name, curShow, False):
@ -276,7 +278,7 @@ class TVCache():
name_cache.addNameToCache(parse_result.series_name, indexer_id) 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 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 == None: if indexer_id is None:
indexer_id = 0 indexer_id = 0
# if we found the show then retrieve the show object # if we found the show then retrieve the show object
@ -291,7 +293,7 @@ class TVCache():
# if we weren't provided with season/episode information then get it from the name that we parsed # if we weren't provided with season/episode information then get it from the name that we parsed
if not season: if not season:
season = parse_result.season_number if parse_result.season_number != None else 1 season = parse_result.season_number if parse_result.season_number is not None else 1
if not episodes: if not episodes:
episodes = parse_result.episode_numbers episodes = parse_result.episode_numbers
@ -300,7 +302,7 @@ class TVCache():
try: try:
lINDEXER_API_PARMS = {'indexer': self.indexer} lINDEXER_API_PARMS = {'indexer': self.indexer}
if not (indexer_lang == "" or indexer_lang == "en" or indexer_lang == None): if not (indexer_lang == "" or indexer_lang == "en" or indexer_lang is None):
lINDEXER_API_PARMS['language'] = indexer_lang lINDEXER_API_PARMS['language'] = indexer_lang
t = indexer_api.indexerApi(**lINDEXER_API_PARMS) t = indexer_api.indexerApi(**lINDEXER_API_PARMS)
@ -340,7 +342,7 @@ class TVCache():
sql = "SELECT * FROM [" + self.providerID + "] WHERE name LIKE '%.PROPER.%' OR name LIKE '%.REPACK.%'" sql = "SELECT * FROM [" + self.providerID + "] WHERE name LIKE '%.PROPER.%' OR name LIKE '%.REPACK.%'"
if date != None: if date is not None:
sql += " AND time >= " + str(int(time.mktime(date.timetuple()))) sql += " AND time >= " + str(int(time.mktime(date.timetuple())))
#return filter(lambda x: x['indexerid'] != 0, myDB.select(sql)) #return filter(lambda x: x['indexerid'] != 0, myDB.select(sql))

View File

@ -112,7 +112,8 @@ class Notification(object):
class ProgressIndicator(): class ProgressIndicator():
def __init__(self, percentComplete=0, currentStatus={'title': ''}): def __init__(self, percentComplete=0, currentStatus=None):
if not currentStatus: currentStatus = {'title': ''}
self.percentComplete = percentComplete self.percentComplete = percentComplete
self.currentStatus = currentStatus self.currentStatus = currentStatus
@ -129,7 +130,7 @@ class ProgressIndicators():
# if any of the progress indicators are done take them off the list # if any of the progress indicators are done take them off the list
for curPI in ProgressIndicators._pi[name]: for curPI in ProgressIndicators._pi[name]:
if curPI != None and curPI.percentComplete() == 100: if curPI is not None and curPI.percentComplete() == 100:
ProgressIndicators._pi[name].remove(curPI) ProgressIndicators._pi[name].remove(curPI)
# return the list of progress indicators associated with this name # return the list of progress indicators associated with this name

View File

@ -511,9 +511,6 @@ class GitUpdateManager(UpdateManager):
else: else:
return False return False
return False
class SourceUpdateManager(UpdateManager): class SourceUpdateManager(UpdateManager):
def __init__(self): def __init__(self):

View File

@ -91,7 +91,7 @@ class Api:
logger.log(accessMsg, logger.DEBUG) logger.log(accessMsg, logger.DEBUG)
else: else:
logger.log(accessMsg, logger.WARNING) logger.log(accessMsg, logger.WARNING)
return outputCallbackDict['default'](_responds(RESULT_DENIED, msg=accessMsg)) return outputCallbackDict['default'](_responds(RESULT_DENIED, msg=str(accessMsg)))
# set the original call_dispatcher as the local _call_dispatcher # set the original call_dispatcher as the local _call_dispatcher
_call_dispatcher = call_dispatcher _call_dispatcher = call_dispatcher
@ -171,7 +171,7 @@ class Api:
try: try:
out = json.dumps(dict, indent=self.intent, sort_keys=True) out = json.dumps(dict, indent=self.intent, sort_keys=True)
callback = request.params.get('callback') or request.params.get('jsonp') callback = request.params.get('callback') or request.params.get('jsonp')
if callback != None: if callback is not None:
out = callback + '(' + out + ');' # wrap with JSONP call if requested out = callback + '(' + out + ');' # wrap with JSONP call if requested
except Exception, e: # if we fail to generate the output fake an error except Exception, e: # if we fail to generate the output fake an error
logger.log(u"API :: " + traceback.format_exc(), logger.DEBUG) logger.log(u"API :: " + traceback.format_exc(), logger.DEBUG)
@ -189,7 +189,7 @@ class Api:
else: else:
del kwargs["apikey"] del kwargs["apikey"]
if sickbeard.USE_API != True: if not sickbeard.USE_API:
msg = u"API :: " + remoteIp + " - SB API Disabled. ACCESS DENIED" msg = u"API :: " + remoteIp + " - SB API Disabled. ACCESS DENIED"
return False, msg, args, kwargs return False, msg, args, kwargs
elif apiKey == realKey: elif apiKey == realKey:
@ -223,7 +223,7 @@ def call_dispatcher(args, kwargs):
del kwargs["cmd"] del kwargs["cmd"]
outDict = {} outDict = {}
if cmds != None: if cmds is not None:
cmds = cmds.split("|") cmds = cmds.split("|")
multiCmds = bool(len(cmds) > 1) multiCmds = bool(len(cmds) > 1)
for cmd in cmds: for cmd in cmds:
@ -758,14 +758,14 @@ class CMD_ComingEpisodes(ApiCall):
status = "missed" status = "missed"
elif ep["airdate"] >= next_week: elif ep["airdate"] >= next_week:
status = "later" status = "later"
elif ep["airdate"] >= today and ep["airdate"] < next_week: elif today <= ep["airdate"] < next_week:
if ep["airdate"] == today: if ep["airdate"] == today:
status = "today" status = "today"
else: else:
status = "soon" status = "soon"
# skip unwanted # skip unwanted
if self.type != None and not status in self.type: if self.type is not None and not status in self.type:
continue continue
ordinalAirdate = int(ep["airdate"]) ordinalAirdate = int(ep["airdate"])
@ -878,7 +878,7 @@ class CMD_EpisodeSearch(ApiCall):
sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) #@UndefinedVariable sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) #@UndefinedVariable
# wait until the queue item tells us whether it worked or not # wait until the queue item tells us whether it worked or not
while ep_queue_item.success == None: #@UndefinedVariable while ep_queue_item.success is None: #@UndefinedVariable
time.sleep(1) time.sleep(1)
# return the correct json value # return the correct json value
@ -930,7 +930,7 @@ class CMD_EpisodeSetStatus(ApiCall):
ep_list = [] ep_list = []
if self.e: if self.e:
epObj = showObj.getEpisode(self.s, self.e) epObj = showObj.getEpisode(self.s, self.e)
if epObj == None: if epObj is None:
return _responds(RESULT_FAILURE, msg="Episode not found") return _responds(RESULT_FAILURE, msg="Episode not found")
ep_list = [epObj] ep_list = [epObj]
else: else:
@ -945,7 +945,7 @@ class CMD_EpisodeSetStatus(ApiCall):
start_backlog = False start_backlog = False
ep_segment = None ep_segment = None
for epObj in ep_list: for epObj in ep_list:
if ep_segment == None and self.status == WANTED: if ep_segment is None and self.status == WANTED:
# figure out what segment the episode is in and remember it so we can backlog it # figure out what segment the episode is in and remember it so we can backlog it
if showObj.air_by_date: if showObj.air_by_date:
ep_segment = str(epObj.airdate)[:7] ep_segment = str(epObj.airdate)[:7]
@ -955,7 +955,7 @@ class CMD_EpisodeSetStatus(ApiCall):
with epObj.lock: with epObj.lock:
# don't let them mess up UNAIRED episodes # don't let them mess up UNAIRED episodes
if epObj.status == UNAIRED: if epObj.status == UNAIRED:
if self.e != None: # setting the status of a unaired is only considert a failure if we directly wanted this episode, but is ignored on a season request 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
ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is UNAIRED")) ep_results.append(_epResult(RESULT_FAILURE, epObj, "Refusing to change status because it is UNAIRED"))
failure = True failure = True
continue continue
@ -1051,7 +1051,7 @@ class CMD_Exceptions(ApiCall):
""" display scene exceptions for all or a given show """ """ display scene exceptions for all or a given show """
myDB = db.DBConnection("cache.db", row_type="dict") myDB = db.DBConnection("cache.db", row_type="dict")
if self.indexerid == None: if self.indexerid is None:
sqlResults = myDB.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions") sqlResults = myDB.select("SELECT show_name, indexer_id AS 'indexerid' FROM scene_exceptions")
scene_exceptions = {} scene_exceptions = {}
for row in sqlResults: for row in sqlResults:
@ -1455,7 +1455,7 @@ class CMD_SickBeardPauseBacklog(ApiCall):
def run(self): def run(self):
""" pause the backlog search """ """ pause the backlog search """
if self.pause == True: if self.pause:
sickbeard.searchQueueScheduler.action.pause_backlog() #@UndefinedVariable sickbeard.searchQueueScheduler.action.pause_backlog() #@UndefinedVariable
return _responds(RESULT_SUCCESS, msg="Backlog paused") return _responds(RESULT_SUCCESS, msg="Backlog paused")
else: else:
@ -1637,10 +1637,10 @@ class CMD_SickBeardSetDefaults(ApiCall):
raise ApiError("Status Prohibited") raise ApiError("Status Prohibited")
sickbeard.STATUS_DEFAULT = self.status sickbeard.STATUS_DEFAULT = self.status
if self.flatten_folders != None: if self.flatten_folders is not None:
sickbeard.FLATTEN_FOLDERS_DEFAULT = int(self.flatten_folders) sickbeard.FLATTEN_FOLDERS_DEFAULT = int(self.flatten_folders)
if self.future_show_paused != None: if self.future_show_paused is not None:
sickbeard.COMING_EPS_DISPLAY_PAUSED = int(self.future_show_paused) sickbeard.COMING_EPS_DISPLAY_PAUSED = int(self.future_show_paused)
return _responds(RESULT_SUCCESS, msg="Saved defaults") return _responds(RESULT_SUCCESS, msg="Saved defaults")
@ -2064,16 +2064,13 @@ class CMD_ShowPause(ApiCall):
if not showObj: if not showObj:
return _responds(RESULT_FAILURE, msg="Show not found") return _responds(RESULT_FAILURE, msg="Show not found")
if self.pause == True: if self.pause:
showObj.paused = 1 showObj.paused = 1
return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been paused") return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been paused")
else: else:
showObj.paused = 0 showObj.paused = 0
return _responds(RESULT_SUCCESS, msg=str(showObj.name) + " has been unpaused") 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): class CMD_ShowRefresh(ApiCall):
_help = {"desc": "refresh a show in sickbeard", _help = {"desc": "refresh a show in sickbeard",
"requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"}, "requiredParameters": {"indexerid": {"desc": "thetvdb.com unique id of a show"},
@ -2160,7 +2157,7 @@ class CMD_ShowSeasons(ApiCall):
myDB = db.DBConnection(row_type="dict") myDB = db.DBConnection(row_type="dict")
if self.season == None: if self.season is None:
sqlResults = myDB.select("SELECT name, episode, airdate, status, season FROM tv_episodes WHERE showid = ?", [self.indexerid]) sqlResults = myDB.select("SELECT name, episode, airdate, status, season FROM tv_episodes WHERE showid = ?", [self.indexerid])
seasons = {} seasons = {}
for row in sqlResults: for row in sqlResults:
@ -2408,7 +2405,7 @@ class CMD_Shows(ApiCall):
if (len(nextEps) != 0): if (len(nextEps) != 0):
nextAirdate = _ordinal_to_dateForm(nextEps[0].airdate.toordinal()) nextAirdate = _ordinal_to_dateForm(nextEps[0].airdate.toordinal())
if self.paused != None and bool(self.paused) != bool(curShow.paused): if self.paused is not None and bool(self.paused) != bool(curShow.paused):
continue continue
showDict = {"paused": curShow.paused, showDict = {"paused": curShow.paused,

View File

@ -154,17 +154,17 @@ def _genericMessage(subject, message):
def _getEpisode(show, season, episode): def _getEpisode(show, season, episode):
if show == None or season == None or episode == None: if show is None or season is None or episode is None:
return "Invalid parameters" return "Invalid parameters"
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return "Show not in show list" return "Show not in show list"
epObj = showObj.getEpisode(int(season), int(episode)) epObj = showObj.getEpisode(int(season), int(episode))
if epObj == None: if epObj is None:
return "Episode couldn't be retrieved" return "Episode couldn't be retrieved"
return epObj return epObj
@ -177,7 +177,7 @@ def ManageMenu():
{ 'title': 'Episode Status Management', 'path': 'manage/episodeStatuses/' },] { 'title': 'Episode Status Management', 'path': 'manage/episodeStatuses/' },]
if sickbeard.USE_TORRENTS and sickbeard.TORRENT_METHOD != 'blackhole' \ 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:'): or not sickbeard.ENABLE_HTTPS and sickbeard.TORRENT_HOST[:5] == 'http:'):
manageMenu.append({ 'title': 'Manage Torrents', 'path': 'manage/manageTorrents/'}) 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] 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]: 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)) show = sickbeard.helpers.findCertainShow(sickbeard.showList, int(cur_indexer_id))
subtitles = show.getEpisode(int(season), int(episode)).downloadSubtitles() subtitles = show.getEpisode(int(season), int(episode)).downloadSubtitles()
@ -569,9 +569,10 @@ class Manage:
return _munge(t) return _munge(t)
@cherrypy.expose @cherrypy.expose
def massEditSubmit(self, paused=None, flatten_folders=None, quality_preset=False, subtitles=None, def massEditSubmit(self, paused=None, flatten_folders=None, quality_preset=False, subtitles=None, anyQualities=[],
anyQualities=[], bestQualities=[], toEdit=None, *args, **kwargs): bestQualities=None, toEdit=None, *args, **kwargs):
if not bestQualities: bestQualities = []
dir_map = {} dir_map = {}
for cur_arg in kwargs: for cur_arg in kwargs:
if not cur_arg.startswith('orig_root_dir_'): if not cur_arg.startswith('orig_root_dir_'):
@ -635,32 +636,32 @@ class Manage:
@cherrypy.expose @cherrypy.expose
def massUpdate(self, toUpdate=None, toRefresh=None, toRename=None, toDelete=None, toMetadata=None, toSubtitle=None): def massUpdate(self, toUpdate=None, toRefresh=None, toRename=None, toDelete=None, toMetadata=None, toSubtitle=None):
if toUpdate != None: if toUpdate is not None:
toUpdate = toUpdate.split('|') toUpdate = toUpdate.split('|')
else: else:
toUpdate = [] toUpdate = []
if toRefresh != None: if toRefresh is not None:
toRefresh = toRefresh.split('|') toRefresh = toRefresh.split('|')
else: else:
toRefresh = [] toRefresh = []
if toRename != None: if toRename is not None:
toRename = toRename.split('|') toRename = toRename.split('|')
else: else:
toRename = [] toRename = []
if toSubtitle != None: if toSubtitle is not None:
toSubtitle = toSubtitle.split('|') toSubtitle = toSubtitle.split('|')
else: else:
toSubtitle = [] toSubtitle = []
if toDelete != None: if toDelete is not None:
toDelete = toDelete.split('|') toDelete = toDelete.split('|')
else: else:
toDelete = [] toDelete = []
if toMetadata != None: if toMetadata is not None:
toMetadata = toMetadata.split('|') toMetadata = toMetadata.split('|')
else: else:
toMetadata = [] toMetadata = []
@ -678,7 +679,7 @@ class Manage:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(curShowID)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(curShowID))
if showObj == None: if showObj is None:
continue continue
if curShowID in toDelete: if curShowID in toDelete:
@ -761,7 +762,7 @@ class Manage:
t.webui_url = '/'.join(s.strip('/') for s in (t.webui_url, 'gui/')) t.webui_url = '/'.join(s.strip('/') for s in (t.webui_url, 'gui/'))
if sickbeard.TORRENT_METHOD == 'download_station': if sickbeard.TORRENT_METHOD == 'download_station':
if helpers.check_url(t.webui_url + 'download/'): if helpers.check_url(t.webui_url + 'download/'):
t.webui_url = t.webui_url + 'download/' t.webui_url += 'download/'
else: else:
t.info_download_station = '<p>To have a better experience please set the Download Station alias as <code>download</code>, you can check this setting in the Synology DSM <b>Control Panel</b> > <b>Application Portal</b>. Make sure you allow DSM to be embedded with iFrames too in <b>Control Panel</b> > <b>DSM Settings</b> > <b>Security</b>.</p><br/><p>There is more information about this available <a href="https://github.com/echel0n/SickBeard-TVRage/pull/338">here</a>.</p><br/>' t.info_download_station = '<p>To have a better experience please set the Download Station alias as <code>download</code>, you can check this setting in the Synology DSM <b>Control Panel</b> > <b>Application Portal</b>. Make sure you allow DSM to be embedded with iFrames too in <b>Control Panel</b> > <b>DSM Settings</b> > <b>Security</b>.</p><br/><p>There is more information about this available <a href="https://github.com/echel0n/SickBeard-TVRage/pull/338">here</a>.</p><br/>'
@ -777,7 +778,7 @@ class Manage:
else: else:
sqlResults = myDB.select("SELECT * FROM failed LIMIT ?", [limit]) sqlResults = myDB.select("SELECT * FROM failed LIMIT ?", [limit])
toRemove = toRemove.split("|") if toRemove != None else [] toRemove = toRemove.split("|") if toRemove is not None else []
for release in toRemove: for release in toRemove:
myDB.action('DELETE FROM failed WHERE release = ?', [release]) myDB.action('DELETE FROM failed WHERE release = ?', [release])
@ -810,9 +811,9 @@ class History:
for sql_result in sqlResults: for sql_result in sqlResults:
if not any((history['show_id'] == sql_result['showid'] \ if not any((history['show_id'] == sql_result['showid']
and history['season'] == sql_result['season'] \ and history['season'] == sql_result['season']
and history['episode'] == sql_result['episode'] \ and history['episode'] == sql_result['episode']
and history['quality'] == sql_result['quality'])\ and history['quality'] == sql_result['quality'])\
for history in compact): for history in compact):
@ -1179,7 +1180,7 @@ class ConfigPostProcessing:
@cherrypy.expose @cherrypy.expose
def testNaming(self, pattern=None, multi=None, abd=False): def testNaming(self, pattern=None, multi=None, abd=False):
if multi != None: if multi is not None:
multi = int(multi) multi = int(multi)
result = naming.test_name(pattern, multi, abd) result = naming.test_name(pattern, multi, abd)
@ -1190,7 +1191,7 @@ class ConfigPostProcessing:
@cherrypy.expose @cherrypy.expose
def isNamingValid(self, pattern=None, multi=None, abd=False): def isNamingValid(self, pattern=None, multi=None, abd=False):
if pattern == None: if pattern is None:
return "invalid" return "invalid"
# air by date shows just need one check, we don't need to worry about season folders # air by date shows just need one check, we don't need to worry about season folders
@ -1756,7 +1757,7 @@ class ConfigSubtitles:
subtitles_finder_frequency = 1 subtitles_finder_frequency = 1
if use_subtitles == "on": if use_subtitles == "on":
if sickbeard.subtitlesFinderScheduler.thread == None or not sickbeard.subtitlesFinderScheduler.thread.isAlive(): if sickbeard.subtitlesFinderScheduler.thread is None or not sickbeard.subtitlesFinderScheduler.thread.isAlive():
sickbeard.subtitlesFinderScheduler.silent = False sickbeard.subtitlesFinderScheduler.silent = False
sickbeard.subtitlesFinderScheduler.initThread() sickbeard.subtitlesFinderScheduler.initThread()
else: else:
@ -1870,7 +1871,7 @@ class HomePostProcess:
redirect("/home/postprocess/") redirect("/home/postprocess/")
else: else:
result = processTV.processDir(dir, nzbName, process_method=process_method, force=force, is_priority=is_priority, failed=failed, type=type, indexer=indexer) result = processTV.processDir(dir, nzbName, process_method=process_method, force=force, is_priority=is_priority, failed=failed, type=type, indexer=indexer)
if quiet != None and int(quiet) == 1: if quiet is not None and int(quiet) == 1:
return result return result
result = result.replace("\n","<br />\n") result = result.replace("\n","<br />\n")
@ -2422,7 +2423,7 @@ class Home:
host = config.clean_host(host, default_port=23053) host = config.clean_host(host, default_port=23053)
result = notifiers.growl_notifier.test_notify(host, password) result = notifiers.growl_notifier.test_notify(host, password)
if password == None or password == '': if password is None or password == '':
pw_append = '' pw_append = ''
else: else:
pw_append = " with password: " + password pw_append = " with password: " + password
@ -2694,12 +2695,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def displayShow(self, show=None): def displayShow(self, show=None):
if show == None: if show is None:
return _genericMessage("Error", "Invalid show ID") return _genericMessage("Error", "Invalid show ID")
else: else:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Show not in show list") return _genericMessage("Error", "Show not in show list")
showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.indexerid) showObj.exceptions = scene_exceptions.get_scene_exceptions(showObj.indexerid)
@ -2805,9 +2806,14 @@ class Home:
return result['description'] if result else 'Episode not found.' return result['description'] if result else 'Episode not found.'
@cherrypy.expose @cherrypy.expose
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): 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):
if show == None: if not anyQualities: anyQualities = []
if not bestQualities: bestQualities = []
if not exceptions_list: exceptions_list = []
if show is None:
errString = "Invalid show ID: " + str(show) errString = "Invalid show ID: " + str(show)
if directCall: if directCall:
return [errString] return [errString]
@ -2816,7 +2822,7 @@ class Home:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
errString = "Unable to find the specified show: " + str(show) errString = "Unable to find the specified show: " + str(show)
if directCall: if directCall:
return [errString] return [errString]
@ -2942,12 +2948,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def deleteShow(self, show=None): def deleteShow(self, show=None):
if show == None: if show is None:
return _genericMessage("Error", "Invalid show ID") return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Unable to find the specified show") return _genericMessage("Error", "Unable to find the specified show")
if sickbeard.showQueueScheduler.action.isBeingAdded(showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): # @UndefinedVariable if sickbeard.showQueueScheduler.action.isBeingAdded(showObj) or sickbeard.showQueueScheduler.action.isBeingUpdated(showObj): # @UndefinedVariable
@ -2961,12 +2967,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def refreshShow(self, show=None): def refreshShow(self, show=None):
if show == None: if show is None:
return _genericMessage("Error", "Invalid show ID") return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Unable to find the specified show") return _genericMessage("Error", "Unable to find the specified show")
# force the update from the DB # force the update from the DB
@ -2983,12 +2989,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def updateShow(self, show=None, force=0): def updateShow(self, show=None, force=0):
if show == None: if show is None:
return _genericMessage("Error", "Invalid show ID") return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Unable to find the specified show") return _genericMessage("Error", "Unable to find the specified show")
# force the update # force the update
@ -3006,12 +3012,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def subtitleShow(self, show=None, force=0): def subtitleShow(self, show=None, force=0):
if show == None: if show is None:
return _genericMessage("Error", "Invalid show ID") return _genericMessage("Error", "Invalid show ID")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Unable to find the specified show") return _genericMessage("Error", "Unable to find the specified show")
# search and download subtitles # search and download subtitles
@ -3049,7 +3055,7 @@ class Home:
@cherrypy.expose @cherrypy.expose
def setStatus(self, show=None, eps=None, status=None, direct=False): def setStatus(self, show=None, eps=None, status=None, direct=False):
if show == None or eps == None or status == None: if show is None or eps is None or status is None:
errMsg = "You must specify a show and at least one episode" errMsg = "You must specify a show and at least one episode"
if direct: if direct:
ui.notifications.error('Error', errMsg) ui.notifications.error('Error', errMsg)
@ -3067,7 +3073,7 @@ class Home:
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
errMsg = "Error", "Show not in show list" errMsg = "Error", "Show not in show list"
if direct: if direct:
ui.notifications.error('Error', errMsg) ui.notifications.error('Error', errMsg)
@ -3078,7 +3084,7 @@ class Home:
wanted_segments = [] wanted_segments = []
failed_segments = {} failed_segments = {}
if eps != None: if eps is not None:
sql_l = [] sql_l = []
for curEp in eps.split('|'): for curEp in eps.split('|'):
@ -3089,7 +3095,7 @@ class Home:
epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1])) epObj = showObj.getEpisode(int(epInfo[0]), int(epInfo[1]))
if epObj == None: if epObj is None:
return _genericMessage("Error", "Episode couldn't be retrieved") return _genericMessage("Error", "Episode couldn't be retrieved")
if int(status) in (WANTED, FAILED): if int(status) in (WANTED, FAILED):
@ -3155,12 +3161,12 @@ class Home:
@cherrypy.expose @cherrypy.expose
def testRename(self, show=None): def testRename(self, show=None):
if show == None: if show is None:
return _genericMessage("Error", "You must specify a show") return _genericMessage("Error", "You must specify a show")
showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) showObj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if showObj == None: if showObj is None:
return _genericMessage("Error", "Show not in show list") return _genericMessage("Error", "Show not in show list")
try: try:
@ -3201,13 +3207,13 @@ class Home:
@cherrypy.expose @cherrypy.expose
def doRename(self, show=None, eps=None): def doRename(self, show=None, eps=None):
if show == None or eps == None: if show is None or eps is None:
errMsg = "You must specify a show and at least one episode" errMsg = "You must specify a show and at least one episode"
return _genericMessage("Error", errMsg) return _genericMessage("Error", errMsg)
show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show)) show_obj = sickbeard.helpers.findCertainShow(sickbeard.showList, int(show))
if show_obj == None: if show_obj is None:
errMsg = "Error", "Show not in show list" errMsg = "Error", "Show not in show list"
return _genericMessage("Error", errMsg) return _genericMessage("Error", errMsg)
@ -3218,7 +3224,7 @@ class Home:
myDB = db.DBConnection() myDB = db.DBConnection()
if eps == None: if eps is None:
redirect("/home/displayShow?show=" + show) redirect("/home/displayShow?show=" + show)
for curEp in eps.split('|'): for curEp in eps.split('|'):
@ -3258,7 +3264,7 @@ class Home:
sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) # @UndefinedVariable sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) # @UndefinedVariable
# wait until the queue item tells us whether it worked or not # wait until the queue item tells us whether it worked or not
while ep_queue_item.success == None: # @UndefinedVariable while ep_queue_item.success is None: # @UndefinedVariable
time.sleep(1) time.sleep(1)
# return the correct json value # return the correct json value
@ -3356,7 +3362,7 @@ class Home:
sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) # @UndefinedVariable sickbeard.searchQueueScheduler.action.add_item(ep_queue_item) # @UndefinedVariable
# wait until the queue item tells us whether it worked or not # wait until the queue item tells us whether it worked or not
while ep_queue_item.success == None: # @UndefinedVariable while ep_queue_item.success is None: # @UndefinedVariable
time.sleep(1) time.sleep(1)
# return the correct json value # return the correct json value
@ -3636,7 +3642,7 @@ class WebInterface:
air_date_time = network_timezones.parse_date_time(episode['airdate'], show["airs"], show['network']) air_date_time = network_timezones.parse_date_time(episode['airdate'], show["airs"], show['network'])
# Create event for episode # Create event for episode
ical = ical + 'BEGIN:VEVENT\r\n' ical += 'BEGIN:VEVENT\r\n'
ical = ical + 'DTSTART;VALUE=DATE:' + str(air_date_time.date()).replace("-", "") + '\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 + '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' ical = ical + 'UID:Sick-Beard-' + str(datetime.date.today().isoformat()) + '-' + show['show_name'].replace(" ", "-") + '-E' + str(episode['episode']) + 'S' + str(episode['season']) + '\r\n'
@ -3645,7 +3651,7 @@ class WebInterface:
else: else:
ical = ical + 'DESCRIPTION:' + show['airs'] + ' on ' + show['network'] + '\r\n' ical = ical + 'DESCRIPTION:' + show['airs'] + ' on ' + show['network'] + '\r\n'
ical = ical + 'LOCATION:' + 'Episode ' + str(episode['episode']) + ' - Season ' + str(episode['season']) + '\r\n' ical = ical + 'LOCATION:' + 'Episode ' + str(episode['episode']) + ' - Season ' + str(episode['season']) + '\r\n'
ical = ical + 'END:VEVENT\r\n' ical += 'END:VEVENT\r\n'
# Ending the iCal # Ending the iCal
ical += 'END:VCALENDAR' ical += 'END:VCALENDAR'

View File

@ -27,7 +27,8 @@ from sickbeard.webserve import WebInterface
from sickbeard.helpers import create_https_certificates from sickbeard.helpers import create_https_certificates
def initWebServer(options = {}): def initWebServer(options=None):
if not options: options = {}
options.setdefault('port', 8081) options.setdefault('port', 8081)
options.setdefault('host', '0.0.0.0') options.setdefault('host', '0.0.0.0')
options.setdefault('log_dir', None) options.setdefault('log_dir', None)