Browse Source

Fix more errors and warnings found by code validation

tags/2.3.5RC2
Safihre 7 years ago
parent
commit
5e722b27f3
  1. 8
      SABnzbd.py
  2. 2
      sabnzbd/__init__.py
  3. 9
      sabnzbd/api.py
  4. 6
      sabnzbd/config.py
  5. 5
      sabnzbd/decoder.py
  6. 4
      sabnzbd/dirscanner.py
  7. 2
      sabnzbd/downloader.py
  8. 13
      sabnzbd/interface.py
  9. 3
      sabnzbd/misc.py
  10. 15
      sabnzbd/newsunpack.py
  11. 5
      sabnzbd/newswrapper.py
  12. 2
      sabnzbd/notifier.py
  13. 5
      sabnzbd/nzbqueue.py
  14. 4
      sabnzbd/nzbstuff.py
  15. 1
      sabnzbd/par2file.py
  16. 4
      sabnzbd/postproc.py
  17. 13
      sabnzbd/rss.py
  18. 8
      sabnzbd/skintext.py
  19. 4
      sabnzbd/urlgrabber.py
  20. 2
      sabnzbd/utils/certgen.py
  21. 1
      sabnzbd/utils/checkdir.py
  22. 2
      sabnzbd/utils/getperformance.py
  23. 264
      sabnzbd/utils/happyeyeballs.py
  24. 2
      sabnzbd/utils/pystone.py
  25. 4
      sabnzbd/utils/servertests.py
  26. 5
      sabnzbd/zconfig.py
  27. 1
      tests/conftest.py
  28. 2
      util/apireg.py
  29. 1
      util/mailslot.py

8
SABnzbd.py

@ -502,7 +502,7 @@ def all_localhosts():
def check_resolve(host): def check_resolve(host):
""" Return True if 'host' resolves """ """ Return True if 'host' resolves """
try: try:
dummy = socket.getaddrinfo(host, None) socket.getaddrinfo(host, None)
except: except:
# Does not resolve # Does not resolve
return False return False
@ -598,7 +598,7 @@ def get_webhost(cherryhost, cherryport, https_port):
cherryhost = cherryhost.strip('[]') cherryhost = cherryhost.strip('[]')
else: else:
try: try:
info = socket.getaddrinfo(cherryhost, None) socket.getaddrinfo(cherryhost, None)
except: except:
cherryhost = cherryhost.strip('[]') cherryhost = cherryhost.strip('[]')
@ -1005,13 +1005,13 @@ def main():
if enable_https and https_port: if enable_https and https_port:
try: try:
cherrypy.process.servers.check_port(cherryhost, https_port, timeout=0.05) cherrypy.process.servers.check_port(cherryhost, https_port, timeout=0.05)
except IOError, error: except IOError:
Bail_Out(browserhost, cherryport) Bail_Out(browserhost, cherryport)
except: except:
Bail_Out(browserhost, cherryport, '49') Bail_Out(browserhost, cherryport, '49')
try: try:
cherrypy.process.servers.check_port(cherryhost, cherryport, timeout=0.05) cherrypy.process.servers.check_port(cherryhost, cherryport, timeout=0.05)
except IOError, error: except IOError:
Bail_Out(browserhost, cherryport) Bail_Out(browserhost, cherryport)
except: except:
Bail_Out(browserhost, cherryport, '49') Bail_Out(browserhost, cherryport, '49')

2
sabnzbd/__init__.py

@ -1204,7 +1204,7 @@ def test_cert_checking():
ssl_sock.connect((cfg.selftest_host(), 443)) ssl_sock.connect((cfg.selftest_host(), 443))
ssl_sock.close() ssl_sock.close()
return True return True
except (socket.gaierror, socket.timeout) as e: except (socket.gaierror, socket.timeout):
# Non-SSL related error. # Non-SSL related error.
# We now assume that certificates work instead of forcing # We now assume that certificates work instead of forcing
# lower quality just because some (temporary) internet problem # lower quality just because some (temporary) internet problem

9
sabnzbd/api.py

@ -220,6 +220,8 @@ def _api_queue_pause(output, value, kwargs):
if value: if value:
items = value.split(',') items = value.split(',')
handled = NzbQueue.do.pause_multiple_nzo(items) handled = NzbQueue.do.pause_multiple_nzo(items)
else:
handled = False
return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled}) return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled})
@ -228,6 +230,8 @@ def _api_queue_resume(output, value, kwargs):
if value: if value:
items = value.split(',') items = value.split(',')
handled = NzbQueue.do.resume_multiple_nzo(items) handled = NzbQueue.do.resume_multiple_nzo(items)
else:
handled = False
return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled}) return report(output, keyword='', data={'status': bool(handled), 'nzo_ids': handled})
@ -462,6 +466,7 @@ def _api_change_opts(name, output, kwargs):
""" API: accepts output, value(=nzo_id), value2(=pp) """ """ API: accepts output, value(=nzo_id), value2(=pp) """
value = kwargs.get('value') value = kwargs.get('value')
value2 = kwargs.get('value2') value2 = kwargs.get('value2')
result = 0
if value and value2 and value2.isdigit(): if value and value2 and value2.isdigit():
result = NzbQueue.do.change_opts(value, int(value2)) result = NzbQueue.do.change_opts(value, int(value2))
return report(output, keyword='status', data=bool(result > 0)) return report(output, keyword='status', data=bool(result > 0))
@ -802,7 +807,6 @@ def _api_browse(name, output, kwargs):
compact = kwargs.get('compact') compact = kwargs.get('compact')
if compact and compact == '1': if compact and compact == '1':
paths = []
name = platform_encode(kwargs.get('term', '')) name = platform_encode(kwargs.get('term', ''))
paths = [entry['path'] for entry in folders_at_path(os.path.dirname(name)) if 'path' in entry] paths = [entry['path'] for entry in folders_at_path(os.path.dirname(name)) if 'path' in entry]
return report(output, keyword='', data=paths) return report(output, keyword='', data=paths)
@ -1685,7 +1689,6 @@ def build_queue_header(search=None, start=0, limit=0, output=None):
header['size'] = format_bytes(bytes) header['size'] = format_bytes(bytes)
header['noofslots_total'] = qnfo.q_fullsize header['noofslots_total'] = qnfo.q_fullsize
status = ''
if Downloader.do.paused or Downloader.do.postproc: if Downloader.do.paused or Downloader.do.postproc:
status = Status.PAUSED status = Status.PAUSED
elif bytespersec > 0: elif bytespersec > 0:
@ -1700,7 +1703,6 @@ def build_queue_header(search=None, start=0, limit=0, output=None):
# new eta format: 16:00 Fri 07 Feb # new eta format: 16:00 Fri 07 Feb
header['eta'] = datestart.strftime(time_format('%H:%M %a %d %b')).decode(codepage) header['eta'] = datestart.strftime(time_format('%H:%M %a %d %b')).decode(codepage)
except: except:
datestart = datetime.datetime.now()
header['eta'] = T('unknown') header['eta'] = T('unknown')
return (header, qnfo.list, bytespersec, qnfo.q_fullsize, qnfo.bytes_left_previous_page) return (header, qnfo.list, bytespersec, qnfo.q_fullsize, qnfo.bytes_left_previous_page)
@ -1772,7 +1774,6 @@ def build_history(start=None, limit=None, verbose=False, verbose_list=None, sear
if not h_limit: if not h_limit:
items, fetched_items, total_items = history_db.fetch_history(h_start, 1, search, failed_only, categories) items, fetched_items, total_items = history_db.fetch_history(h_start, 1, search, failed_only, categories)
items = [] items = []
fetched_items = 0
else: else:
items, fetched_items, total_items = history_db.fetch_history(h_start, h_limit, search, failed_only, categories) items, fetched_items, total_items = history_db.fetch_history(h_start, h_limit, search, failed_only, categories)

6
sabnzbd/config.py

@ -411,8 +411,8 @@ class ConfigServer(object):
except KeyError: except KeyError:
continue continue
exec 'self.%s.set(value)' % kw exec 'self.%s.set(value)' % kw
if not self.displayname(): if not self.displayname():
self.displayname.set(self.__name) self.displayname.set(self.__name)
return True return True
def get_dict(self, safe=False): def get_dict(self, safe=False):
@ -896,7 +896,7 @@ def get_servers():
return {} return {}
def define_categories(force=False): def define_categories():
""" Define categories listed in the Setup file """ Define categories listed in the Setup file
return a list of ConfigCat instances return a list of ConfigCat instances
""" """

5
sabnzbd/decoder.py

@ -125,7 +125,7 @@ class Decoder(Thread):
nzf.article_count += 1 nzf.article_count += 1
found = True found = True
except IOError, e: except IOError:
logme = T('Decoding %s failed') % art_id logme = T('Decoding %s failed') % art_id
logging.warning(logme) logging.warning(logme)
logging.info("Traceback: ", exc_info=True) logging.info("Traceback: ", exc_info=True)
@ -134,7 +134,7 @@ class Decoder(Thread):
sabnzbd.nzbqueue.NzbQueue.do.reset_try_lists(article) sabnzbd.nzbqueue.NzbQueue.do.reset_try_lists(article)
register = False register = False
except MemoryError, e: except MemoryError:
logme = T('Decoder failure: Out of memory') logme = T('Decoder failure: Out of memory')
logging.warning(logme) logging.warning(logme)
anfo = sabnzbd.articlecache.ArticleCache.do.cache_info() anfo = sabnzbd.articlecache.ArticleCache.do.cache_info()
@ -240,7 +240,6 @@ class Decoder(Thread):
nzf = article.nzf nzf = article.nzf
yenc, data = yCheck(data) yenc, data = yCheck(data)
ybegin, ypart, yend = yenc ybegin, ypart, yend = yenc
decoded_data = None
# Deal with non-yencoded posts # Deal with non-yencoded posts
if not ybegin: if not ybegin:

4
sabnzbd/dirscanner.py

@ -144,7 +144,7 @@ def ProcessArchiveFile(filename, path, pp=None, script=None, cat=None, catdir=No
priority=priority, nzbname=nzbname) priority=priority, nzbname=nzbname)
if not nzo.password: if not nzo.password:
nzo.password = password nzo.password = password
except (TypeError, ValueError) as e: except (TypeError, ValueError):
# Duplicate or empty, ignore # Duplicate or empty, ignore
pass pass
except: except:
@ -232,7 +232,7 @@ def ProcessSingleFile(filename, path, pp=None, script=None, cat=None, catdir=Non
# Empty, but correct file # Empty, but correct file
return -1, nzo_ids return -1, nzo_ids
except: except:
if data.find("<nzb") >= 0 and data.find("</nzb") < 0: if data.find("<nzb") >= 0 > data.find("</nzb"):
# Looks like an incomplete file, retry # Looks like an incomplete file, retry
return -2, nzo_ids return -2, nzo_ids
else: else:

2
sabnzbd/downloader.py

@ -311,7 +311,7 @@ class Downloader(Thread):
''' '''
if value: if value:
mx = cfg.bandwidth_max.get_int() mx = cfg.bandwidth_max.get_int()
if '%' in str(value) or (from_units(value) > 0 and from_units(value) < 101): if '%' in str(value) or (0 < from_units(value) < 101):
limit = value.strip(' %') limit = value.strip(' %')
self.bandwidth_perc = from_units(limit) self.bandwidth_perc = from_units(limit)
if mx: if mx:

13
sabnzbd/interface.py

@ -161,7 +161,7 @@ def check_hostname():
if not host: if not host:
return False return False
# Remove the port-part (like ':8080'), if it is there, always on the right hand side. # Remove the port-part (like ':8080'), if it is there, always on the right hand side.
# Not to be confused with IPv6 colons (within square brackets) # Not to be confused with IPv6 colons (within square brackets)
host = re.sub(':[0123456789]+$', '', host).lower() host = re.sub(':[0123456789]+$', '', host).lower()
@ -174,7 +174,7 @@ def check_hostname():
return True return True
# Fine if ends with ".local" or ".local.", aka mDNS name # Fine if ends with ".local" or ".local.", aka mDNS name
# See rfc6762 Multicast DNS # See rfc6762 Multicast DNS
if host.endswith(('.local', '.local.')): if host.endswith(('.local', '.local.')):
return True return True
@ -774,7 +774,7 @@ class NzoPage(object):
# /SABnzbd_nzo_xxxxx/files # /SABnzbd_nzo_xxxxx/files
elif 'files' in args: elif 'files' in args:
info = self.nzo_files(info, pnfo_list, nzo_id) info = self.nzo_files(info, nzo_id)
# /SABnzbd_nzo_xxxxx/save # /SABnzbd_nzo_xxxxx/save
elif 'save' in args: elif 'save' in args:
@ -784,7 +784,7 @@ class NzoPage(object):
# /SABnzbd_nzo_xxxxx/ # /SABnzbd_nzo_xxxxx/
else: else:
info = self.nzo_details(info, pnfo_list, nzo_id) info = self.nzo_details(info, pnfo_list, nzo_id)
info = self.nzo_files(info, pnfo_list, nzo_id) info = self.nzo_files(info, nzo_id)
template = Template(file=os.path.join(sabnzbd.WEB_DIR, 'nzo.tmpl'), template = Template(file=os.path.join(sabnzbd.WEB_DIR, 'nzo.tmpl'),
filter=FILTER, searchList=[info], compilerSettings=DIRECTIVES) filter=FILTER, searchList=[info], compilerSettings=DIRECTIVES)
@ -836,7 +836,7 @@ class NzoPage(object):
return info return info
def nzo_files(self, info, pnfo_list, nzo_id): def nzo_files(self, info, nzo_id):
active = [] active = []
nzo = NzbQueue.do.get_nzo(nzo_id) nzo = NzbQueue.do.get_nzo(nzo_id)
if nzo: if nzo:
@ -2077,7 +2077,7 @@ class ConfigScheduling(object):
if '%' not in value and from_units(value) < 1.0: if '%' not in value and from_units(value) < 1.0:
value = T('off') # : "Off" value for speedlimit in scheduler value = T('off') # : "Off" value for speedlimit in scheduler
else: else:
if '%' not in value and int_conv(value) > 1 and int_conv(value) < 101: if '%' not in value and 1 < int_conv(value) < 101:
value += '%' value += '%'
value = value.upper() value = value.upper()
if action in actions: if action in actions:
@ -2132,7 +2132,6 @@ class ConfigScheduling(object):
@secured_expose(check_session_key=True, check_configlock=True) @secured_expose(check_session_key=True, check_configlock=True)
def addSchedule(self, **kwargs): def addSchedule(self, **kwargs):
servers = config.get_servers() servers = config.get_servers()
categories = list_cats(False)
minute = kwargs.get('minute') minute = kwargs.get('minute')
hour = kwargs.get('hour') hour = kwargs.get('hour')
days_of_week = ''.join([str(x) for x in kwargs.get('daysofweek', '')]) days_of_week = ''.join([str(x) for x in kwargs.get('daysofweek', '')])

3
sabnzbd/misc.py

@ -748,7 +748,6 @@ def to_units(val, spaces=0, postfix=''):
Show single decimal for M and higher Show single decimal for M and higher
""" """
dec_limit = 1 dec_limit = 1
decimals = 0
if val < 0: if val < 0:
sign = '-' sign = '-'
else: else:
@ -1453,7 +1452,7 @@ def create_https_certificates(ssl_cert, ssl_key):
try: try:
from sabnzbd.utils.certgen import generate_key, generate_local_cert from sabnzbd.utils.certgen import generate_key, generate_local_cert
private_key = generate_key(key_size=2048, output_file=ssl_key) private_key = generate_key(key_size=2048, output_file=ssl_key)
generate_local_cert(private_key, days_valid=3560, output_file=ssl_cert, LN=u'SABnzbd', ON=u'SABnzbd', CN=u'localhost') generate_local_cert(private_key, days_valid=3560, output_file=ssl_cert, LN=u'SABnzbd', ON=u'SABnzbd')
logging.info('Self-signed certificates generated successfully') logging.info('Self-signed certificates generated successfully')
except: except:
logging.error(T('Error creating SSL key and certificate')) logging.error(T('Error creating SSL key and certificate'))

15
sabnzbd/newsunpack.py

@ -33,7 +33,7 @@ from sabnzbd.encoding import TRANS, unicoder, platform_encode, deunicode
import sabnzbd.utils.rarfile as rarfile import sabnzbd.utils.rarfile as rarfile
from sabnzbd.misc import format_time_string, find_on_path, make_script_path, int_conv, \ from sabnzbd.misc import format_time_string, find_on_path, make_script_path, int_conv, \
real_path, globber, globber_full, get_all_passwords, renamer, clip_path, calc_age, \ real_path, globber, globber_full, get_all_passwords, renamer, clip_path, calc_age, \
has_win_device, long_path, remove_file, recursive_listdir, is_rarfile long_path, remove_file, recursive_listdir, is_rarfile
from sabnzbd.sorting import SeriesSorter from sabnzbd.sorting import SeriesSorter
import sabnzbd.cfg as cfg import sabnzbd.cfg as cfg
from sabnzbd.constants import Status from sabnzbd.constants import Status
@ -175,7 +175,7 @@ def external_processing(extern_proc, nzo, complete_dir, nicename, status):
proc = p.stdout proc = p.stdout
if p.stdin: if p.stdin:
p.stdin.close() p.stdin.close()
line = ''
lines = [] lines = []
while 1: while 1:
line = proc.readline() line = proc.readline()
@ -236,11 +236,10 @@ def unpack_magic(nzo, workdir, workdir_complete, dele, one_folder, joinables, zi
else: else:
xjoinables, xzips, xrars, xsevens, xts = build_filelists(workdir, workdir_complete, check_both=dele) xjoinables, xzips, xrars, xsevens, xts = build_filelists(workdir, workdir_complete, check_both=dele)
rerun = False
force_rerun = False force_rerun = False
newfiles = [] newfiles = []
error = None error = None
new_joins = new_rars = new_zips = new_ts = None new_joins = new_ts = None
if cfg.enable_filejoin(): if cfg.enable_filejoin():
new_joins = [jn for jn in xjoinables if jn not in joinables] new_joins = [jn for jn in xjoinables if jn not in joinables]
@ -1120,9 +1119,9 @@ def par2_repair(parfile_nzf, nzo, workdir, setname, single):
# Multipar or not? # Multipar or not?
if sabnzbd.WIN32 and cfg.multipar(): if sabnzbd.WIN32 and cfg.multipar():
finished, readd, datafiles, used_joinables, used_for_repair = MultiPar_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=single) finished, readd, datafiles, used_joinables, used_for_repair = MultiPar_Verify(parfile, nzo, setname, joinables, single=single)
else: else:
finished, readd, datafiles, used_joinables, used_for_repair = PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=single) finished, readd, datafiles, used_joinables, used_for_repair = PAR_Verify(parfile, nzo, setname, joinables, single=single)
if finished: if finished:
result = True result = True
@ -1189,7 +1188,7 @@ _RE_LOADING_PAR2 = re.compile(r'Loading "([^"]+)"\.')
_RE_LOADED_PAR2 = re.compile(r'Loaded (\d+) new packets') _RE_LOADED_PAR2 = re.compile(r'Loaded (\d+) new packets')
def PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False): def PAR_Verify(parfile, nzo, setname, joinables, single=False):
""" Run par2 on par-set """ """ Run par2 on par-set """
used_joinables = [] used_joinables = []
used_for_repair = [] used_for_repair = []
@ -1526,7 +1525,7 @@ def PAR_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False):
_RE_FILENAME = re.compile(r'"([^"]+)"') _RE_FILENAME = re.compile(r'"([^"]+)"')
def MultiPar_Verify(parfile, parfile_nzf, nzo, setname, joinables, single=False): def MultiPar_Verify(parfile, nzo, setname, joinables, single=False):
""" Run par2 on par-set """ """ Run par2 on par-set """
parfolder = os.path.split(parfile)[0] parfolder = os.path.split(parfile)[0]
used_joinables = [] used_joinables = []

5
sabnzbd/newswrapper.py

@ -150,7 +150,7 @@ class NNTP(object):
# Pre-define attributes to save memory # Pre-define attributes to save memory
__slots__ = ('host', 'port', 'nw', 'blocking', 'error_msg', 'sock') __slots__ = ('host', 'port', 'nw', 'blocking', 'error_msg', 'sock')
def __init__(self, host, port, info, sslenabled, send_group, nw, user=None, password=None, block=False, write_fds=None): def __init__(self, host, port, info, sslenabled, nw, block=False, write_fds=None):
self.host = host self.host = host
self.port = port self.port = port
self.nw = nw self.nw = nw
@ -312,8 +312,7 @@ class NewsWrapper(object):
# Construct NNTP object and shorthands # Construct NNTP object and shorthands
self.nntp = NNTP(self.server.hostip, self.server.port, self.server.info, self.server.ssl, self.nntp = NNTP(self.server.hostip, self.server.port, self.server.info, self.server.ssl,
self.server.send_group, self, self.server.username, self.server.password, self, self.blocking, write_fds)
self.blocking, write_fds)
self.recv = self.nntp.sock.recv self.recv = self.nntp.sock.recv
self.timeout = time.time() + self.server.timeout self.timeout = time.time() + self.server.timeout

2
sabnzbd/notifier.py

@ -462,7 +462,7 @@ def send_pushover(title, msg, gtype, force=False, test=None):
"expire": emergency_expire "expire": emergency_expire
} }
return do_send_pushover(body) return do_send_pushover(body)
if prio > -3 and prio < 2: if -3 < prio < 2:
body = { "token": apikey, body = { "token": apikey,
"user": userkey, "user": userkey,
"device": device, "device": device,

5
sabnzbd/nzbqueue.py

@ -69,7 +69,7 @@ class NzbQueue(object):
data = sabnzbd.load_admin(QUEUE_FILE_NAME) data = sabnzbd.load_admin(QUEUE_FILE_NAME)
# Process the data and check compatibility # Process the data and check compatibility
nzo_ids = self.check_compatibility(data) nzo_ids = self.check_compatibility(repair, data)
# First handle jobs in the queue file # First handle jobs in the queue file
folders = [] folders = []
@ -104,7 +104,7 @@ class NzbQueue(object):
except: except:
pass pass
def check_compatibility(self, data): def check_compatibility(self, repair, data):
""" Do compatibility checks on the loaded data """ """ Do compatibility checks on the loaded data """
nzo_ids = [] nzo_ids = []
if not data: if not data:
@ -204,7 +204,6 @@ class NzbQueue(object):
verified = sabnzbd.load_data(VERIFIED_FILE, path, remove=False) or {'x': False} verified = sabnzbd.load_data(VERIFIED_FILE, path, remove=False) or {'x': False}
return all(verified[x] for x in verified) return all(verified[x] for x in verified)
nzo_id = None
name = os.path.basename(folder) name = os.path.basename(folder)
path = os.path.join(folder, JOB_ADMIN) path = os.path.join(folder, JOB_ADMIN)
if hasattr(new_nzb, 'filename'): if hasattr(new_nzb, 'filename'):

4
sabnzbd/nzbstuff.py

@ -1022,7 +1022,7 @@ class NzbObject(TryList):
# Sort the sets # Sort the sets
for setname in self.extrapars: for setname in self.extrapars:
self.extrapars[parset].sort(key=lambda x: x.blocks) self.extrapars[setname].sort(key=lambda x: x.blocks)
# Also re-parse all filenames in case par2 came after first articles # Also re-parse all filenames in case par2 came after first articles
self.verify_all_filenames_and_resort() self.verify_all_filenames_and_resort()
@ -2005,7 +2005,7 @@ def scan_password(name):
slash = name.find('/') slash = name.find('/')
# Look for name/password, but make sure that '/' comes before any {{ # Look for name/password, but make sure that '/' comes before any {{
if slash >= 0 and slash < braces and 'password=' not in name: if 0 <= slash < braces and 'password=' not in name:
# Is it maybe in 'name / password' notation? # Is it maybe in 'name / password' notation?
if slash == name.find(' / ') + 1: if slash == name.find(' / ') + 1:
# Remove the extra space after name and before password # Remove the extra space after name and before password

1
sabnzbd/par2file.py

@ -49,7 +49,6 @@ def analyse_par2(name, filepath=None):
setname is empty when not a par2 file setname is empty when not a par2 file
""" """
name = name.strip() name = name.strip()
setname = None
vol = block = 0 vol = block = 0
m = PROBABLY_PAR2_RE.search(name) m = PROBABLY_PAR2_RE.search(name)
if m: if m:

4
sabnzbd/postproc.py

@ -281,7 +281,6 @@ def process_job(nzo):
nzb_list = [] nzb_list = []
# These need to be initialized in case of a crash # These need to be initialized in case of a crash
workdir_complete = '' workdir_complete = ''
postproc_time = 0
script_log = '' script_log = ''
script_line = '' script_line = ''
@ -336,15 +335,12 @@ def process_job(nzo):
unpack_error = 1 unpack_error = 1
script = nzo.script script = nzo.script
cat = nzo.cat
logging.info('Starting Post-Processing on %s' + logging.info('Starting Post-Processing on %s' +
' => Repair:%s, Unpack:%s, Delete:%s, Script:%s, Cat:%s', ' => Repair:%s, Unpack:%s, Delete:%s, Script:%s, Cat:%s',
filename, flag_repair, flag_unpack, flag_delete, script, nzo.cat) filename, flag_repair, flag_unpack, flag_delete, script, nzo.cat)
# Set complete dir to workdir in case we need to abort # Set complete dir to workdir in case we need to abort
workdir_complete = workdir workdir_complete = workdir
marker_file = None
# Par processing, if enabled # Par processing, if enabled
if all_ok and flag_repair: if all_ok and flag_repair:

13
sabnzbd/rss.py

@ -290,7 +290,7 @@ class RSSQueue(object):
msg = T('Do not have valid authentication for feed %s') % feed msg = T('Do not have valid authentication for feed %s') % feed
logging.info(msg) logging.info(msg)
if status >= 500 and status <= 599: if 500 <= status <= 599:
msg = T('Server side error (server code %s); could not get %s on %s') % (status, feed, uri) msg = T('Server side error (server code %s); could not get %s on %s') % (status, feed, uri)
logging.info(msg) logging.info(msg)
@ -330,12 +330,8 @@ class RSSQueue(object):
if readout: if readout:
try: try:
link, category, size, age, season, episode = _get_link(uri, entry) link, category, size, age, season, episode = _get_link(entry)
except (AttributeError, IndexError): except (AttributeError, IndexError):
link = None
category = u''
size = 0L
age = None
logging.info(T('Incompatible feed') + ' ' + uri) logging.info(T('Incompatible feed') + ' ' + uri)
logging.info("Traceback: ", exc_info=True) logging.info("Traceback: ", exc_info=True)
return T('Incompatible feed') return T('Incompatible feed')
@ -627,14 +623,11 @@ def _HandleLink(jobs, feed, link, title, size, age, season, episode, flag, orgca
else: else:
jobs[link]['status'] = flag jobs[link]['status'] = flag
def _get_link(uri, entry): def _get_link(entry):
""" Retrieve the post link from this entry """ Retrieve the post link from this entry
Returns (link, category, size) Returns (link, category, size)
""" """
link = None
category = ''
size = 0L size = 0L
uri = uri.lower()
age = datetime.datetime.now() age = datetime.datetime.now()
# Try standard link and enclosures first # Try standard link and enclosures first

8
sabnzbd/skintext.py

@ -47,16 +47,10 @@ SKIN_TEXT = {
'post-Propagating' : TT('Propagation delay'), 'post-Propagating' : TT('Propagation delay'),
'post-Checking' : TT('Checking'), #: PP status 'post-Checking' : TT('Checking'), #: PP status
'sch-frequency' : TT('Frequency'), #: #: Config->Scheduler
'sch-action' : TT('Action'), #: #: Config->Scheduler
'sch-arguments' : TT('Arguments'), #: #: Config->Scheduler
'sch-task' : TT('Task'), #: #: Config->Scheduler 'sch-task' : TT('Task'), #: #: Config->Scheduler
'sch-disable_server' : TT('disable server'), #: #: Config->Scheduler 'sch-disable_server' : TT('disable server'), #: #: Config->Scheduler
'sch-enable_server' : TT('enable server'), #: #: Config->Scheduler 'sch-enable_server' : TT('enable server'), #: #: Config->Scheduler
'sch-resume' : TT('Resume'), #: #: Config->Scheduler
'sch-pause' : TT('Pause'), #: #: Config->Scheduler
'sch-shutdown' : TT('Shutdown'), #: #: Config->Scheduler
'sch-restart' : TT('Restart'), #: #: Config->Scheduler
'sch-speedlimit' : TT('Speedlimit'), #: #: Config->Scheduler 'sch-speedlimit' : TT('Speedlimit'), #: #: Config->Scheduler
'sch-pause_all' : TT('Pause All'), #: #: Config->Scheduler 'sch-pause_all' : TT('Pause All'), #: #: Config->Scheduler
'sch-pause_post' : TT('Pause post-processing'), #: #: Config->Scheduler 'sch-pause_post' : TT('Pause post-processing'), #: #: Config->Scheduler

4
sabnzbd/urlgrabber.py

@ -199,7 +199,7 @@ class URLGrabber(Thread):
retry = True retry = True
fetch_request = None fetch_request = None
elif retry: elif retry:
fetch_request, msg, retry, wait, data = _analyse(fetch_request, url, future_nzo) fetch_request, msg, retry, wait, data = _analyse(fetch_request, future_nzo)
if not fetch_request: if not fetch_request:
if retry: if retry:
@ -351,7 +351,7 @@ def _build_request(url):
return urllib2.urlopen(req) return urllib2.urlopen(req)
def _analyse(fetch_request, url, future_nzo): def _analyse(fetch_request, future_nzo):
""" Analyze response of indexer """ Analyze response of indexer
returns fetch_request|None, error-message|None, retry, wait-seconds, data returns fetch_request|None, error-message|None, retry, wait-seconds, data
""" """

2
sabnzbd/utils/certgen.py

@ -52,7 +52,7 @@ def generate_key(key_size=2048, output_file='key.pem'):
# Ported from cryptography docs/x509/tutorial.rst # Ported from cryptography docs/x509/tutorial.rst
def generate_local_cert(private_key, days_valid=3560, output_file='cert.cert', LN=u'SABnzbd', ON=u'SABnzbd', CN=u'localhost'): def generate_local_cert(private_key, days_valid=3560, output_file='cert.cert', LN=u'SABnzbd', ON=u'SABnzbd'):
# Various details about who we are. For a self-signed certificate the # Various details about who we are. For a self-signed certificate the
# subject and issuer are always the same. # subject and issuer are always the same.
subject = issuer = x509.Name([ subject = issuer = x509.Name([

1
sabnzbd/utils/checkdir.py

@ -70,7 +70,6 @@ def isFAT(dir):
''' '''
dfcmd = "df " + dir dfcmd = "df " + dir
device = ''
for thisline in os.popen(dfcmd).readlines(): for thisline in os.popen(dfcmd).readlines():
if thisline.find('/')==0: if thisline.find('/')==0:
if debug: print thisline if debug: print thisline

2
sabnzbd/utils/getperformance.py

@ -61,7 +61,7 @@ def getpystone():
maxpystone = max(maxpystone, int(pystonefloat)) maxpystone = max(maxpystone, int(pystonefloat))
# Stop when pystone() has been running for at least 0.1 second # Stop when pystone() has been running for at least 0.1 second
if duration > 0.1: if duration > 0.1:
break; break
return maxpystone return maxpystone

264
sabnzbd/utils/happyeyeballs.py

@ -31,119 +31,119 @@ DEBUG = False
# called by each thread # called by each thread
def do_socket_connect(queue, ip, PORT, SSL, ipv4delay): def do_socket_connect(queue, ip, PORT, SSL, ipv4delay):
# connect to the ip, and put the result into the queue # connect to the ip, and put the result into the queue
if DEBUG: logging.debug("Input for thread is %s %s %s", ip, PORT, SSL) if DEBUG: logging.debug("Input for thread is %s %s %s", ip, PORT, SSL)
try: try:
# CREATE SOCKET # CREATE SOCKET
if ip.find(':') >= 0: if ip.find(':') >= 0:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
if ip.find('.') >= 0: if ip.find('.') >= 0:
time.sleep(ipv4delay) # IPv4 ... so a delay for IPv4 as we prefer IPv6. Note: ipv4delay could be 0 time.sleep(ipv4delay) # IPv4 ... so a delay for IPv4 as we prefer IPv6. Note: ipv4delay could be 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3) s.settimeout(3)
if not SSL: if not SSL:
# Connect ... # Connect ...
s.connect((ip, PORT)) s.connect((ip, PORT))
# ... and close # ... and close
s.close() s.close()
else: else:
# WRAP SOCKET # WRAP SOCKET
wrappedSocket = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) wrappedSocket = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1)
# CONNECT # CONNECT
wrappedSocket.connect((ip, PORT)) wrappedSocket.connect((ip, PORT))
# CLOSE SOCKET CONNECTION # CLOSE SOCKET CONNECTION
wrappedSocket.close() wrappedSocket.close()
queue.put((ip, True)) queue.put((ip, True))
if DEBUG: logging.debug("connect to %s OK", ip) if DEBUG: logging.debug("connect to %s OK", ip)
except: except:
queue.put((ip, False)) queue.put((ip, False))
if DEBUG: logging.debug("connect to %s not OK", ip) if DEBUG: logging.debug("connect to %s not OK", ip)
pass pass
def happyeyeballs(HOST, **kwargs): def happyeyeballs(HOST, **kwargs):
# Happyeyeballs function, with caching of the results # Happyeyeballs function, with caching of the results
# Fill out the parameters into the variables # Fill out the parameters into the variables
try: try:
PORT = kwargs['port'] PORT = kwargs['port']
except: except:
PORT = 80 PORT = 80
try: try:
SSL = kwargs['ssl'] SSL = kwargs['ssl']
except: except:
SSL = False SSL = False
try: try:
preferipv6 = kwargs['preferipv6'] preferipv6 = kwargs['preferipv6']
except: except:
preferipv6 = True # prefer IPv6, so give IPv6 connects a head start by delaying IPv4 preferipv6 = True # prefer IPv6, so give IPv6 connects a head start by delaying IPv4
# Find out if a cached result is available, and recent enough: # Find out if a cached result is available, and recent enough:
timecurrent = int(time.time()) # current time in seconds since epoch timecurrent = int(time.time()) # current time in seconds since epoch
retentionseconds = 100 retentionseconds = 100
hostkey = (HOST, PORT, SSL, preferipv6) # Example key: (u'ssl.astraweb.com', 563, True, True) hostkey = (HOST, PORT, SSL, preferipv6) # Example key: (u'ssl.astraweb.com', 563, True, True)
try: try:
happyeyeballs.happylist[hostkey] # just to check: does it exist? happyeyeballs.happylist[hostkey] # just to check: does it exist?
# No exception, so entry exists, so let's check the time: # No exception, so entry exists, so let's check the time:
timecached = happyeyeballs.happylist[hostkey][1] timecached = happyeyeballs.happylist[hostkey][1]
if timecurrent - timecached <= retentionseconds: if timecurrent - timecached <= retentionseconds:
if DEBUG: logging.debug("existing cached result recent enough") if DEBUG: logging.debug("existing cached result recent enough")
return happyeyeballs.happylist[hostkey][0] return happyeyeballs.happylist[hostkey][0]
else: else:
if DEBUG: logging.debug("existing cached result too old. Find a new one") if DEBUG: logging.debug("existing cached result too old. Find a new one")
# Continue a few lines down # Continue a few lines down
except: except:
# Exception, so entry not there, so we have to fill it out # Exception, so entry not there, so we have to fill it out
if DEBUG: logging.debug("Host not yet in the cache. Find entry") if DEBUG: logging.debug("Host not yet in the cache. Find entry")
pass pass
# we only arrive here if the entry has to be determined. So let's do that: # we only arrive here if the entry has to be determined. So let's do that:
# We have to determine the (new) best IP address # We have to determine the (new) best IP address
start = time.clock() start = time.clock()
if DEBUG: logging.debug("\n\n%s %s %s %s", HOST, PORT, SSL, preferipv6) if DEBUG: logging.debug("\n\n%s %s %s %s", HOST, PORT, SSL, preferipv6)
ipv4delay = 0 ipv4delay = 0
try: try:
# Check if there is an AAAA / IPv6 result for this host: # Check if there is an AAAA / IPv6 result for this host:
info = socket.getaddrinfo(HOST, PORT, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_IP, socket.AI_CANONNAME) socket.getaddrinfo(HOST, PORT, socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_IP, socket.AI_CANONNAME)
if DEBUG: logging.debug("IPv6 address found for %s", HOST) if DEBUG: logging.debug("IPv6 address found for %s", HOST)
if preferipv6: if preferipv6:
ipv4delay=0.1 # preferipv6, AND at least one IPv6 found, so give IPv4 (!) a delay so that IPv6 has a head start and is preferred ipv4delay=0.1 # preferipv6, AND at least one IPv6 found, so give IPv4 (!) a delay so that IPv6 has a head start and is preferred
except: except:
if DEBUG: logging.debug("No IPv6 address found for %s", HOST) if DEBUG: logging.debug("No IPv6 address found for %s", HOST)
myqueue = Queue.Queue() # queue used for threads giving back the results myqueue = Queue.Queue() # queue used for threads giving back the results
try: try:
# Get all IP (IPv4 and IPv6) addresses: # Get all IP (IPv4 and IPv6) addresses:
allinfo = socket.getaddrinfo(HOST, PORT, 0, 0, socket.IPPROTO_TCP) allinfo = socket.getaddrinfo(HOST, PORT, 0, 0, socket.IPPROTO_TCP)
for info in allinfo: for info in allinfo:
address = info[4][0] address = info[4][0]
thisthread = threading.Thread(target=do_socket_connect, args=(myqueue, address, PORT, SSL, ipv4delay)) thisthread = threading.Thread(target=do_socket_connect, args=(myqueue, address, PORT, SSL, ipv4delay))
thisthread.daemon = True thisthread.daemon = True
thisthread.start() thisthread.start()
result = None # default return value, used if none of threads says True/"OK", so no connect on any IP address result = None # default return value, used if none of threads says True/"OK", so no connect on any IP address
# start reading from the Queue for message from the threads: # start reading from the Queue for message from the threads:
for i in range(len(allinfo)): for i in range(len(allinfo)):
s = myqueue.get() # get a response s = myqueue.get() # get a response
if s[1] == True: if s[1] == True:
result = s[0] result = s[0]
break # the first True/"OK" is enough, so break out of for loop break # the first True/"OK" is enough, so break out of for loop
except: except:
if DEBUG: logging.debug("something went wrong in the try block") if DEBUG: logging.debug("something went wrong in the try block")
result = None result = None
logging.info("Quickest IP address for %s (port %s, ssl %s, preferipv6 %s) is %s", HOST, PORT, SSL, preferipv6, result) logging.info("Quickest IP address for %s (port %s, ssl %s, preferipv6 %s) is %s", HOST, PORT, SSL, preferipv6, result)
delay = int(1000 * (time.clock() - start)) delay = int(1000 * (time.clock() - start))
logging.debug("Happy Eyeballs lookup and port connect took %s ms", delay) logging.debug("Happy Eyeballs lookup and port connect took %s ms", delay)
# We're done. Store and return the result # We're done. Store and return the result
if result: if result:
happyeyeballs.happylist[hostkey] = ( result, timecurrent ) happyeyeballs.happylist[hostkey] = ( result, timecurrent )
if DEBUG: logging.debug("Determined new result for %s with result %s", (hostkey, happyeyeballs.happylist[hostkey]) ) if DEBUG: logging.debug("Determined new result for %s with result %s", (hostkey, happyeyeballs.happylist[hostkey]) )
return result return result
happyeyeballs.happylist = {} # The cached results. This static variable must be after the def happyeyeballs() happyeyeballs.happylist = {} # The cached results. This static variable must be after the def happyeyeballs()
@ -152,27 +152,27 @@ happyeyeballs.happylist = {} # The cached results. This static variable must
if __name__ == '__main__': if __name__ == '__main__':
logger = logging.getLogger('') logger = logging.getLogger('')
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
if DEBUG: logger.setLevel(logging.DEBUG) if DEBUG: logger.setLevel(logging.DEBUG)
# plain HTTP/HTTPS sites: # plain HTTP/HTTPS sites:
print happyeyeballs('www.google.com') print happyeyeballs('www.google.com')
print happyeyeballs('www.google.com', port=443, ssl=True) print happyeyeballs('www.google.com', port=443, ssl=True)
print happyeyeballs('www.nu.nl') print happyeyeballs('www.nu.nl')
# newsservers: # newsservers:
print happyeyeballs('newszilla6.xs4all.nl', port=119) print happyeyeballs('newszilla6.xs4all.nl', port=119)
print happyeyeballs('newszilla.xs4all.nl', port=119) print happyeyeballs('newszilla.xs4all.nl', port=119)
print happyeyeballs('block.cheapnews.eu', port=119) print happyeyeballs('block.cheapnews.eu', port=119)
print happyeyeballs('block.cheapnews.eu', port=443, ssl=True) print happyeyeballs('block.cheapnews.eu', port=443, ssl=True)
print happyeyeballs('sslreader.eweka.nl', port=563, ssl=True) print happyeyeballs('sslreader.eweka.nl', port=563, ssl=True)
print happyeyeballs('news.thundernews.com', port=119) print happyeyeballs('news.thundernews.com', port=119)
print happyeyeballs('news.thundernews.com', port=119, preferipv6=False) print happyeyeballs('news.thundernews.com', port=119, preferipv6=False)
print happyeyeballs('secure.eu.thundernews.com', port=563, ssl=True) print happyeyeballs('secure.eu.thundernews.com', port=563, ssl=True)
# Strange cases # Strange cases
print happyeyeballs('does.not.resolve', port=443, ssl=True) print happyeyeballs('does.not.resolve', port=443, ssl=True)
print happyeyeballs('www.google.com', port=119) print happyeyeballs('www.google.com', port=119)
print happyeyeballs('216.58.211.164') print happyeyeballs('216.58.211.164')

2
sabnzbd/utils/pystone.py

@ -236,7 +236,7 @@ def Func2(StrParI1, StrParI2):
if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1: if Func1(StrParI1[IntLoc], StrParI2[IntLoc+1]) == Ident1:
CharLoc = 'A' CharLoc = 'A'
IntLoc = IntLoc + 1 IntLoc = IntLoc + 1
if CharLoc >= 'W' and CharLoc <= 'Z': if 'W' <= CharLoc <= 'Z':
IntLoc = 7 IntLoc = 7
if CharLoc == 'X': if CharLoc == 'X':
return TRUE return TRUE

4
sabnzbd/utils/servertests.py

@ -90,7 +90,7 @@ def test_nntp_server(host, port, server=None, username=None, password=None, ssl=
nw.recv_chunk(block=True) nw.recv_chunk(block=True)
nw.finish_connect(nw.status_code) nw.finish_connect(nw.status_code)
except socket.timeout, e: except socket.timeout:
if port != 119 and not ssl: if port != 119 and not ssl:
return False, T('Timed out: Try enabling SSL or connecting on a different port.') return False, T('Timed out: Try enabling SSL or connecting on a different port.')
else: else:
@ -103,7 +103,7 @@ def test_nntp_server(host, port, server=None, username=None, password=None, ssl=
return False, unicode(e) return False, unicode(e)
except TypeError, e: except TypeError:
return False, T('Invalid server address.') return False, T('Invalid server address.')
except IndexError: except IndexError:

5
sabnzbd/zconfig.py

@ -79,11 +79,6 @@ def set_bonjour(host=None, port=None):
return return
name = hostname() name = hostname()
if '.local' in name:
suffix = ''
else:
suffix = '.local'
logging.debug('Try to publish in Bonjour as "%s" (%s:%s)', name, host, port) logging.debug('Try to publish in Bonjour as "%s" (%s:%s)', name, host, port)
try: try:
refObject = pybonjour.DNSServiceRegister( refObject = pybonjour.DNSServiceRegister(

1
tests/conftest.py

@ -21,7 +21,6 @@ tests.conftest - Wrappers to start SABnzbd for testing
import os import os
import itertools import itertools
import urllib2
import pytest import pytest
import shutil import shutil
import time import time

2
util/apireg.py

@ -69,7 +69,7 @@ def set_connection_info(url, user=True):
try: try:
hive = _winreg.ConnectRegistry(None, section) hive = _winreg.ConnectRegistry(None, section)
try: try:
key = _winreg.CreateKey(hive, keypath) _winreg.CreateKey(hive, keypath)
except: except:
pass pass
key = _winreg.OpenKey(hive, keypath) key = _winreg.OpenKey(hive, keypath)

1
util/mailslot.py

@ -19,7 +19,6 @@
sabnzbd.mailslot - Mailslot communication sabnzbd.mailslot - Mailslot communication
""" """
import os
from win32file import GENERIC_WRITE, FILE_SHARE_READ, \ from win32file import GENERIC_WRITE, FILE_SHARE_READ, \
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL
from ctypes import c_uint, c_buffer, byref, sizeof, windll from ctypes import c_uint, c_buffer, byref, sizeof, windll

Loading…
Cancel
Save