[Lint] Cleanup code to pass PyLint Warning category

Selected Warning messages disabled in pylintrc:
  * unused-argument: Quite a large and disruptive change if enabled.
  * broad-except: Most required in-depth investigation to determine type.
  * fixme: Not important
  * protected-access: Complicated to fix
  * import-error: Too many false-positives
  * unidiomatic-typecheck: Should be fixed in the next round of checks.
  * unused-variable: Again large and disruptive changes.
  * global-statement: Most usage is required.
  * attribute-defined-outside-init: Should be fixed in next round of checks.
  * arguments-differ: Possible false-positives, needs revisited.
  * no-init, non-parent-init-called, super-init-not-called: False-positives?
  * signature-differs: False-positives?
This commit is contained in:
Calum Lind 2015-10-22 23:14:14 +01:00
commit 807fa609f9
65 changed files with 411 additions and 398 deletions

View file

@ -22,9 +22,9 @@ supports.
REQUIRED_VERSION = "1.0.6.0" REQUIRED_VERSION = "1.0.6.0"
def check_version(lt): def check_version(libtorrent):
from deluge.common import VersionSplit from deluge.common import VersionSplit
if VersionSplit(lt.version) < VersionSplit(REQUIRED_VERSION): if VersionSplit(libtorrent.version) < VersionSplit(REQUIRED_VERSION):
raise ImportError("This version of Deluge requires libtorrent >=%s!" % REQUIRED_VERSION) raise ImportError("This version of Deluge requires libtorrent >=%s!" % REQUIRED_VERSION)
try: try:

View file

@ -30,7 +30,7 @@ try:
import dbus import dbus
bus = dbus.SessionBus() bus = dbus.SessionBus()
dbus_fileman = bus.get_object("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1") dbus_fileman = bus.get_object("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1")
except: except Exception:
dbus_fileman = None dbus_fileman = None
@ -527,7 +527,7 @@ def get_magnet_info(uri):
return False return False
def create_magnet_uri(infohash, name=None, trackers=[]): def create_magnet_uri(infohash, name=None, trackers=None):
""" """
Creates a magnet uri Creates a magnet uri
@ -570,9 +570,9 @@ def get_path_size(path):
return os.path.getsize(path) return os.path.getsize(path)
dir_size = 0 dir_size = 0
for (p, dirs, files) in os.walk(path): for (p, dummy_dirs, files) in os.walk(path):
for file in files: for _file in files:
filename = os.path.join(p, file) filename = os.path.join(p, _file)
dir_size += os.path.getsize(filename) dir_size += os.path.getsize(filename)
return dir_size return dir_size
@ -840,9 +840,9 @@ def set_env_variable(name, value):
if result == 0: if result == 0:
raise Warning raise Warning
except Exception: except Exception:
log.warning('Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % name) log.warning('Failed to set Env Var \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name)
else: else:
log.debug('Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')' % (name, value)) log.debug('Set Env Var \'%s\' to \'%s\' (\'kernel32.SetEnvironmentVariableW\')', name, value)
# Update the copy maintained by msvcrt (used by gtk+ runtime) # Update the copy maintained by msvcrt (used by gtk+ runtime)
try: try:
@ -850,9 +850,9 @@ def set_env_variable(name, value):
if result != 0: if result != 0:
raise Warning raise Warning
except Exception: except Exception:
log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')' % name) log.warning('Failed to set Env Var \'%s\' (\'msvcrt._putenv\')', name)
else: else:
log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')' % (name, value)) log.debug('Set Env Var \'%s\' to \'%s\' (\'msvcrt._putenv\')', name, value)
# Update the copy maintained by whatever c runtime is used by Python # Update the copy maintained by whatever c runtime is used by Python
try: try:
@ -862,9 +862,9 @@ def set_env_variable(name, value):
if result != 0: if result != 0:
raise Warning raise Warning
except Exception: except Exception:
log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')' % (name, msvcrtname)) log.warning('Failed to set Env Var \'%s\' (\'%s._putenv\')', name, msvcrtname)
else: else:
log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')' % (name, value, msvcrtname)) log.debug('Set Env Var \'%s\' to \'%s\' (\'%s._putenv\')', name, value, msvcrtname)
def set_language(lang): def set_language(lang):

View file

@ -248,7 +248,7 @@ class ComponentRegistry(object):
else: else:
return succeed(None) return succeed(None)
def start(self, names=[]): def start(self, names=None):
""" """
Starts Components that are currently in a Stopped state and their Starts Components that are currently in a Stopped state and their
dependencies. If *names* is specified, will only start those dependencies. If *names* is specified, will only start those
@ -284,7 +284,7 @@ class ComponentRegistry(object):
return DeferredList(deferreds) return DeferredList(deferreds)
def stop(self, names=[]): def stop(self, names=None):
""" """
Stops Components that are currently not in a Stopped state. If Stops Components that are currently not in a Stopped state. If
*names* is specified, then it will only stop those Components, *names* is specified, then it will only stop those Components,
@ -322,7 +322,7 @@ class ComponentRegistry(object):
return DeferredList(deferreds) return DeferredList(deferreds)
def pause(self, names=[]): def pause(self, names=None):
""" """
Pauses Components that are currently in a Started state. If Pauses Components that are currently in a Started state. If
*names* is specified, then it will only pause those Components, *names* is specified, then it will only pause those Components,
@ -348,7 +348,7 @@ class ComponentRegistry(object):
return DeferredList(deferreds) return DeferredList(deferreds)
def resume(self, names=[]): def resume(self, names=None):
""" """
Resumes Components that are currently in a Paused state. If Resumes Components that are currently in a Paused state. If
*names* is specified, then it will only resume those Components, *names* is specified, then it will only resume those Components,
@ -386,7 +386,7 @@ class ComponentRegistry(object):
""" """
def on_stopped(result): def on_stopped(result):
return DeferredList(map(lambda c: c._component_shutdown(), self.components.values())) return DeferredList([comp._component_shutdown() for comp in self.components.values()])
return self.stop(self.components.keys()).addCallback(on_stopped) return self.stop(self.components.keys()).addCallback(on_stopped)

View file

@ -198,7 +198,7 @@ what is currently in the config and it could not convert the value
global callLater global callLater
if callLater is None: if callLater is None:
# Must import here and not at the top or it will throw ReactorAlreadyInstalledError # Must import here and not at the top or it will throw ReactorAlreadyInstalledError
from twisted.internet.reactor import callLater from twisted.internet.reactor import callLater # pylint: disable=redefined-outer-name
# Run the set_function for this key if any # Run the set_function for this key if any
try: try:
for func in self.__set_functions[key]: for func in self.__set_functions[key]:
@ -210,7 +210,7 @@ what is currently in the config and it could not convert the value
for func in self.__change_callbacks: for func in self.__change_callbacks:
func(key, value) func(key, value)
callLater(0, do_change_callbacks, key, value) callLater(0, do_change_callbacks, key, value)
except: except Exception:
pass pass
# We set the save_timer for 5 seconds if not already set # We set the save_timer for 5 seconds if not already set
@ -295,7 +295,7 @@ what is currently in the config and it could not convert the value
global callLater global callLater
if callLater is None: if callLater is None:
# Must import here and not at the top or it will throw ReactorAlreadyInstalledError # Must import here and not at the top or it will throw ReactorAlreadyInstalledError
from twisted.internet.reactor import callLater from twisted.internet.reactor import callLater # pylint: disable=redefined-outer-name
# We set the save_timer for 5 seconds if not already set # We set the save_timer for 5 seconds if not already set
if not self._save_timer or not self._save_timer.active(): if not self._save_timer or not self._save_timer.active():

View file

@ -103,11 +103,13 @@ class Core(component.Component):
else: else:
log.error("Invalid listen interface (must be IP Address): %s", listen_interface) log.error("Invalid listen interface (must be IP Address): %s", listen_interface)
def start(self):
"""Starts the core"""
# New release check information # New release check information
self.__new_release = None self.__new_release = None
def start(self):
"""Starts the core"""
pass
def stop(self): def stop(self):
log.debug("Core stopping...") log.debug("Core stopping...")
@ -726,8 +728,8 @@ class Core(component.Component):
def _create_torrent_thread(self, path, tracker, piece_length, comment, target, def _create_torrent_thread(self, path, tracker, piece_length, comment, target,
webseeds, private, created_by, trackers, add_to_session): webseeds, private, created_by, trackers, add_to_session):
import deluge.metafile from deluge import metafile
deluge.metafile.make_meta_file( metafile.make_meta_file(
path, path,
tracker, tracker,
piece_length, piece_length,

View file

@ -234,11 +234,11 @@ class FilterManager(component.Component):
init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list())) init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list()))
return init_state return init_state
def register_filter(self, id, filter_func, filter_value=None): def register_filter(self, filter_id, filter_func, filter_value=None):
self.registered_filters[id] = filter_func self.registered_filters[filter_id] = filter_func
def deregister_filter(self, id): def deregister_filter(self, filter_id):
del self.registered_filters[id] del self.registered_filters[filter_id]
def register_tree_field(self, field, init_func=lambda: {}): def register_tree_field(self, field, init_func=lambda: {}):
self.tree_fields[field] = init_func self.tree_fields[field] = init_func

View file

@ -86,5 +86,5 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
log.debug("Deregistering status field %s with PluginManager", field) log.debug("Deregistering status field %s with PluginManager", field)
try: try:
del self.status_fields[field] del self.status_fields[field]
except: except Exception:
log.warning("Unable to deregister status field %s", field) log.warning("Unable to deregister status field %s", field)

View file

@ -121,11 +121,11 @@ class PreferencesManager(component.Component):
log.warning("New proxy config is: %s", self.config["proxy"]) log.warning("New proxy config is: %s", self.config["proxy"])
del self.config["proxies"] del self.config["proxies"]
def start(self):
self.core = component.get("Core") self.core = component.get("Core")
self.session = component.get("Core").session self.session = component.get("Core").session
self.new_release_timer = None self.new_release_timer = None
def start(self):
# Set the initial preferences on start-up # Set the initial preferences on start-up
for key in DEFAULT_PREFS: for key in DEFAULT_PREFS:
self.do_config_set_func(key, self.config[key]) self.do_config_set_func(key, self.config[key])
@ -270,13 +270,13 @@ class PreferencesManager(component.Component):
pe_settings.allowed_enc_level = lt.enc_level(pe_enc_level[self.config["enc_level"]]) pe_settings.allowed_enc_level = lt.enc_level(pe_enc_level[self.config["enc_level"]])
pe_settings.prefer_rc4 = True pe_settings.prefer_rc4 = True
self.session.set_pe_settings(pe_settings) self.session.set_pe_settings(pe_settings)
set = self.session.get_pe_settings() pe_sess_settings = self.session.get_pe_settings()
log.debug("encryption settings:\n\t\t\tout_policy: %s\n\t\t\ log.debug("encryption settings:\n\t\t\tout_policy: %s\n\t\t\
in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s", in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s",
set.out_enc_policy, pe_sess_settings.out_enc_policy,
set.in_enc_policy, pe_sess_settings.in_enc_policy,
set.allowed_enc_level, pe_sess_settings.allowed_enc_level,
set.prefer_rc4) pe_sess_settings.prefer_rc4)
def _on_set_max_connections_global(self, key, value): def _on_set_max_connections_global(self, key, value):
log.debug("max_connections_global set to %s..", value) log.debug("max_connections_global set to %s..", value)
@ -346,8 +346,9 @@ class PreferencesManager(component.Component):
self.session_set_setting("dont_count_slow_torrents", value) self.session_set_setting("dont_count_slow_torrents", value)
def _on_set_send_info(self, key, value): def _on_set_send_info(self, key, value):
log.debug("Sending anonymous stats..")
"""sends anonymous stats home""" """sends anonymous stats home"""
log.debug("Sending anonymous stats..")
class SendInfoThread(threading.Thread): class SendInfoThread(threading.Thread):
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
@ -358,7 +359,6 @@ class PreferencesManager(component.Component):
now = time.time() now = time.time()
# check if we've done this within the last week or never # check if we've done this within the last week or never
if (now - self.config["info_sent"]) >= (60 * 60 * 24 * 7): if (now - self.config["info_sent"]) >= (60 * 60 * 24 * 7):
import deluge.common
from urllib import quote_plus from urllib import quote_plus
from urllib2 import urlopen from urllib2 import urlopen
import platform import platform

View file

@ -194,7 +194,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
""" """
Sends an error response with the contents of the exception that was raised. Sends an error response with the contents of the exception that was raised.
""" """
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() exceptionType, exceptionValue, dummy_exceptionTraceback = sys.exc_info()
formated_tb = traceback.format_exc() formated_tb = traceback.format_exc()
try: try:
self.sendData(( self.sendData((
@ -205,17 +205,17 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
exceptionValue._kwargs, exceptionValue._kwargs,
formated_tb formated_tb
)) ))
except AttributeError as err: except AttributeError:
# This is not a deluge exception (object has no attribute '_args), let's wrap it # This is not a deluge exception (object has no attribute '_args), let's wrap it
log.error("An exception occurred while sending RPC_ERROR to " log.error("An exception occurred while sending RPC_ERROR to "
"client. Wrapping it and resending. Error to " "client. Wrapping it and resending. Error to "
"send(causing exception goes next):\n%s", formated_tb) "send(causing exception goes next):\n%s", formated_tb)
try: try:
raise WrappedException(str(exceptionValue), exceptionType.__name__, formated_tb) raise WrappedException(str(exceptionValue), exceptionType.__name__, formated_tb)
except: except Exception:
send_error() send_error()
except Exception as err: except Exception as ex:
log.error("An exception occurred while sending RPC_ERROR to client: %s", err) log.error("An exception occurred while sending RPC_ERROR to client: %s", ex)
if method == "daemon.info": if method == "daemon.info":
# This is a special case and used in the initial connection process # This is a special case and used in the initial connection process
@ -241,7 +241,6 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
self.sendData((RPC_RESPONSE, request_id, (ret))) self.sendData((RPC_RESPONSE, request_id, (ret)))
if not ret: if not ret:
self.transport.loseConnection() self.transport.loseConnection()
finally:
return return
elif method == "daemon.set_event_interest" and self.valid_session(): elif method == "daemon.set_event_interest" and self.valid_session():
log.debug("RPC dispatch daemon.set_event_interest") log.debug("RPC dispatch daemon.set_event_interest")
@ -256,7 +255,6 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
send_error() send_error()
else: else:
self.sendData((RPC_RESPONSE, request_id, (True))) self.sendData((RPC_RESPONSE, request_id, (True)))
finally:
return return
if method in self.factory.methods and self.valid_session(): if method in self.factory.methods and self.valid_session():
@ -454,7 +452,7 @@ class RPCServer(component.Component):
:returns: the auth level :returns: the auth level
:rtype: int :rtype: int
""" """
self.factory.methods[rpc]._rpcserver_auth_level return self.factory.methods[rpc]._rpcserver_auth_level
def is_session_valid(self, session_id): def is_session_valid(self, session_id):
""" """

View file

@ -368,12 +368,12 @@ class Torrent(object):
# If we are turning off this option, call set_file_priorities to # If we are turning off this option, call set_file_priorities to
# reset all the piece priorities # reset all the piece priorities
self.set_file_priorities(self.options["file_priorities"]) self.set_file_priorities(self.options["file_priorities"])
return return None, None
if not self.has_metadata: if not self.has_metadata:
return return None, None
if self.get_status(["storage_mode"])["storage_mode"] == "compact": if self.get_status(["storage_mode"])["storage_mode"] == "compact":
log.debug("Setting first/last priority with compact allocation does not work!") log.debug("Setting first/last priority with compact allocation does not work!")
return return None, None
# A list of priorities for each piece in the torrent # A list of priorities for each piece in the torrent
priorities = self.handle.piece_priorities() priorities = self.handle.piece_priorities()
prioritized_pieces = [] prioritized_pieces = []

View file

@ -42,10 +42,12 @@ class HTTPDownloader(client.HTTPDownloader):
""" """
self.part_callback = part_callback self.part_callback = part_callback
self.current_length = 0 self.current_length = 0
self.total_length = 0
self.decoder = None self.decoder = None
self.value = filename self.value = filename
self.force_filename = force_filename self.force_filename = force_filename
self.allow_compression = allow_compression self.allow_compression = allow_compression
self.code = None
agent = "Deluge/%s (http://deluge-torrent.org)" % get_version() agent = "Deluge/%s (http://deluge-torrent.org)" % get_version()
client.HTTPDownloader.__init__(self, url, filename, headers=headers, agent=agent) client.HTTPDownloader.__init__(self, url, filename, headers=headers, agent=agent)
@ -125,14 +127,14 @@ def sanitise_filename(filename):
if os.path.basename(filename) != filename: if os.path.basename(filename) != filename:
# Dodgy server, log it # Dodgy server, log it
log.warning("Potentially malicious server: trying to write to file '%s'" % filename) log.warning("Potentially malicious server: trying to write to file '%s'", filename)
# Only use the basename # Only use the basename
filename = os.path.basename(filename) filename = os.path.basename(filename)
filename = filename.strip() filename = filename.strip()
if filename.startswith(".") or ";" in filename or "|" in filename: if filename.startswith(".") or ";" in filename or "|" in filename:
# Dodgy server, log it # Dodgy server, log it
log.warning("Potentially malicious server: trying to write to file '%s'" % filename) log.warning("Potentially malicious server: trying to write to file '%s'", filename)
return filename return filename
@ -178,7 +180,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
# In Twisted 13.1.0 _parse() function replaced by _URI class. # In Twisted 13.1.0 _parse() function replaced by _URI class.
# In Twisted 15.0.0 _URI class renamed to URI. # In Twisted 15.0.0 _URI class renamed to URI.
if hasattr(client, "_parse"): if hasattr(client, "_parse"):
scheme, host, port, path = client._parse(url) scheme, host, port, dummy_path = client._parse(url)
else: else:
try: try:
from twisted.web.client import _URI as URI from twisted.web.client import _URI as URI
@ -203,7 +205,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
""" """
A custom context factory to add a server name for TLS connections. A custom context factory to add a server name for TLS connections.
""" """
def getContext(self, hostname=None, port=None): # NOQA def getContext(self): # NOQA
ctx = ssl.ClientContextFactory.getContext(self) ctx = ssl.ClientContextFactory.getContext(self)
ClientTLSOptions(host, ctx) ClientTLSOptions(host, ctx)
return ctx return ctx

View file

@ -12,6 +12,7 @@
import inspect import inspect
import logging import logging
import logging.handlers
import os import os
from twisted.internet import defer from twisted.internet import defer
@ -94,7 +95,6 @@ class Logging(LoggingLoggerClass):
return rv return rv
levels = { levels = {
"none": logging.NOTSET,
"info": logging.INFO, "info": logging.INFO,
"warn": logging.WARNING, "warn": logging.WARNING,
"warning": logging.WARNING, "warning": logging.WARNING,
@ -114,7 +114,6 @@ def setup_logger(level="error", filename=None, filemode="w"):
:param level: str, the level to log :param level: str, the level to log
:param filename: str, the file to log to :param filename: str, the file to log to
""" """
import logging
if logging.getLoggerClass() is not Logging: if logging.getLoggerClass() is not Logging:
logging.setLoggerClass(Logging) logging.setLoggerClass(Logging)
@ -126,7 +125,6 @@ def setup_logger(level="error", filename=None, filemode="w"):
root_logger = logging.getLogger() root_logger = logging.getLogger()
if filename and filemode == "a": if filename and filemode == "a":
import logging.handlers
handler = logging.handlers.RotatingFileHandler( handler = logging.handlers.RotatingFileHandler(
filename, filemode, filename, filemode,
maxBytes=50 * 1024 * 1024, # 50 Mb maxBytes=50 * 1024 * 1024, # 50 Mb
@ -135,7 +133,6 @@ def setup_logger(level="error", filename=None, filemode="w"):
delay=0 delay=0
) )
elif filename and filemode == "w": elif filename and filemode == "w":
import logging.handlers
handler = getattr( handler = getattr(
logging.handlers, "WatchedFileHandler", logging.FileHandler)( logging.handlers, "WatchedFileHandler", logging.FileHandler)(
filename, filemode, "utf-8", delay=0 filename, filemode, "utf-8", delay=0

View file

@ -168,7 +168,7 @@ class PluginManagerBase:
cont_lines = [] cont_lines = []
# Missing plugin info # Missing plugin info
if not self.pkg_env[name]: if not self.pkg_env[name]:
log.warn("Failed to retrive info for plugin '%s'" % name) log.warn("Failed to retrive info for plugin '%s'", name)
for k in info: for k in info:
info[k] = "not available" info[k] = "not available"
return info return info

View file

@ -29,6 +29,7 @@ class PluginBase(component.Component):
class CorePluginBase(PluginBase): class CorePluginBase(PluginBase):
def __init__(self, plugin_name): def __init__(self, plugin_name):
super(CorePluginBase, self).__init__("CorePlugin." + plugin_name) super(CorePluginBase, self).__init__("CorePlugin." + plugin_name)
# Register RPC methods # Register RPC methods
@ -38,12 +39,25 @@ class CorePluginBase(PluginBase):
def __del__(self): def __del__(self):
component.get("RPCServer").deregister_object(self) component.get("RPCServer").deregister_object(self)
def enable(self):
super(CorePluginBase, self).enable()
def disable(self):
super(CorePluginBase, self).disable()
class GtkPluginBase(PluginBase): class GtkPluginBase(PluginBase):
def __init__(self, plugin_name): def __init__(self, plugin_name):
super(GtkPluginBase, self).__init__("GtkPlugin." + plugin_name) super(GtkPluginBase, self).__init__("GtkPlugin." + plugin_name)
log.debug("GtkPlugin initialized..") log.debug("GtkPlugin initialized..")
def enable(self):
super(GtkPluginBase, self).enable()
def disable(self):
super(GtkPluginBase, self).disable()
class WebPluginBase(PluginBase): class WebPluginBase(PluginBase):

View file

@ -8,13 +8,13 @@ from twisted.internet.error import CannotListenError
import deluge.common import deluge.common
import deluge.configmanager import deluge.configmanager
import deluge.core.preferencesmanager
import deluge.log import deluge.log
deluge.log.setup_logger("none") deluge.log.setup_logger("none")
def disable_new_release_check(): def disable_new_release_check():
import deluge.core.preferencesmanager
deluge.core.preferencesmanager.DEFAULT_PREFS["new_release_check"] = False deluge.core.preferencesmanager.DEFAULT_PREFS["new_release_check"] = False

View file

@ -2,6 +2,7 @@ from twisted.internet import defer
from twisted.internet.error import CannotListenError from twisted.internet.error import CannotListenError
import deluge.component as component import deluge.component as component
import deluge.ui.common
from deluge import error from deluge import error
from deluge.core.authmanager import AUTH_LEVEL_ADMIN from deluge.core.authmanager import AUTH_LEVEL_ADMIN
from deluge.ui.client import Client, DaemonSSLProxy, client from deluge.ui.client import Client, DaemonSSLProxy, client
@ -72,12 +73,12 @@ class ClientTestCase(BaseTestCase):
try: try:
self.core = common.start_core(listen_port=self.listen_port) self.core = common.start_core(listen_port=self.listen_port)
except CannotListenError as ex: except CannotListenError as ex:
error = ex exception_error = ex
self.listen_port += 1 self.listen_port += 1
else: else:
break break
else: else:
raise error raise exception_error
def tear_down(self): def tear_down(self):
self.core.terminate() self.core.terminate()
@ -97,8 +98,7 @@ class ClientTestCase(BaseTestCase):
return d return d
def test_connect_localclient(self): def test_connect_localclient(self):
from deluge.ui import common username, password = deluge.ui.common.get_localhost_auth()
username, password = common.get_localhost_auth()
d = client.connect( d = client.connect(
"localhost", self.listen_port, username=username, password=password "localhost", self.listen_port, username=username, password=password
) )
@ -112,8 +112,7 @@ class ClientTestCase(BaseTestCase):
return d return d
def test_connect_bad_password(self): def test_connect_bad_password(self):
from deluge.ui import common username, password = deluge.ui.common.get_localhost_auth()
username, password = common.get_localhost_auth()
d = client.connect( d = client.connect(
"localhost", self.listen_port, username=username, password=password + "1" "localhost", self.listen_port, username=username, password=password + "1"
) )
@ -129,8 +128,7 @@ class ClientTestCase(BaseTestCase):
return d return d
def test_connect_without_password(self): def test_connect_without_password(self):
from deluge.ui import common username, password = deluge.ui.common.get_localhost_auth()
username, password = common.get_localhost_auth()
d = client.connect( d = client.connect(
"localhost", self.listen_port, username=username "localhost", self.listen_port, username=username
) )
@ -147,8 +145,7 @@ class ClientTestCase(BaseTestCase):
return d return d
def test_connect_without_sending_client_version_fails(self): def test_connect_without_sending_client_version_fails(self):
from deluge.ui import common username, password = deluge.ui.common.get_localhost_auth()
username, password = common.get_localhost_auth()
no_version_sending_client = NoVersionSendingClient() no_version_sending_client = NoVersionSendingClient()
d = no_version_sending_client.connect( d = no_version_sending_client.connect(
"localhost", self.listen_port, username=username, password=password "localhost", self.listen_port, username=username, password=password

View file

@ -11,6 +11,7 @@ from twisted.web.resource import Resource
from twisted.web.server import Site from twisted.web.server import Site
from twisted.web.static import File from twisted.web.static import File
import deluge.common
import deluge.component as component import deluge.component as component
import deluge.core.torrent import deluge.core.torrent
from deluge.core.core import Core from deluge.core.core import Core
@ -86,10 +87,12 @@ class CoreTestCase(BaseTestCase):
error = ex error = ex
self.listen_port += 1 self.listen_port += 1
else: else:
return result break
else: else:
raise error raise error
return result
def tear_down(self): def tear_down(self):
def on_shutdown(result): def on_shutdown(result):
@ -155,7 +158,6 @@ class CoreTestCase(BaseTestCase):
def test_add_magnet(self): def test_add_magnet(self):
info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00" info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
import deluge.common
uri = deluge.common.create_magnet_uri(info_hash) uri = deluge.common.create_magnet_uri(info_hash)
options = {} options = {}

View file

@ -9,13 +9,13 @@ class DecoratorsTestCase(unittest.TestCase):
return not func(*args, **kwargs) return not func(*args, **kwargs)
@proxy(negate) @proxy(negate)
def something(bool): def something(_bool):
return bool return _bool
@proxy(negate) @proxy(negate)
@proxy(negate) @proxy(negate)
def double_nothing(bool): def double_nothing(_bool):
return bool return _bool
self.assertTrue(something(False)) self.assertTrue(something(False))
self.assertFalse(something(True)) self.assertFalse(something(True))

View file

@ -8,7 +8,7 @@
# #
try: try:
import rencode import rencode # pylint: disable=relative-import
except ImportError: except ImportError:
import deluge.rencode as rencode import deluge.rencode as rencode

View file

@ -159,7 +159,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
# The rest just get's logged in debug level, just to log # The rest just get's logged in debug level, just to log
# what's happening # what's happening
log.debug(msg) log.debug(msg)
except: except Exception:
import traceback import traceback
log.error("Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s", log.error("Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s",
request[2], traceback.format_exc()) request[2], traceback.format_exc())
@ -426,8 +426,8 @@ class DaemonClassicProxy(DaemonProxy):
def __init__(self, event_handlers=None): def __init__(self, event_handlers=None):
if event_handlers is None: if event_handlers is None:
event_handlers = {} event_handlers = {}
import deluge.core.daemon from deluge.core import daemon
self.__daemon = deluge.core.daemon.Daemon(classic=True) self.__daemon = daemon.Daemon(classic=True)
log.debug("daemon created!") log.debug("daemon created!")
self.connected = True self.connected = True
self.host = "localhost" self.host = "localhost"

View file

@ -38,7 +38,6 @@ STATE_TRANSLATION = {
"Downloading": _("Downloading"), "Downloading": _("Downloading"),
"Seeding": _("Seeding"), "Seeding": _("Seeding"),
"Paused": _("Paused"), "Paused": _("Paused"),
"Checking": _("Checking"),
"Queued": _("Queued"), "Queued": _("Queued"),
"Error": _("Error"), "Error": _("Error"),
} }

View file

@ -83,7 +83,7 @@ def init_colors():
try: try:
curses.init_pair(counter, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(counter, curses.COLOR_WHITE, curses.COLOR_BLACK)
color_pairs[("white", "black")] = counter color_pairs[("white", "black")] = counter
except: except Exception:
pass pass

View file

@ -21,16 +21,16 @@ from deluge.ui.console.main import BaseCommand
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
def atom(next, token): def atom(_next, token):
"""taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm""" """taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm"""
if token[1] == "(": if token[1] == "(":
out = [] out = []
token = next() token = _next()
while token[1] != ")": while token[1] != ")":
out.append(atom(next, token)) out.append(atom(_next, token))
token = next() token = _next()
if token[1] == ",": if token[1] == ",":
token = next() token = _next()
return tuple(out) return tuple(out)
elif token[0] is tokenize.NUMBER or token[1] == "-": elif token[0] is tokenize.NUMBER or token[1] == "-":
try: try:
@ -118,7 +118,7 @@ class Command(BaseCommand):
if type(config[key]) != type(val): if type(config[key]) != type(val):
try: try:
val = type(config[key])(val) val = type(config[key])(val)
except: except TypeError:
self.config.write("{!error!}Configuration value provided has incorrect type.") self.config.write("{!error!}Configuration value provided has incorrect type.")
return return

View file

@ -38,7 +38,7 @@ class Command(BaseCommand):
def on_connect_fail(result): def on_connect_fail(result):
try: try:
msg = result.value.exception_msg msg = result.value.exception_msg
except: except AttributeError:
msg = result.value.args[0] msg = result.value.args[0]
self.console.write("{!error!}Failed to connect to %s:%s with reason: %s" % (host, port, msg)) self.console.write("{!error!}Failed to connect to %s:%s with reason: %s" % (host, port, msg))
return result return result

View file

@ -168,9 +168,9 @@ class Command(BaseCommand):
cols = 80 cols = 80
prevpath = [] prevpath = []
for i, file in enumerate(status["files"]): for i, _file in enumerate(status["files"]):
filename = file["path"].split(dirsep)[-1] filename = _file["path"].split(dirsep)[-1]
filepath = file["path"].split(dirsep)[:-1] filepath = _file["path"].split(dirsep)[:-1]
for depth, subdir in enumerate(filepath): for depth, subdir in enumerate(filepath):
indent = " " * depth * spaces_per_level indent = " " * depth * spaces_per_level
@ -199,10 +199,8 @@ class Command(BaseCommand):
col_priority += "{!input!}" col_priority += "{!input!}"
col_priority += fp col_priority += fp
rf = format_utils.remove_formatting def tlen(string):
return strwidth(format_utils.remove_formatting(string))
def tlen(s):
return strwidth(rf(s))
if not isinstance(col_filename, unicode): if not isinstance(col_filename, unicode):
col_filename = unicode(col_filename, "utf-8") col_filename = unicode(col_filename, "utf-8")

View file

@ -118,9 +118,8 @@ class Command(BaseCommand):
filedump = base64.encodestring(open(filepath, "rb").read()) filedump = base64.encodestring(open(filepath, "rb").read())
try: try:
client.core.upload_plugin(filename, filedump) client.core.upload_plugin(filename, filedump)
client.core.rescan_plugins() client.core.rescan_plugins()
except: except Exception:
self.console.write("{!error!}An error occurred, plugin was not installed") self.console.write("{!error!}An error occurred, plugin was not installed")
self.console.write("{!green!}Plugin was successfully installed: %s" % filename) self.console.write("{!green!}Plugin was successfully installed: %s" % filename)

View file

@ -99,12 +99,12 @@ class DelugeHelpFormatter(optparse.IndentedHelpFormatter):
replace_dict = { replace_dict = {
"<torrent-id>": "{!green!}%s{!input!}", "<torrent-id>": "{!green!}%s{!input!}",
"<state>": "{!yellow!}%s{!input!}", "<state>": "{!yellow!}%s{!input!}",
"\.\.\.": "{!yellow!}%s{!input!}", "\\.\\.\\.": "{!yellow!}%s{!input!}",
"\s\*\s": "{!blue!}%s{!input!}", "\\s\\*\\s": "{!blue!}%s{!input!}",
"(?<![\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}", "(?<![\\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}",
# "(\-[a-zA-Z0-9])": "{!red!}%s{!input!}", # "(\-[a-zA-Z0-9])": "{!red!}%s{!input!}",
"--[_\-a-zA-Z0-9]+": "{!green!}%s{!input!}", "--[_\\-a-zA-Z0-9]+": "{!green!}%s{!input!}",
"(\[|\])": "{!info!}%s{!input!}", "(\\[|\\])": "{!info!}%s{!input!}",
"<tab>": "{!white!}%s{!input!}", "<tab>": "{!white!}%s{!input!}",
"[_A-Z]{3,}": "{!cyan!}%s{!input!}", "[_A-Z]{3,}": "{!cyan!}%s{!input!}",
@ -181,13 +181,13 @@ class OptionParser(optparse.OptionParser):
""" """
raise Exception(msg) raise Exception(msg)
def print_usage(self, file=None): def print_usage(self, _file=None):
console = component.get("ConsoleUI") console = component.get("ConsoleUI")
if self.usage: if self.usage:
for line in self.get_usage().splitlines(): for line in self.get_usage().splitlines():
console.write(line) console.write(line)
def print_help(self, file=None): def print_help(self, _file=None):
console = component.get("ConsoleUI") console = component.get("ConsoleUI")
console.set_batch_write(True) console.set_batch_write(True)
for line in self.format_help().splitlines(): for line in self.format_help().splitlines():
@ -239,14 +239,17 @@ class BaseCommand(object):
result = shlex.split(text) result = shlex.split(text)
for i, s in enumerate(result): for i, s in enumerate(result):
result[i] = s.replace(r"\ ", " ") result[i] = s.replace(r"\ ", " ")
result = filter(lambda s: s != "", result) result = [s for s in result if s != ""]
return result return result
def create_parser(self): def create_parser(self):
return OptionParser(prog=self.name, usage=self.usage, epilog=self.epilog, option_list=self.option_list) return OptionParser(prog=self.name, usage=self.usage, epilog=self.epilog, option_list=self.option_list)
def load_commands(command_dir, exclude=[]): def load_commands(command_dir, exclude=None):
if not exclude:
exclude = []
def get_command(name): def get_command(name):
return getattr(__import__("deluge.ui.console.commands.%s" % name, {}, {}, ["Command"]), "Command")() return getattr(__import__("deluge.ui.console.commands.%s" % name, {}, {}, ["Command"]), "Command")()
@ -277,7 +280,7 @@ class ConsoleUI(component.Component):
try: try:
locale.setlocale(locale.LC_ALL, "") locale.setlocale(locale.LC_ALL, "")
self.encoding = locale.getpreferredencoding() self.encoding = locale.getpreferredencoding()
except: except Exception:
self.encoding = sys.getdefaultencoding() self.encoding = sys.getdefaultencoding()
log.debug("Using encoding: %s", self.encoding) log.debug("Using encoding: %s", self.encoding)
@ -404,9 +407,9 @@ Please use commands from the command line, eg:\n
if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy): if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy):
return self.screen.tab_complete_torrent(line) return self.screen.tab_complete_torrent(line)
def tab_complete_path(self, line, type="file", ext="", sort="name", dirs_first=True): def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=True):
if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy): if self.interactive and isinstance(self.screen, deluge.ui.console.modes.legacy.Legacy):
return self.screen.tab_complete_path(line, type=type, ext=ext, sort=sort, dirs_first=dirs_first) return self.screen.tab_complete_path(line, path_type=path_type, ext=ext, sort=sort, dirs_first=dirs_first)
def set_mode(self, mode): def set_mode(self, mode):
reactor.removeReader(self.screen) reactor.removeReader(self.screen)

View file

@ -11,7 +11,7 @@ import base64
import logging import logging
import os import os
import deluge.common as common import deluge.common
import deluge.component as component import deluge.component as component
from deluge.ui.client import client from deluge.ui.client import client
from deluge.ui.console.modes import format_utils from deluge.ui.console.modes import format_utils
@ -134,7 +134,7 @@ class AddTorrents(BaseMode, component.Component):
full_path = os.path.join(path, dirname) full_path = os.path.join(path, dirname)
try: try:
size = len(os.listdir(full_path)) size = len(os.listdir(full_path))
except: except OSError:
size = -1 size = -1
time = os.stat(full_path).st_mtime time = os.stat(full_path).st_mtime
@ -185,7 +185,7 @@ class AddTorrents(BaseMode, component.Component):
self.formatted_rows = [] self.formatted_rows = []
for row in self.raw_rows: for row in self.raw_rows:
filename = row[0] filename = deluge.common.decode_string(row[0])
size = row[1] size = row[1]
time = row[2] time = row[2]
@ -195,21 +195,12 @@ class AddTorrents(BaseMode, component.Component):
else: else:
size_str = " unknown" size_str = " unknown"
try: cols = [filename, size_str, deluge.common.fdate(time)]
filename = filename.decode("utf8")
except:
pass
cols = [filename, size_str, common.fdate(time)]
widths = [self.cols - 35, 12, 23] widths = [self.cols - 35, 12, 23]
self.formatted_rows.append(format_utils.format_row(cols, widths)) self.formatted_rows.append(format_utils.format_row(cols, widths))
else: else:
# Size of .torrent file itself couldn't matter less so we'll leave it out # Size of .torrent file itself couldn't matter less so we'll leave it out
try: cols = [filename, deluge.common.fdate(time)]
filename = filename.decode("utf8")
except:
pass
cols = [filename, common.fdate(time)]
widths = [self.cols - 23, 23] widths = [self.cols - 23, 23]
self.formatted_rows.append(format_utils.format_row(cols, widths)) self.formatted_rows.append(format_utils.format_row(cols, widths))
@ -262,8 +253,8 @@ class AddTorrents(BaseMode, component.Component):
string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr
self.add_string(self.rows - 1, string) self.add_string(self.rows - 1, string)
except: except Exception as ex:
pass log.debug("Exception caught: %s", ex)
off = 1 off = 1
@ -400,7 +391,7 @@ class AddTorrents(BaseMode, component.Component):
ress = {"succ": 0, "fail": 0, "total": len(self.marked), "fmsg": []} ress = {"succ": 0, "fail": 0, "total": len(self.marked), "fmsg": []}
def fail_cb(msg, t_file, ress): def fail_cb(msg, t_file, ress):
log.debug("failed to add torrent: %s: %s" % (t_file, msg)) log.debug("failed to add torrent: %s: %s", t_file, msg)
ress["fail"] += 1 ress["fail"] += 1
ress["fmsg"].append("{!input!} * %s: {!error!}%s" % (t_file, msg)) ress["fmsg"].append("{!input!} * %s: {!error!}%s" % (t_file, msg))
if (ress["succ"] + ress["fail"]) >= ress["total"]: if (ress["succ"] + ress["fail"]) >= ress["total"]:
@ -408,7 +399,7 @@ class AddTorrents(BaseMode, component.Component):
def success_cb(tid, t_file, ress): def success_cb(tid, t_file, ress):
if tid: if tid:
log.debug("added torrent: %s (%s)" % (t_file, tid)) log.debug("added torrent: %s (%s)", t_file, tid)
ress["succ"] += 1 ress["succ"] += 1
if (ress["succ"] + ress["fail"]) >= ress["total"]: if (ress["succ"] + ress["fail"]) >= ress["total"]:
self.alltorrentmode._report_add_status(ress["succ"], ress["fail"], ress["fmsg"]) self.alltorrentmode._report_add_status(ress["succ"], ress["fail"], ress["fmsg"])

View file

@ -102,18 +102,18 @@ files in the torrent and the ability to set file priorities.
input something input something
""" """
STATE_FILTER = {
class FILTER: "all": 0,
ALL = 0 "active": 1,
ACTIVE = 1 "downloading": 2,
DOWNLOADING = 2 "seeding": 3,
SEEDING = 3 "paused": 4,
PAUSED = 4 "checking": 5,
CHECKING = 5 "error": 6,
ERROR = 6 "queued": 7,
QUEUED = 7 "allocating": 8,
ALLOCATING = 8 "moving": 9
MOVING = 9 }
DEFAULT_PREFS = { DEFAULT_PREFS = {
"show_queue": True, "show_queue": True,
@ -386,14 +386,14 @@ class AllTorrents(BaseMode, component.Component):
def __update_columns(self): def __update_columns(self):
self.column_widths = [self.config["%s_width" % c] for c in self.__cols_to_show] self.column_widths = [self.config["%s_width" % c] for c in self.__cols_to_show]
req = sum(filter(lambda x: x >= 0, self.column_widths)) requested_width = sum([width for width in self.column_widths if width >= 0])
if req > self.cols: # can't satisfy requests, just spread out evenly if requested_width > self.cols: # can't satisfy requests, just spread out evenly
cw = int(self.cols / len(self.__columns)) cw = int(self.cols / len(self.__columns))
for i in range(0, len(self.column_widths)): for i in range(0, len(self.column_widths)):
self.column_widths[i] = cw self.column_widths[i] = cw
else: else:
rem = self.cols - req rem = self.cols - requested_width
var_cols = len(filter(lambda x: x < 0, self.column_widths)) var_cols = len([width for width in self.column_widths if width < 0])
if var_cols > 0: if var_cols > 0:
vw = int(rem / var_cols) vw = int(rem / var_cols)
for i in range(0, len(self.column_widths)): for i in range(0, len(self.column_widths)):
@ -404,7 +404,7 @@ class AllTorrents(BaseMode, component.Component):
try: try:
primary_sort_col_name = prefs_to_names[self.config["sort_primary"]] primary_sort_col_name = prefs_to_names[self.config["sort_primary"]]
except: except KeyError:
primary_sort_col_name = "" primary_sort_col_name = ""
for i, column in enumerate(self.__columns): for i, column in enumerate(self.__columns):
@ -652,34 +652,34 @@ class AllTorrents(BaseMode, component.Component):
component.stop(["AllTorrents"]).addCallback(dolegacy) component.stop(["AllTorrents"]).addCallback(dolegacy)
def _torrent_filter(self, idx, data): def _torrent_filter(self, idx, data):
if data == FILTER.ALL: if data == STATE_FILTER["all"]:
self.__status_dict = {} self.__status_dict = {}
self._curr_filter = None self._curr_filter = None
elif data == FILTER.ACTIVE: elif data == STATE_FILTER["active"]:
self.__status_dict = {"state": "Active"} self.__status_dict = {"state": "Active"}
self._curr_filter = "Active" self._curr_filter = "Active"
elif data == FILTER.DOWNLOADING: elif data == STATE_FILTER["downloading"]:
self.__status_dict = {"state": "Downloading"} self.__status_dict = {"state": "Downloading"}
self._curr_filter = "Downloading" self._curr_filter = "Downloading"
elif data == FILTER.SEEDING: elif data == STATE_FILTER["seeding"]:
self.__status_dict = {"state": "Seeding"} self.__status_dict = {"state": "Seeding"}
self._curr_filter = "Seeding" self._curr_filter = "Seeding"
elif data == FILTER.PAUSED: elif data == STATE_FILTER["paused"]:
self.__status_dict = {"state": "Paused"} self.__status_dict = {"state": "Paused"}
self._curr_filter = "Paused" self._curr_filter = "Paused"
elif data == FILTER.CHECKING: elif data == STATE_FILTER["checking"]:
self.__status_dict = {"state": "Checking"} self.__status_dict = {"state": "Checking"}
self._curr_filter = "Checking" self._curr_filter = "Checking"
elif data == FILTER.ERROR: elif data == STATE_FILTER["error"]:
self.__status_dict = {"state": "Error"} self.__status_dict = {"state": "Error"}
self._curr_filter = "Error" self._curr_filter = "Error"
elif data == FILTER.QUEUED: elif data == STATE_FILTER["queued"]:
self.__status_dict = {"state": "Queued"} self.__status_dict = {"state": "Queued"}
self._curr_filter = "Queued" self._curr_filter = "Queued"
elif data == FILTER.ALLOCATING: elif data == STATE_FILTER["allocating"]:
self.__status_dict = {"state": "Allocating"} self.__status_dict = {"state": "Allocating"}
self._curr_filter = "Allocating" self._curr_filter = "Allocating"
elif data == FILTER.MOVING: elif data == STATE_FILTER["moving"]:
self.__status_dict = {"state": "Moving"} self.__status_dict = {"state": "Moving"}
self._curr_filter = "Moving" self._curr_filter = "Moving"
@ -688,16 +688,16 @@ class AllTorrents(BaseMode, component.Component):
def _show_torrent_filter_popup(self): def _show_torrent_filter_popup(self):
self.popup = SelectablePopup(self, "Filter Torrents", self._torrent_filter) self.popup = SelectablePopup(self, "Filter Torrents", self._torrent_filter)
self.popup.add_line("_All", data=FILTER.ALL) self.popup.add_line("_All", data=STATE_FILTER["all"])
self.popup.add_line("Ac_tive", data=FILTER.ACTIVE) self.popup.add_line("Ac_tive", data=STATE_FILTER["active"])
self.popup.add_line("_Downloading", data=FILTER.DOWNLOADING, foreground="green") self.popup.add_line("_Downloading", data=STATE_FILTER["downloading"], foreground="green")
self.popup.add_line("_Seeding", data=FILTER.SEEDING, foreground="cyan") self.popup.add_line("_Seeding", data=STATE_FILTER["seeding"], foreground="cyan")
self.popup.add_line("_Paused", data=FILTER.PAUSED) self.popup.add_line("_Paused", data=STATE_FILTER["paused"])
self.popup.add_line("_Error", data=FILTER.ERROR, foreground="red") self.popup.add_line("_Error", data=STATE_FILTER["error"], foreground="red")
self.popup.add_line("_Checking", data=FILTER.CHECKING, foreground="blue") self.popup.add_line("_Checking", data=STATE_FILTER["checking"], foreground="blue")
self.popup.add_line("Q_ueued", data=FILTER.QUEUED, foreground="yellow") self.popup.add_line("Q_ueued", data=STATE_FILTER["queued"], foreground="yellow")
self.popup.add_line("A_llocating", data=FILTER.ALLOCATING, foreground="yellow") self.popup.add_line("A_llocating", data=STATE_FILTER["allocating"], foreground="yellow")
self.popup.add_line("_Moving", data=FILTER.MOVING, foreground="green") self.popup.add_line("_Moving", data=STATE_FILTER["moving"], foreground="green")
def _report_add_status(self, succ_cnt, fail_cnt, fail_msgs): def _report_add_status(self, succ_cnt, fail_cnt, fail_msgs):
if fail_cnt == 0: if fail_cnt == 0:
@ -712,13 +712,13 @@ class AllTorrents(BaseMode, component.Component):
def do_add_from_url(result): def do_add_from_url(result):
def fail_cb(msg, url): def fail_cb(msg, url):
log.debug("failed to add torrent: %s: %s" % (url, msg)) log.debug("failed to add torrent: %s: %s", url, msg)
error_msg = "{!input!} * %s: {!error!}%s" % (url, msg) error_msg = "{!input!} * %s: {!error!}%s" % (url, msg)
self._report_add_status(0, 1, [error_msg]) self._report_add_status(0, 1, [error_msg])
def success_cb(tid, url): def success_cb(tid, url):
if tid: if tid:
log.debug("added torrent: %s (%s)" % (url, tid)) log.debug("added torrent: %s (%s)", url, tid)
self._report_add_status(1, 0, []) self._report_add_status(1, 0, [])
else: else:
fail_cb("Already in session (probably)", url) fail_cb("Already in session (probably)", url)
@ -859,7 +859,7 @@ class AllTorrents(BaseMode, component.Component):
string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr
self.add_string(self.rows - 1, string) self.add_string(self.rows - 1, string)
except: except Exception:
pass pass
# add all the torrents # add all the torrents
@ -958,8 +958,8 @@ class AllTorrents(BaseMode, component.Component):
try: try:
self.add_string(currow, "%s%s" % (colorstr, row[0]), trim=False) self.add_string(currow, "%s%s" % (colorstr, row[0]), trim=False)
except: except Exception:
# Yeah, this should be fixed in some better way # XXX: Yeah, this should be fixed in some better way
pass pass
tidx += 1 tidx += 1
currow += 1 currow += 1
@ -1260,7 +1260,7 @@ class AllTorrents(BaseMode, component.Component):
i = len(self.__cols_to_show) i = len(self.__cols_to_show)
try: try:
i = self.__cols_to_show.index(self.config["sort_primary"]) - 1 i = self.__cols_to_show.index(self.config["sort_primary"]) - 1
except: except KeyError:
pass pass
i = max(0, i) i = max(0, i)
@ -1276,7 +1276,7 @@ class AllTorrents(BaseMode, component.Component):
i = 0 i = 0
try: try:
i = self.__cols_to_show.index(self.config["sort_primary"]) + 1 i = self.__cols_to_show.index(self.config["sort_primary"]) + 1
except: except KeyError:
pass pass
i = min(len(self.__cols_to_show) - 1, i) i = min(len(self.__cols_to_show) - 1, i)

View file

@ -26,7 +26,7 @@ try:
from fcntl import ioctl from fcntl import ioctl
import termios import termios
import struct import struct
except: except ImportError:
pass pass
@ -155,7 +155,7 @@ class BaseMode(CursesStdIO):
# This is the last string so lets append some " " to it # This is the last string so lets append some " " to it
s += " " * (self.cols - (col + len(s)) - 1) s += " " * (self.cols - (col + len(s)) - 1)
if trim: if trim:
y, x = screen.getmaxyx() dummy, x = screen.getmaxyx()
if (col + len(s)) > x: if (col + len(s)) > x:
s = "%s..." % s[0:x - 4 - col] s = "%s..." % s[0:x - 4 - col]
screen.addstr(row, col, s, color) screen.addstr(row, col, s, color)

View file

@ -61,13 +61,13 @@ def get_column_value(name, state):
if col[1]: if col[1]:
try: try:
args = [state[key] for key in col[0]] args = [state[key] for key in col[0]]
except: except KeyError:
return "Please Wait" return "Please Wait"
return col[1](*args) return col[1](*args)
else: else:
try: try:
return state[col[0][0]] return state[col[0][0]]
except: except KeyError:
return "Please Wait" return "Please Wait"

View file

@ -45,8 +45,8 @@ class EventView(BaseMode):
string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr
self.add_string(self.rows - 1, string) self.add_string(self.rows - 1, string)
except: except Exception as ex:
pass log.debug("Exception caught: %s", ex)
if events: if events:
for i, event in enumerate(events): for i, event in enumerate(events):

View file

@ -121,7 +121,7 @@ def format_column(col, lim):
def format_row(row, column_widths): def format_row(row, column_widths):
return "".join([format_column(row[i], column_widths[i]) for i in range(0, len(row))]) return "".join([format_column(row[i], column_widths[i]) for i in range(0, len(row))])
_strip_re = re.compile("\{!.*?!\}") _strip_re = re.compile("\\{!.*?!\\}")
def remove_formatting(string): def remove_formatting(string):

View file

@ -201,7 +201,7 @@ class IntSpinInput(InputField):
self.valstr = self.default_str self.valstr = self.default_str
try: try:
int(self.value) int(self.value)
except: except ValueError:
self.real_value = False self.real_value = False
else: else:
self.value = int(self.valstr) self.value = int(self.valstr)
@ -214,11 +214,11 @@ class IntSpinInput(InputField):
self.real_value = True self.real_value = True
try: try:
self.value = int(self.valstr) self.value = int(self.valstr)
except: except ValueError:
self.value = self.default_value self.value = self.default_value
try: try:
int(self.value) int(self.value)
except: except ValueError:
self.real_value = False self.real_value = False
if not self.valstr: if not self.valstr:
self.parent.add_string(row, "%s {!input!}[ ]" % self.message, screen, col, False, True) self.parent.add_string(row, "%s {!input!}[ ]" % self.message, screen, col, False, True)
@ -381,7 +381,7 @@ class FloatSpinInput(InputField):
self.valstr = self.default_str self.valstr = self.default_str
try: try:
float(self.value) float(self.value)
except: except ValueError:
self.real_value = False self.real_value = False
else: else:
self.set_value(self.valstr) self.set_value(self.valstr)
@ -394,11 +394,11 @@ class FloatSpinInput(InputField):
self.real_value = True self.real_value = True
try: try:
self.value = round(float(self.valstr), self.precision) self.value = round(float(self.valstr), self.precision)
except: except ValueError:
self.value = self.default_value self.value = self.default_value
try: try:
float(self.value) float(self.value)
except: except ValueError:
self.real_value = False self.real_value = False
if not self.valstr: if not self.valstr:

View file

@ -142,14 +142,14 @@ class Legacy(BaseMode, component.Component):
try: try:
lines1 = open(self.history_file[0], "r").read().splitlines() lines1 = open(self.history_file[0], "r").read().splitlines()
self._hf_lines[0] = len(lines1) self._hf_lines[0] = len(lines1)
except: except IOError:
lines1 = [] lines1 = []
self._hf_lines[0] = 0 self._hf_lines[0] = 0
try: try:
lines2 = open(self.history_file[1], "r").read().splitlines() lines2 = open(self.history_file[1], "r").read().splitlines()
self._hf_lines[1] = len(lines2) self._hf_lines[1] = len(lines2)
except: except IOError:
lines2 = [] lines2 = []
self._hf_lines[1] = 0 self._hf_lines[1] = 0
@ -170,13 +170,13 @@ class Legacy(BaseMode, component.Component):
# self.lines[i] = line # self.lines[i] = line
line = format_utils.remove_formatting(line) line = format_utils.remove_formatting(line)
if line.startswith(">>> "): if line.startswith(">>> "):
input = line[4:] console_input = line[4:]
if self.console_config["ignore_duplicate_lines"]: if self.console_config["ignore_duplicate_lines"]:
if len(self.input_history) > 0: if len(self.input_history) > 0:
if self.input_history[-1] != input: if self.input_history[-1] != console_input:
self.input_history.append(input) self.input_history.append(console_input)
else: else:
self.input_history.append(input) self.input_history.append(console_input)
self.input_history_index = len(self.input_history) self.input_history_index = len(self.input_history)
@ -776,10 +776,10 @@ class Legacy(BaseMode, component.Component):
cursor = len(line) cursor = len(line)
return (line, cursor) return (line, cursor)
def tab_complete_path(self, line, type="file", ext="", sort="name", dirs_first=1): def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=1):
self.console = component.get("ConsoleUI") self.console = component.get("ConsoleUI")
line = line.replace("\ ", " ") line = line.replace("\\ ", " ")
line = os.path.abspath(os.path.expanduser(line)) line = os.path.abspath(os.path.expanduser(line))
ret = [] ret = []
if os.path.exists(line): if os.path.exists(line):
@ -832,12 +832,12 @@ class Legacy(BaseMode, component.Component):
self.console.write("{!error!}Permission denied: {!info!}%s" % line) self.console.write("{!error!}Permission denied: {!info!}%s" % line)
if sort == "date": if sort == "date":
ret = sorted(ret, key=lambda p: os.stat(p).st_mtime, reverse=True) ret = sorted(ret, key=os.path.getmtime, reverse=True)
if dirs_first == 1: if dirs_first == 1:
ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=True) ret = sorted(ret, key=os.path.isdir, reverse=True)
elif dirs_first == -1: elif dirs_first == -1:
ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=False) ret = sorted(ret, key=os.path.isdir, reverse=False)
# Highlight directory names # Highlight directory names
for i, filename in enumerate(ret): for i, filename in enumerate(ret):

View file

@ -104,12 +104,12 @@ def torrent_action(idx, data, mode, ids):
mode.marked = range(1, selected_num + 1) mode.marked = range(1, selected_num + 1)
elif qact == ACTION.QUEUE_UP: elif qact == ACTION.QUEUE_UP:
mode.cursel = max(1, mode.cursel - 1) mode.cursel = max(1, mode.cursel - 1)
mode.marked = map(lambda v: v - 1, mode.marked) mode.marked = [marked - 1 for marked in mode.marked]
mode.marked = filter(lambda v: v > 0, mode.marked) mode.marked = [marked for marked in mode.marked if marked > 0]
elif qact == ACTION.QUEUE_DOWN: elif qact == ACTION.QUEUE_DOWN:
mode.cursel = min(queue_length, mode.cursel + 1) mode.cursel = min(queue_length, mode.cursel + 1)
mode.marked = map(lambda v: v + 1, mode.marked) mode.marked = [marked + 1 for marked in mode.marked]
mode.marked = filter(lambda v: v <= queue_length, mode.marked) mode.marked = [marked for marked in mode.marked if marked <= queue_length]
elif qact == ACTION.QUEUE_BOTTOM: elif qact == ACTION.QUEUE_BOTTOM:
if mode.marked: if mode.marked:
mode.cursel = queue_length - selected_num + 1 + sorted(mode.marked).index(mode.cursel) mode.cursel = queue_length - selected_num + 1 + sorted(mode.marked).index(mode.cursel)
@ -168,7 +168,7 @@ def torrent_action(idx, data, mode, ids):
callbacks.append(d.addCallback(got_status)) callbacks.append(d.addCallback(got_status))
def finish_up(status): def finish_up(status):
status = map(lambda x: x[1], status) status = [t_status[1] for t_status in status]
if len(ids) == 1: if len(ids) == 1:
rem_msg = "{!info!}Removing the following torrent:{!input!}" rem_msg = "{!info!}Removing the following torrent:{!input!}"
@ -290,7 +290,7 @@ def torrent_action(idx, data, mode, ids):
callbacks = [] callbacks = []
field_list = map(lambda t: t[0], torrent_options) field_list = [torrent_option[0] for torrent_option in torrent_options]
for tid in torrents: for tid in torrents:
deferred = component.get("SessionProxy").get_torrent_status(tid, field_list) deferred = component.get("SessionProxy").get_torrent_status(tid, field_list)

View file

@ -224,14 +224,14 @@ class TorrentDetail(BaseMode, component.Component):
def __update_columns(self): def __update_columns(self):
self.column_widths = [-1, 15, 15, 20] self.column_widths = [-1, 15, 15, 20]
req = sum(filter(lambda x: x >= 0, self.column_widths)) req = sum([col_width for col_width in self.column_widths if col_width >= 0])
if req > self.cols: # can't satisfy requests, just spread out evenly if req > self.cols: # can't satisfy requests, just spread out evenly
cw = int(self.cols / len(self.column_names)) cw = int(self.cols / len(self.column_names))
for i in range(0, len(self.column_widths)): for i in range(0, len(self.column_widths)):
self.column_widths[i] = cw self.column_widths[i] = cw
else: else:
rem = self.cols - req rem = self.cols - req
var_cols = len(filter(lambda x: x < 0, self.column_widths)) var_cols = len([col_width for col_width in self.column_widths if col_width < 0])
vw = int(rem / var_cols) vw = int(rem / var_cols)
for i in range(0, len(self.column_widths)): for i in range(0, len(self.column_widths)):
if self.column_widths[i] < 0: if self.column_widths[i] < 0:
@ -267,9 +267,7 @@ class TorrentDetail(BaseMode, component.Component):
for i in old_folder.strip("/").split("/"): for i in old_folder.strip("/").split("/"):
if not fl: if not fl:
fe = fl = self.file_list fe = fl = self.file_list
s = [files for files in fl if files[0].strip("/") == i][0]
s = filter(lambda x: x[0].strip("/") == i, fl)[0]
fe = s fe = s
fl = s[3] fl = s[3]
fe[0] = new_folder.strip("/").rpartition("/")[-1] fe[0] = new_folder.strip("/").rpartition("/")[-1]
@ -519,8 +517,8 @@ class TorrentDetail(BaseMode, component.Component):
string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr string += " " * (self.cols - len(rf(string)) - len(rf(hstr))) + hstr
self.add_string(self.rows - 1, string) self.add_string(self.rows - 1, string)
except: except Exception as ex:
pass log.debug("Exception caught: %s", ex)
off = 1 off = 1
if self.torrent_state: if self.torrent_state:

View file

@ -87,7 +87,6 @@ COUNTRIES = {
'GM': _('Gambia'), 'GM': _('Gambia'),
'GE': _('Georgia'), 'GE': _('Georgia'),
'DE': _('Germany'), 'DE': _('Germany'),
'GB': _('United Kingdom'),
'GH': _('Ghana'), 'GH': _('Ghana'),
'GI': _('Gibraltar'), 'GI': _('Gibraltar'),
'GR': _('Greece'), 'GR': _('Greece'),

View file

@ -283,22 +283,22 @@ class AddTorrentDialog(component.Component):
def prepare_file_store(self, files): def prepare_file_store(self, files):
with listview_replace_treestore(self.listview_files): with listview_replace_treestore(self.listview_files):
split_files = {} split_files = {}
for i, file in enumerate(files): for i, _file in enumerate(files):
self.prepare_file( self.prepare_file(
file, file["path"], i, file["download"], split_files _file, _file["path"], i, _file["download"], split_files
) )
self.add_files(None, split_files) self.add_files(None, split_files)
self.listview_files.expand_row("0", False) self.listview_files.expand_row("0", False)
def prepare_file(self, file, file_name, file_num, download, files_storage): def prepare_file(self, _file, file_name, file_num, download, files_storage):
first_slash_index = file_name.find(os.path.sep) first_slash_index = file_name.find(os.path.sep)
if first_slash_index == -1: if first_slash_index == -1:
files_storage[file_name] = (file_num, file, download) files_storage[file_name] = (file_num, _file, download)
else: else:
file_name_chunk = file_name[:first_slash_index + 1] file_name_chunk = file_name[:first_slash_index + 1]
if file_name_chunk not in files_storage: if file_name_chunk not in files_storage:
files_storage[file_name_chunk] = {} files_storage[file_name_chunk] = {}
self.prepare_file(file, file_name[first_slash_index + 1:], self.prepare_file(_file, file_name[first_slash_index + 1:],
file_num, download, files_storage[file_name_chunk]) file_num, download, files_storage[file_name_chunk])
def add_files(self, parent_iter, split_files): def add_files(self, parent_iter, split_files):
@ -436,13 +436,13 @@ class AddTorrentDialog(component.Component):
for i, file_dict in enumerate(self.files[torrent_id]): for i, file_dict in enumerate(self.files[torrent_id]):
file_dict["download"] = files_priorities[i] file_dict["download"] = files_priorities[i]
def build_priorities(self, iter, priorities): def build_priorities(self, _iter, priorities):
while iter is not None: while _iter is not None:
if self.files_treestore.iter_has_child(iter): if self.files_treestore.iter_has_child(_iter):
self.build_priorities(self.files_treestore.iter_children(iter), priorities) self.build_priorities(self.files_treestore.iter_children(_iter), priorities)
elif not self.files_treestore.get_value(iter, 1).endswith(os.path.sep): elif not self.files_treestore.get_value(_iter, 1).endswith(os.path.sep):
priorities[self.files_treestore.get_value(iter, 3)] = self.files_treestore.get_value(iter, 0) priorities[self.files_treestore.get_value(_iter, 3)] = self.files_treestore.get_value(_iter, 0)
iter = self.files_treestore.iter_next(iter) _iter = self.files_treestore.iter_next(_iter)
return priorities return priorities
def set_default_options(self): def set_default_options(self):
@ -496,35 +496,35 @@ class AddTorrentDialog(component.Component):
self.toggle_iter(row) self.toggle_iter(row)
self.update_treeview_toggles(self.files_treestore.get_iter_first()) self.update_treeview_toggles(self.files_treestore.get_iter_first())
def toggle_iter(self, iter, toggle_to=None): def toggle_iter(self, _iter, toggle_to=None):
if toggle_to is None: if toggle_to is None:
toggle_to = not self.files_treestore.get_value(iter, 0) toggle_to = not self.files_treestore.get_value(_iter, 0)
self.files_treestore.set_value(iter, 0, toggle_to) self.files_treestore.set_value(_iter, 0, toggle_to)
if self.files_treestore.iter_has_child(iter): if self.files_treestore.iter_has_child(_iter):
child = self.files_treestore.iter_children(iter) child = self.files_treestore.iter_children(_iter)
while child is not None: while child is not None:
self.toggle_iter(child, toggle_to) self.toggle_iter(child, toggle_to)
child = self.files_treestore.iter_next(child) child = self.files_treestore.iter_next(child)
def update_treeview_toggles(self, iter): def update_treeview_toggles(self, _iter):
toggle_inconsistent = -1 toggle_inconsistent = -1
this_level_toggle = None this_level_toggle = None
while iter is not None: while _iter is not None:
if self.files_treestore.iter_has_child(iter): if self.files_treestore.iter_has_child(_iter):
toggle = self.update_treeview_toggles(self.files_treestore.iter_children(iter)) toggle = self.update_treeview_toggles(self.files_treestore.iter_children(_iter))
if toggle == toggle_inconsistent: if toggle == toggle_inconsistent:
self.files_treestore.set_value(iter, 4, True) self.files_treestore.set_value(_iter, 4, True)
else: else:
self.files_treestore.set_value(iter, 0, toggle) self.files_treestore.set_value(_iter, 0, toggle)
# set inconsistent to false # set inconsistent to false
self.files_treestore.set_value(iter, 4, False) self.files_treestore.set_value(_iter, 4, False)
else: else:
toggle = self.files_treestore.get_value(iter, 0) toggle = self.files_treestore.get_value(_iter, 0)
if this_level_toggle is None: if this_level_toggle is None:
this_level_toggle = toggle this_level_toggle = toggle
elif this_level_toggle != toggle: elif this_level_toggle != toggle:
this_level_toggle = toggle_inconsistent this_level_toggle = toggle_inconsistent
iter = self.files_treestore.iter_next(iter) _iter = self.files_treestore.iter_next(_iter)
return this_level_toggle return this_level_toggle
def _on_button_file_clicked(self, widget): def _on_button_file_clicked(self, widget):

View file

@ -222,8 +222,6 @@ class ConnectionManager(component.Component):
# Host isn't in the list, so lets add it # Host isn't in the list, so lets add it
row = self.liststore.append() row = self.liststore.append()
import time
import hashlib
self.liststore[row][HOSTLIST_COL_ID] = hashlib.sha1(str(time.time())).hexdigest() self.liststore[row][HOSTLIST_COL_ID] = hashlib.sha1(str(time.time())).hexdigest()
self.liststore[row][HOSTLIST_COL_HOST] = host self.liststore[row][HOSTLIST_COL_HOST] = host
self.liststore[row][HOSTLIST_COL_PORT] = port self.liststore[row][HOSTLIST_COL_PORT] = port
@ -330,7 +328,7 @@ class ConnectionManager(component.Component):
port, port,
"localclient" if not user and host in ("127.0.0.1", "localhost") else user "localclient" if not user and host in ("127.0.0.1", "localhost") else user
) == client.connection_info(): ) == client.connection_info():
def on_info(info): def on_info(info, row):
if not self.running: if not self.running:
return return
log.debug("Client connected, query info: %s", info) log.debug("Client connected, query info: %s", info)
@ -339,7 +337,7 @@ class ConnectionManager(component.Component):
row[HOSTLIST_COL_STATUS] = "Connected" row[HOSTLIST_COL_STATUS] = "Connected"
log.debug("Query daemon's info") log.debug("Query daemon's info")
client.daemon.info().addCallback(on_info) client.daemon.info().addCallback(on_info, row)
continue continue
# Create a new Client instance # Create a new Client instance

View file

@ -25,6 +25,10 @@ log = logging.getLogger(__name__)
class CreateTorrentDialog: class CreateTorrentDialog:
def __init__(self):
pass
def show(self): def show(self):
self.builder = gtk.Builder() self.builder = gtk.Builder()

View file

@ -119,10 +119,10 @@ class EditTrackersDialog:
if response == 1: if response == 1:
self.trackers = [] self.trackers = []
def each(model, path, iter, data): def each(model, path, _iter, data):
tracker = {} tracker = {}
tracker["tier"] = model.get_value(iter, 0) tracker["tier"] = model.get_value(_iter, 0)
tracker["url"] = model.get_value(iter, 1) tracker["url"] = model.get_value(_iter, 1)
self.trackers.append(tracker) self.trackers.append(tracker)
self.liststore.foreach(each, None) self.liststore.foreach(each, None)
if self.old_trackers != self.trackers: if self.old_trackers != self.trackers:

View file

@ -346,15 +346,15 @@ class FilesTab(Tab):
def prepare_file_store(self, files): def prepare_file_store(self, files):
split_files = {} split_files = {}
i = 0 i = 0
for file in files: for _file in files:
self.prepare_file(file, file["path"], i, split_files) self.prepare_file(_file, _file["path"], i, split_files)
i += 1 i += 1
self.add_files(None, split_files) self.add_files(None, split_files)
def prepare_file(self, file, file_name, file_num, files_storage): def prepare_file(self, _file, file_name, file_num, files_storage):
first_slash_index = file_name.find("/") first_slash_index = file_name.find("/")
if first_slash_index == -1: if first_slash_index == -1:
files_storage[file_name] = (file_num, file) files_storage[file_name] = (file_num, _file)
else: else:
file_name_chunk = file_name[:first_slash_index + 1] file_name_chunk = file_name[:first_slash_index + 1]
if file_name_chunk not in files_storage: if file_name_chunk not in files_storage:
@ -419,24 +419,24 @@ class FilesTab(Tab):
return return
def get_completed_bytes(row): def get_completed_bytes(row):
bytes = 0 completed_bytes = 0
parent = self.treestore.iter_parent(row) parent = self.treestore.iter_parent(row)
while row: while row:
if self.treestore.iter_children(row): if self.treestore.iter_children(row):
bytes += get_completed_bytes(self.treestore.iter_children(row)) completed_bytes += get_completed_bytes(self.treestore.iter_children(row))
else: else:
bytes += self.treestore[row][1] * (float(self.treestore[row][3]) / 100.0) completed_bytes += self.treestore[row][1] * (float(self.treestore[row][3]) / 100.0)
row = self.treestore.iter_next(row) row = self.treestore.iter_next(row)
try: try:
value = (float(bytes) / float(self.treestore[parent][1])) * 100 value = (float(completed_bytes) / float(self.treestore[parent][1])) * 100
except ZeroDivisionError: except ZeroDivisionError:
# Catch the unusal error found when moving folders around # Catch the unusal error found when moving folders around
value = 0 value = 0
self.treestore[parent][3] = value self.treestore[parent][3] = value
self.treestore[parent][2] = "%.2f%%" % value self.treestore[parent][2] = "%.2f%%" % value
return bytes return completed_bytes
get_completed_bytes(self.treestore.iter_children(root)) get_completed_bytes(self.treestore.iter_children(root))
@ -536,12 +536,12 @@ class FilesTab(Tab):
"""Sets the file priorities in the core. It will change the selected with the 'priority'""" """Sets the file priorities in the core. It will change the selected with the 'priority'"""
file_priorities = [] file_priorities = []
def set_file_priority(model, path, iter, data): def set_file_priority(model, path, _iter, data):
index = model.get_value(iter, 5) index = model.get_value(_iter, 5)
if index in selected and index != -1: if index in selected and index != -1:
file_priorities.append((index, priority)) file_priorities.append((index, priority))
elif index != -1: elif index != -1:
file_priorities.append((index, model.get_value(iter, 4))) file_priorities.append((index, model.get_value(_iter, 4)))
self.treestore.foreach(set_file_priority, None) self.treestore.foreach(set_file_priority, None)
file_priorities.sort() file_priorities.sort()
@ -768,13 +768,13 @@ class FilesTab(Tab):
old_split = old_folder.split("/") old_split = old_folder.split("/")
try: try:
old_split.remove("") old_split.remove("")
except: except ValueError:
pass pass
new_split = new_folder.split("/") new_split = new_folder.split("/")
try: try:
new_split.remove("") new_split.remove("")
except: except ValueError:
pass pass
old_folder_iter = self.get_iter_at_path(old_folder) old_folder_iter = self.get_iter_at_path(old_folder)

View file

@ -114,7 +114,6 @@ DEFAULT_PREFS = {
"autoadd_queued": False, "autoadd_queued": False,
"choose_directory_dialog_path": deluge.common.get_default_download_dir(), "choose_directory_dialog_path": deluge.common.get_default_download_dir(),
"show_new_releases": True, "show_new_releases": True,
"signal_port": 40000,
"ntf_tray_blink": True, "ntf_tray_blink": True,
"ntf_sound": False, "ntf_sound": False,
"ntf_sound_path": deluge.common.get_default_download_dir(), "ntf_sound_path": deluge.common.get_default_download_dir(),
@ -125,7 +124,6 @@ DEFAULT_PREFS = {
"ntf_pass": "", "ntf_pass": "",
"ntf_server": "", "ntf_server": "",
"ntf_security": None, "ntf_security": None,
"signal_port": 40000,
"show_sidebar": True, "show_sidebar": True,
"show_toolbar": True, "show_toolbar": True,
"show_statusbar": True, "show_statusbar": True,

View file

@ -34,6 +34,10 @@ log = logging.getLogger(__name__)
class IPCProtocolServer(Protocol): class IPCProtocolServer(Protocol):
def __init__(self):
pass
def dataReceived(self, data): # NOQA def dataReceived(self, data): # NOQA
config = ConfigManager("gtkui.conf") config = ConfigManager("gtkui.conf")
data = rencode.loads(data, decode_utf8=True) data = rencode.loads(data, decode_utf8=True)
@ -43,6 +47,10 @@ class IPCProtocolServer(Protocol):
class IPCProtocolClient(Protocol): class IPCProtocolClient(Protocol):
def __init__(self):
pass
def connectionMade(self): # NOQA def connectionMade(self): # NOQA
self.transport.write(rencode.dumps(self.factory.args)) self.transport.write(rencode.dumps(self.factory.args))
self.transport.loseConnection() self.transport.loseConnection()

View file

@ -203,14 +203,14 @@ class ListView:
if self.unique_column_id: if self.unique_column_id:
self.last_sort_order = {} self.last_sort_order = {}
def record_position(model, path, iter, data): def record_position(model, path, _iter, data):
self.last_sort_order[model[iter][self.unique_column_id]] = path[0] self.last_sort_order[model[_iter][self.unique_column_id]] = path[0]
model.foreach(record_position, None) model.foreach(record_position, None)
def on_model_row_inserted(self, model, path, iter): def on_model_row_inserted(self, model, path, _iter):
if self.unique_column_id: if self.unique_column_id:
self.last_sort_order.setdefault( self.last_sort_order.setdefault(
model[iter][self.unique_column_id], len(model) - 1) model[_iter][self.unique_column_id], len(model) - 1)
def stabilize_sort_func(self, sort_func): def stabilize_sort_func(self, sort_func):
def stabilized(model, iter1, iter2, data): def stabilized(model, iter1, iter2, data):
@ -593,12 +593,14 @@ class ListView:
return True return True
def add_progress_column(self, header, col_types=[float, str], sortid=0, def add_progress_column(self, header, col_types=None, sortid=0,
hidden=False, position=None, status_field=None, hidden=False, position=None, status_field=None,
function=None, column_type="progress", function=None, column_type="progress",
tooltip=None, sort_func=None, default=True): tooltip=None, sort_func=None, default=True):
"""Add a progress column to the listview.""" """Add a progress column to the listview."""
if col_types is None:
col_types = [float, str]
render = gtk.CellRendererProgress() render = gtk.CellRendererProgress()
self.add_column(header, render, col_types, hidden, position, self.add_column(header, render, col_types, hidden, position,
status_field, sortid, function=function, status_field, sortid, function=function,
@ -607,11 +609,13 @@ class ListView:
return True return True
def add_texticon_column(self, header, col_types=[str, str], sortid=1, def add_texticon_column(self, header, col_types=None, sortid=1,
hidden=False, position=None, status_field=None, hidden=False, position=None, status_field=None,
column_type="texticon", function=None, column_type="texticon", function=None,
tooltip=None, default=True, default_sort=False): tooltip=None, default=True, default_sort=False):
"""Adds a texticon column to the listview.""" """Adds a texticon column to the listview."""
if col_types is None:
col_types = [str, str]
render1 = gtk.CellRendererPixbuf() render1 = gtk.CellRendererPixbuf()
render2 = gtk.CellRendererText() render2 = gtk.CellRendererText()
@ -622,9 +626,9 @@ class ListView:
return True return True
def on_keypress_search_by_name(self, model, column, key, iter): def on_keypress_search_by_name(self, model, column, key, _iter):
torrent_name_col = self.columns["Name"].column_indices[1] torrent_name_col = self.columns["Name"].column_indices[1]
return not model[iter][torrent_name_col].lower().startswith(key.lower()) return not model[_iter][torrent_name_col].lower().startswith(key.lower())
def restore_columns_order_from_state(self): def restore_columns_order_from_state(self):
if self.state is None: if self.state is None:
@ -656,8 +660,7 @@ class ListView:
continue continue
column = find_column(col_state.name) column = find_column(col_state.name)
if not column: if not column:
log.debug("Could not find column matching \"%s\" on state." % log.debug("Could not find column matching \"%s\" on state.", col_state.name)
col_state.name)
# The cases where I've found that the column could not be found # The cases where I've found that the column could not be found
# is when not using the english locale, ie, the default one, or # is when not using the english locale, ie, the default one, or
# when changing locales between runs. # when changing locales between runs.

View file

@ -146,7 +146,7 @@ class MainWindow(component.Component):
component.resume("TorrentView") component.resume("TorrentView")
component.resume("StatusBar") component.resume("StatusBar")
component.resume("TorrentDetails") component.resume("TorrentDetails")
except: except Exception:
pass pass
self.window.show() self.window.show()
@ -170,13 +170,13 @@ class MainWindow(component.Component):
else: else:
self.config["window_x_pos"] = self.window_x_pos self.config["window_x_pos"] = self.window_x_pos
self.config["window_y_pos"] = self.window_y_pos self.config["window_y_pos"] = self.window_y_pos
except: except Exception:
pass pass
try: try:
component.resume("TorrentView") component.resume("TorrentView")
component.resume("StatusBar") component.resume("StatusBar")
component.resume("TorrentDetails") component.resume("TorrentDetails")
except: except Exception:
pass pass
self.window.present() self.window.present()
@ -272,7 +272,7 @@ class MainWindow(component.Component):
try: try:
component.resume("TorrentView") component.resume("TorrentView")
component.resume("StatusBar") component.resume("StatusBar")
except: except Exception:
pass pass
self.is_minimized = False self.is_minimized = False
return False return False

View file

@ -222,13 +222,13 @@ class ValueList(object):
return True return True
return False return False
def handle_list_scroll(self, next=None, path=None, set_entry=False, swap=False, scroll_window=False): def handle_list_scroll(self, _next=None, path=None, set_entry=False, swap=False, scroll_window=False):
""" """
Handles changes to the row selection. Handles changes to the row selection.
:param next: the direction to change selection. True means down and False means up. :param _next: the direction to change selection. True means down and False means up.
None means no change. None means no change.
:type next: boolean/None :type _next: boolean/None
:param path: the current path. If None, the currently selected path is used. :param path: the current path. If None, the currently selected path is used.
:type path: tuple :type path: tuple
:param set_entry: if the new value should be set in the text entry. :param set_entry: if the new value should be set in the text entry.
@ -252,7 +252,7 @@ class ValueList(object):
# Set adjustment increment to 3 times the row height # Set adjustment increment to 3 times the row height
adjustment.set_step_increment(self.row_height * 3) adjustment.set_step_increment(self.row_height * 3)
if next: if _next:
# If number of values is less than max rows, no scroll # If number of values is less than max rows, no scroll
if self.get_values_count() < self.max_visible_rows: if self.get_values_count() < self.max_visible_rows:
return return
@ -280,14 +280,14 @@ class ValueList(object):
path = cursor[0] path = cursor[0]
else: else:
# Since cursor is none, we won't advance the index # Since cursor is none, we won't advance the index
next = None _next = None
# If next is None, we won't change the selection # If _next is None, we won't change the selection
if next is not None: if _next is not None:
# We move the selection either one up or down. # We move the selection either one up or down.
# If we reach end of list, we wrap # If we reach end of list, we wrap
index = path[0] if path else 0 index = path[0] if path else 0
index = index + 1 if next else index - 1 index = index + 1 if _next else index - 1
if index >= len(self.tree_store): if index >= len(self.tree_store):
index = 0 index = 0
elif index < 0: elif index < 0:
@ -422,10 +422,10 @@ class StoredValuesList(ValueList):
elif key_is_up_or_down(keyval): elif key_is_up_or_down(keyval):
# Swap the row value # Swap the row value
if event.state & gtk.gdk.CONTROL_MASK: if event.state & gtk.gdk.CONTROL_MASK:
self.handle_list_scroll(next=key_is_down(keyval), self.handle_list_scroll(_next=key_is_down(keyval),
swap=True) swap=True)
else: else:
self.handle_list_scroll(next=key_is_down(keyval)) self.handle_list_scroll(_next=key_is_down(keyval))
elif key_is_pgup_or_pgdown(event.keyval): elif key_is_pgup_or_pgdown(event.keyval):
# The cursor has been changed by the default key-press-event handler # The cursor has been changed by the default key-press-event handler
# so set the path of the cursor selected # so set the path of the cursor selected
@ -484,7 +484,7 @@ class CompletionList(ValueList):
keyval = event.keyval keyval = event.keyval
ctrl = event.state & gtk.gdk.CONTROL_MASK ctrl = event.state & gtk.gdk.CONTROL_MASK
if key_is_up_or_down(keyval): if key_is_up_or_down(keyval):
self.handle_list_scroll(next=key_is_down(keyval)) self.handle_list_scroll(_next=key_is_down(keyval))
return True return True
elif ctrl: elif ctrl:
# Set show/hide hidden files # Set show/hide hidden files
@ -501,7 +501,7 @@ class CompletionList(ValueList):
path = self.treeview.get_path_at_pos(int(x), int(y)) path = self.treeview.get_path_at_pos(int(x), int(y))
if path: if path:
self.handle_list_scroll(path=path[0], next=None) self.handle_list_scroll(path=path[0], _next=None)
class PathChooserPopup(object): class PathChooserPopup(object):
@ -667,7 +667,7 @@ class PathChooserPopup(object):
def set_max_popup_rows(self, rows): def set_max_popup_rows(self, rows):
try: try:
int(rows) int(rows)
except: except Exception:
self.max_visible_rows = 20 self.max_visible_rows = 20
return return
self.max_visible_rows = rows self.max_visible_rows = rows
@ -780,7 +780,7 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup):
""" """
swap = event.state & gtk.gdk.CONTROL_MASK swap = event.state & gtk.gdk.CONTROL_MASK
scroll_window = event.state & gtk.gdk.SHIFT_MASK scroll_window = event.state & gtk.gdk.SHIFT_MASK
self.handle_list_scroll(next=event.direction == gdk.SCROLL_DOWN, self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN,
set_entry=widget != self.treeview, swap=swap, scroll_window=scroll_window) set_entry=widget != self.treeview, swap=swap, scroll_window=scroll_window)
return True return True
@ -829,10 +829,10 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup):
return True return True
def on_button_up_clicked(self, widget): def on_button_up_clicked(self, widget):
self.handle_list_scroll(next=False, swap=True) self.handle_list_scroll(_next=False, swap=True)
def on_button_down_clicked(self, widget): def on_button_down_clicked(self, widget):
self.handle_list_scroll(next=True, swap=True) self.handle_list_scroll(_next=True, swap=True)
def on_button_default_clicked(self, widget): def on_button_default_clicked(self, widget):
if self.default_text: if self.default_text:
@ -904,11 +904,11 @@ class PathCompletionPopup(CompletionList, PathChooserPopup):
""" """
x, y, state = event.window.get_pointer() x, y, state = event.window.get_pointer()
self.handle_list_scroll(next=event.direction == gdk.SCROLL_DOWN, self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN,
set_entry=widget != self.treeview, scroll_window=True) set_entry=widget != self.treeview, scroll_window=True)
path = self.treeview.get_path_at_pos(int(x), int(y)) path = self.treeview.get_path_at_pos(int(x), int(y))
if path: if path:
self.handle_list_scroll(path=path[0], next=None) self.handle_list_scroll(path=path[0], _next=None)
return True return True
@ -970,7 +970,7 @@ class PathAutoCompleter(object):
if values_count == 1: if values_count == 1:
self.do_completion() self.do_completion()
else: else:
self.completion_popup.handle_list_scroll(next=True) self.completion_popup.handle_list_scroll(_next=True)
return True return True
self.path_entry.text_entry.emit("key-press-event", event) self.path_entry.text_entry.emit("key-press-event", event)
@ -1305,7 +1305,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
# Select new row with arrow up/down is pressed # Select new row with arrow up/down is pressed
if key_is_up_or_down(keyval): if key_is_up_or_down(keyval):
self.handle_list_scroll(next=key_is_down(keyval), self.handle_list_scroll(_next=key_is_down(keyval),
set_entry=True) set_entry=True)
return True return True
elif self.auto_completer.is_auto_completion_accelerator(keyval, state): elif self.auto_completer.is_auto_completion_accelerator(keyval, state):
@ -1515,7 +1515,7 @@ if __name__ == "__main__":
box1.add(entry1) box1.add(entry1)
box1.add(entry2) box1.add(entry2)
paths = [ test_paths = [
"/home/bro/Downloads", "/home/bro/Downloads",
"/media/Movies-HD", "/media/Movies-HD",
"/media/torrent/in", "/media/torrent/in",
@ -1528,7 +1528,7 @@ if __name__ == "__main__":
"/media/Series/19" "/media/Series/19"
] ]
entry1.add_values(paths) entry1.add_values(test_paths)
entry1.set_text("/home/bro/", default_text=True) entry1.set_text("/home/bro/", default_text=True)
entry2.set_text("/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/", entry2.set_text("/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/",
cursor_end=False) cursor_end=False)

View file

@ -315,9 +315,9 @@ class PeersTab(Tab):
if not widget.get_tooltip_context(x, y, keyboard_tip): if not widget.get_tooltip_context(x, y, keyboard_tip):
return False return False
else: else:
model, path, iter = widget.get_tooltip_context(x, y, keyboard_tip) model, path, _iter = widget.get_tooltip_context(x, y, keyboard_tip)
country_code = model.get(iter, 5)[0] country_code = model.get(_iter, 5)[0]
if country_code != " " and country_code in COUNTRIES: if country_code != " " and country_code in COUNTRIES:
tooltip.set_text(COUNTRIES[country_code]) tooltip.set_text(COUNTRIES[country_code])
# widget here is self.listview # widget here is self.listview

View file

@ -207,10 +207,10 @@ class PiecesBar(gtk.DrawingArea):
if self.__state: if self.__state:
text += _(self.__state) + " " text += _(self.__state) + " "
if self.__fraction == 1.0: if self.__fraction == 1.0:
format = "%d%%" fraction_format = "%d%%"
else: else:
format = "%.2f%%" fraction_format = "%.2f%%"
text += format % (self.__fraction * 100) text += fraction_format % (self.__fraction * 100)
log.trace("PiecesBar text %r", text) log.trace("PiecesBar text %r", text)
pl.set_text(text) pl.set_text(text)
plsize = pl.get_size() plsize = pl.get_size()

View file

@ -43,7 +43,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
"""Deregisters a hook function""" """Deregisters a hook function"""
try: try:
self.hooks[hook].remove(function) self.hooks[hook].remove(function)
except: except KeyError:
log.warning("Unable to deregister hook %s", hook) log.warning("Unable to deregister hook %s", hook)
def start(self): def start(self):

View file

@ -77,8 +77,8 @@ class Preferences(component.Component):
self.liststore.append([i, category]) self.liststore.append([i, category])
i += 1 i += 1
def set_separator(model, iter, data=None): def set_separator(model, _iter, data=None):
if "_separator_" == model.get_value(iter, 1): if "_separator_" == model.get_value(_iter, 1):
return True return True
self.treeview.set_row_separator_func(set_separator) self.treeview.set_row_separator_func(set_separator)
@ -207,13 +207,14 @@ class Preferences(component.Component):
translations_path = deluge.common.get_translations_path() translations_path = deluge.common.get_translations_path()
for root, dirs, files in os.walk(translations_path): for root, dirs, files in os.walk(translations_path):
# Get the dirs # Get the dirs
lang_dirs = dirs
break break
self.language_combo = self.builder.get_object("combobox_language") self.language_combo = self.builder.get_object("combobox_language")
self.language_checkbox = self.builder.get_object("checkbutton_language") self.language_checkbox = self.builder.get_object("checkbutton_language")
lang_model = self.language_combo.get_model() lang_model = self.language_combo.get_model()
index = -1 index = -1
for i, lang_code in enumerate(sorted(dirs)): for i, lang_code in enumerate(sorted(lang_dirs)):
name = "%s (Language name missing)" % lang_code name = "%s (Language name missing)" % lang_code
if lang_code in languages.LANGUAGES: if lang_code in languages.LANGUAGES:
name = languages.LANGUAGES[lang_code] name = languages.LANGUAGES[lang_code]
@ -267,12 +268,12 @@ class Preferences(component.Component):
self.page_num_to_remove = None self.page_num_to_remove = None
self.iter_to_remove = None self.iter_to_remove = None
def check_row(model, path, iter, user_data): def check_row(model, path, _iter, user_data):
row_name = model.get_value(iter, 1) row_name = model.get_value(_iter, 1)
if row_name == user_data: if row_name == user_data:
# This is the row we need to remove # This is the row we need to remove
self.page_num_to_remove = model.get_value(iter, 0) self.page_num_to_remove = model.get_value(_iter, 0)
self.iter_to_remove = iter self.iter_to_remove = _iter
return return
self.liststore.foreach(check_row, name) self.liststore.foreach(check_row, name)
@ -834,7 +835,7 @@ class Preferences(component.Component):
"""Handles widget sensitivity based on radio/check button values.""" """Handles widget sensitivity based on radio/check button values."""
try: try:
value = widget.get_active() value = widget.get_active()
except: except Exception:
return return
path_choosers = {"download_location_path_chooser": self.download_location_path_chooser, path_choosers = {"download_location_path_chooser": self.download_location_path_chooser,
@ -981,7 +982,6 @@ class Preferences(component.Component):
import base64 import base64
import shutil import shutil
import os.path
filename = os.path.split(filepath)[1] filename = os.path.split(filepath)[1]
shutil.copyfile( shutil.copyfile(
filepath, filepath,
@ -1080,15 +1080,15 @@ class Preferences(component.Component):
self.accounts_liststore.clear() self.accounts_liststore.clear()
for account in known_accounts: for account in known_accounts:
iter = self.accounts_liststore.append() accounts_iter = self.accounts_liststore.append()
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_USERNAME, account['username'] accounts_iter, ACCOUNTS_USERNAME, account['username']
) )
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_LEVEL, account['authlevel'] accounts_iter, ACCOUNTS_LEVEL, account['authlevel']
) )
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_PASSWORD, account['password'] accounts_iter, ACCOUNTS_PASSWORD, account['password']
) )
def _on_accounts_selection_changed(self, treeselection): def _on_accounts_selection_changed(self, treeselection):
@ -1116,15 +1116,15 @@ class Preferences(component.Component):
authlevel = dialog.get_authlevel() authlevel = dialog.get_authlevel()
def add_ok(rv): def add_ok(rv):
iter = self.accounts_liststore.append() accounts_iter = self.accounts_liststore.append()
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_USERNAME, username accounts_iter, ACCOUNTS_USERNAME, username
) )
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_LEVEL, authlevel accounts_iter, ACCOUNTS_LEVEL, authlevel
) )
self.accounts_liststore.set_value( self.accounts_liststore.set_value(
iter, ACCOUNTS_PASSWORD, password accounts_iter, ACCOUNTS_PASSWORD, password
) )
def add_fail(failure): def add_fail(failure):

View file

@ -152,8 +152,8 @@ class QueuedTorrents(component.Component):
def on_button_add_clicked(self, widget): def on_button_add_clicked(self, widget):
# Add all the torrents in the liststore # Add all the torrents in the liststore
def add_torrent(model, path, iter, data): def add_torrent(model, path, _iter, data):
torrent_path = model.get_value(iter, 1).decode('utf-8') torrent_path = model.get_value(_iter, 1).decode('utf-8')
process_args([torrent_path]) process_args([torrent_path])
self.liststore.foreach(add_torrent, None) self.liststore.foreach(add_torrent, None)

View file

@ -71,7 +71,7 @@ class RemoveTorrentDialog(object):
if errors: if errors:
log.info("Error(s) occured when trying to delete torrent(s).") log.info("Error(s) occured when trying to delete torrent(s).")
for t_id, e_msg in errors: for t_id, e_msg in errors:
log.warn("Error removing torrent %s : %s" % (t_id, e_msg)) log.warn("Error removing torrent %s : %s", t_id, e_msg)
d = client.core.remove_torrents(self.__torrent_ids, remove_data) d = client.core.remove_torrents(self.__torrent_ids, remove_data)
d.addCallback(on_removed_finished) d.addCallback(on_removed_finished)

View file

@ -106,11 +106,7 @@ class SystemTray(component.Component):
if deluge.common.windows_check() or deluge.common.osx_check(): if deluge.common.windows_check() or deluge.common.osx_check():
self.tray = gtk.status_icon_new_from_pixbuf(get_logo(32)) self.tray = gtk.status_icon_new_from_pixbuf(get_logo(32))
else: else:
try:
self.tray = gtk.status_icon_new_from_icon_name("deluge") self.tray = gtk.status_icon_new_from_icon_name("deluge")
except:
log.warning("Update PyGTK to 2.10 or greater for SystemTray..")
return
self.tray.connect("activate", self.on_tray_clicked) self.tray.connect("activate", self.on_tray_clicked)
self.tray.connect("popup-menu", self.on_tray_popup) self.tray.connect("popup-menu", self.on_tray_popup)

View file

@ -138,7 +138,7 @@ class TorrentDetails(component.Component):
for w, name in weights: for w, name in weights:
if w >= weight: if w >= weight:
position = self.tabs[name].position position = self.tabs[name].position
log.debug("Found pos %d" % position) log.debug("Found pos %d", position)
break break
return position return position
@ -166,12 +166,12 @@ class TorrentDetails(component.Component):
tab.is_visible = True tab.is_visible = True
# add the tab at position guided by the weight # add the tab at position guided by the weight
insert_pos = self.tab_insert_position(weight) insert_pos = self.tab_insert_position(weight)
log.debug("Trying to insert tab at %d" % insert_pos) log.debug("Trying to insert tab at %d", insert_pos)
pos = self.notebook.insert_page( pos = self.notebook.insert_page(
tab.get_child_widget(), tab.get_child_widget(),
tab.get_tab_label(), tab.get_tab_label(),
insert_pos) insert_pos)
log.debug("Tab inserted at %d" % pos) log.debug("Tab inserted at %d", pos)
tab.position = pos tab.position = pos
if not self.notebook.get_property("visible"): if not self.notebook.get_property("visible"):
# If the notebook isn't visible, show it # If the notebook isn't visible, show it
@ -386,10 +386,10 @@ class TorrentDetails(component.Component):
# Leave tabs we dont know anything about it the state as they # Leave tabs we dont know anything about it the state as they
# might come from a plugin # might come from a plugin
for i, (name, visible) in enumerate(self.state): for i, (name, visible) in enumerate(self.state):
log.debug("Testing name: %s" % name) log.debug("Testing name: %s", name)
if name in self.tabs: if name in self.tabs:
self.state[i] = (name, self.tabs[name].is_visible) self.state[i] = (name, self.tabs[name].is_visible)
log.debug("Set to %s %d" % self.state[i]) log.debug("Set to %s", self.state[i])
state = self.state state = self.state
save_pickled_state_file("tabs.state", state) save_pickled_state_file("tabs.state", state)

View file

@ -598,7 +598,7 @@ class TorrentView(ListView, component.Component):
"""Returns data stored in self.status, it may not be complete""" """Returns data stored in self.status, it may not be complete"""
try: try:
return self.status[torrent_id] return self.status[torrent_id]
except: except KeyError:
return {} return {}
def get_visible_torrents(self): def get_visible_torrents(self):

View file

@ -388,7 +388,7 @@ class TrackerIcons(Component):
icon = TrackerIcon(icon_name) icon = TrackerIcon(icon_name)
return icon return icon
def on_download_icon_fail(self, f, host, icons=[]): def on_download_icon_fail(self, f, host, icons=None):
""" """
Recovers from a download error Recovers from a download error
@ -402,6 +402,8 @@ class TrackerIcons(Component):
else the original failure else the original failure
:rtype: Deferred or Failure :rtype: Deferred or Failure
""" """
if not icons:
icons = []
error_msg = f.getErrorMessage() error_msg = f.getErrorMessage()
log.debug("Error downloading icon from %s: %s", host, error_msg) log.debug("Error downloading icon from %s: %s", host, error_msg)
d = f d = f
@ -495,21 +497,21 @@ class FaviconParser(HTMLParser):
def handle_starttag(self, tag, attrs): def handle_starttag(self, tag, attrs):
if tag == "link" and ("rel", "icon") in attrs or ("rel", "shortcut icon") in attrs: if tag == "link" and ("rel", "icon") in attrs or ("rel", "shortcut icon") in attrs:
href = None href = None
type = None icon_type = None
for attr, value in attrs: for attr, value in attrs:
if attr == "href": if attr == "href":
href = value href = value
elif attr == "type": elif attr == "type":
type = value icon_type = value
if href: if href:
try: try:
mimetype = extension_to_mimetype(href.rpartition(".")[2]) mimetype = extension_to_mimetype(href.rpartition(".")[2])
except KeyError: except KeyError:
pass pass
else: else:
type = mimetype icon_type = mimetype
if type: if icon_type:
self.icons.append((href, type)) self.icons.append((href, icon_type))
def handle_endtag(self, tag): def handle_endtag(self, tag):
if tag == "head": if tag == "head":

View file

@ -117,7 +117,6 @@ class _UI(object):
class UI: class UI:
def __init__(self, options, args, ui_args): def __init__(self, options, args, ui_args):
import logging
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
log.debug("UI init..") log.debug("UI init..")
@ -153,7 +152,6 @@ class UI:
from deluge.ui.console.main import ConsoleUI from deluge.ui.console.main import ConsoleUI
ConsoleUI(ui_args) ConsoleUI(ui_args)
except ImportError as ex: except ImportError as ex:
import sys
import traceback import traceback
error_type, error_value, tb = sys.exc_info() error_type, error_value, tb = sys.exc_info()
stack = traceback.extract_tb(tb) stack = traceback.extract_tb(tb)

View file

@ -13,7 +13,6 @@ import random
import time import time
from datetime import datetime, timedelta from datetime import datetime, timedelta
from email.utils import formatdate from email.utils import formatdate
from functools import reduce
from twisted.internet.task import LoopingCall from twisted.internet.task import LoopingCall
@ -43,7 +42,10 @@ from deluge.ui.web.json_api import export, JSONComponent # NOQA, isort:skip
def make_checksum(session_id): def make_checksum(session_id):
return reduce(lambda x, y: x + y, map(ord, session_id)) checksum = 0
for value in [ord(char) for char in session_id]:
checksum += value
return checksum
def get_session_id(session_id): def get_session_id(session_id):

View file

@ -31,9 +31,9 @@ def escape(text):
def compress(contents, request): def compress(contents, request):
request.setHeader("content-encoding", "gzip") request.setHeader("content-encoding", "gzip")
compress = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0) compress_zlib = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0)
contents = compress.compress(contents) contents = compress_zlib.compress(contents)
contents += compress.flush() contents += compress_zlib.flush()
return contents return contents
try: try:

View file

@ -60,7 +60,7 @@ def export(auth_level=AUTH_LEVEL_DEFAULT):
""" """
global AUTH_LEVEL_DEFAULT, AuthError global AUTH_LEVEL_DEFAULT, AuthError
if AUTH_LEVEL_DEFAULT is None: if AUTH_LEVEL_DEFAULT is None:
from deluge.ui.web.auth import AUTH_LEVEL_DEFAULT from deluge.ui.web.auth import AUTH_LEVEL_DEFAULT, AuthError # pylint: disable=redefined-outer-name
def wrap(func, *args, **kwargs): def wrap(func, *args, **kwargs):
func._json_export = True func._json_export = True
@ -847,7 +847,7 @@ class WebApi(JSONComponent):
d = c.connect(host, port, user, password) d = c.connect(host, port, user, password)
d.addCallback(on_connect, c) d.addCallback(on_connect, c)
d.addErrback(on_connect_failed) d.addErrback(on_connect_failed)
except: except Exception:
main_deferred.callback((False, "An error occurred")) main_deferred.callback((False, "An error occurred"))
return main_deferred return main_deferred
@ -874,7 +874,7 @@ class WebApi(JSONComponent):
try: try:
port = int(port) port = int(port)
except: except ValueError:
return (False, "Port is invalid") return (False, "Port is invalid")
# Host isn't in the list, so lets add it # Host isn't in the list, so lets add it

View file

@ -261,7 +261,7 @@ class ScriptResource(resource.Resource, component.Component):
} }
} }
def add_script(self, path, filepath, type=None): def add_script(self, path, filepath, script_type=None):
""" """
Adds a script or scripts to the script resource. Adds a script or scripts to the script resource.
@ -269,16 +269,16 @@ class ScriptResource(resource.Resource, component.Component):
:type path: string :type path: string
:param filepath: The physical location of the script :param filepath: The physical location of the script
:type filepath: string :type filepath: string
:keyword type: The type of script to add (normal, debug, dev) :keyword script_type: The type of script to add (normal, debug, dev)
:param type: string :param script_type: string
""" """
if type not in ("dev", "debug", "normal"): if script_type not in ("dev", "debug", "normal"):
type = "normal" script_type = "normal"
self.__scripts[type]["scripts"][path] = filepath self.__scripts[script_type]["scripts"][path] = filepath
self.__scripts[type]["order"].append(path) self.__scripts[script_type]["order"].append(path)
def add_script_folder(self, path, filepath, type=None, recurse=True): def add_script_folder(self, path, filepath, script_type=None, recurse=True):
""" """
Adds a folder of scripts to the script resource. Adds a folder of scripts to the script resource.
@ -286,45 +286,45 @@ class ScriptResource(resource.Resource, component.Component):
:type path: string :type path: string
:param filepath: The physical location of the script :param filepath: The physical location of the script
:type filepath: string :type filepath: string
:keyword type: The type of script to add (normal, debug, dev) :keyword script_type: The type of script to add (normal, debug, dev)
:param type: string :param script_type: string
:keyword recurse: Whether or not to recurse into other folders :keyword recurse: Whether or not to recurse into other folders
:param recurse: bool :param recurse: bool
""" """
if type not in ("dev", "debug", "normal"): if script_type not in ("dev", "debug", "normal"):
type = "normal" script_type = "normal"
self.__scripts[type]["scripts"][path] = (filepath, recurse) self.__scripts[script_type]["scripts"][path] = (filepath, recurse)
self.__scripts[type]["order"].append(path) self.__scripts[script_type]["order"].append(path)
def remove_script(self, path, type=None): def remove_script(self, path, script_type=None):
""" """
Removes a script or folder of scripts from the script resource. Removes a script or folder of scripts from the script resource.
:param path: The path of the folder :param path: The path of the folder
:type path: string :type path: string
:keyword type: The type of script to add (normal, debug, dev) :keyword script_type: The type of script to add (normal, debug, dev)
:param type: string :param script_type: string
""" """
if type not in ("dev", "debug", "normal"): if script_type not in ("dev", "debug", "normal"):
type = "normal" script_type = "normal"
del self.__scripts[type]["scripts"][path] del self.__scripts[script_type]["scripts"][path]
self.__scripts[type]["order"].remove(path) self.__scripts[script_type]["order"].remove(path)
def get_scripts(self, type=None): def get_scripts(self, script_type=None):
""" """
Returns a list of the scripts that can be used for producing Returns a list of the scripts that can be used for producing
script tags. script tags.
:keyword type: The type of scripts to get (normal, debug, dev) :keyword script_type: The type of scripts to get (normal, debug, dev)
:param type: string :param script_type: string
""" """
if type not in ("dev", "debug", "normal"): if script_type not in ("dev", "debug", "normal"):
type = 'normal' script_type = 'normal'
_scripts = self.__scripts[type]["scripts"] _scripts = self.__scripts[script_type]["scripts"]
_order = self.__scripts[type]["order"] _order = self.__scripts[script_type]["order"]
scripts = [] scripts = []
for path in _order: for path in _order:
@ -371,8 +371,8 @@ class ScriptResource(resource.Resource, component.Component):
def render(self, request): def render(self, request):
log.debug("Requested path: '%s'", request.lookup_path) log.debug("Requested path: '%s'", request.lookup_path)
for type in ("dev", "debug", "normal"): for script_type in ("dev", "debug", "normal"):
scripts = self.__scripts[type]["scripts"] scripts = self.__scripts[script_type]["scripts"]
for pattern in scripts: for pattern in scripts:
if not request.lookup_path.startswith(pattern): if not request.lookup_path.startswith(pattern):
continue continue
@ -536,16 +536,19 @@ class TopLevel(resource.Resource):
class ServerContextFactory: class ServerContextFactory:
def __init__(self):
pass
def getContext(self): # NOQA def getContext(self): # NOQA
"""Creates an SSL context.""" """Creates an SSL context."""
ctx = SSL.Context(SSL.SSLv23_METHOD) ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
deluge_web = component.get("DelugeWeb") delugeweb = component.get("DelugeWeb")
log.debug("Enabling SSL using:") log.debug("Enabling SSL using:")
log.debug("Pkey: %s", deluge_web.pkey) log.debug("Pkey: %s", delugeweb.pkey)
log.debug("Cert: %s", deluge_web.cert) log.debug("Cert: %s", delugeweb.cert)
ctx.use_privatekey_file(configmanager.get_config_dir(deluge_web.pkey)) ctx.use_privatekey_file(configmanager.get_config_dir(delugeweb.pkey))
ctx.use_certificate_chain_file(configmanager.get_config_dir(deluge_web.cert)) ctx.use_certificate_chain_file(configmanager.get_config_dir(delugeweb.cert))
return ctx return ctx

View file

@ -12,7 +12,8 @@ from __future__ import print_function
import os import os
from optparse import OptionGroup from optparse import OptionGroup
import deluge.common from deluge.common import osx_check, windows_check
from deluge.configmanager import get_config_dir
from deluge.ui.ui import _UI, UI from deluge.ui.ui import _UI, UI
@ -35,14 +36,14 @@ class Web(_UI):
group.add_option("-b", "--base", dest="base", group.add_option("-b", "--base", dest="base",
help="Set the base path that the ui is running on (proxying)", help="Set the base path that the ui is running on (proxying)",
action="store", default=None) action="store", default=None)
if not (deluge.common.windows_check() or deluge.common.osx_check()): if not (windows_check() or osx_check()):
group.add_option("-d", "--do-not-daemonize", dest="donotdaemonize", group.add_option("-d", "--do-not-daemonize", dest="donotdaemonize",
help="Do not daemonize the web interface", help="Do not daemonize the web interface",
action="store_true", default=False) action="store_true", default=False)
group.add_option("-P", "--pidfile", dest="pidfile", type="str", group.add_option("-P", "--pidfile", dest="pidfile", type="str",
help="Use pidfile to store process id", help="Use pidfile to store process id",
action="store", default=None) action="store", default=None)
if not deluge.common.windows_check(): if not windows_check():
group.add_option("-U", "--user", dest="user", type="str", group.add_option("-U", "--user", dest="user", type="str",
help="User to switch to. Only use it when starting as root", help="User to switch to. Only use it when starting as root",
action="store", default=None) action="store", default=None)
@ -60,8 +61,8 @@ class Web(_UI):
action="store_true", default=False) action="store_true", default=False)
try: try:
import OpenSSL import OpenSSL
OpenSSL.__version__ assert OpenSSL.__version__
except: except ImportError:
pass pass
else: else:
group.add_option("--no-ssl", dest="ssl", action="store_false", group.add_option("--no-ssl", dest="ssl", action="store_false",
@ -94,8 +95,7 @@ class Web(_UI):
# chdir() to esnure that our process doesn't keep any directory in # chdir() to esnure that our process doesn't keep any directory in
# use that may prevent a filesystem unmount. # use that may prevent a filesystem unmount.
import deluge.configmanager os.chdir(get_config_dir())
os.chdir(deluge.configmanager.get_config_dir())
if self.options.pidfile: if self.options.pidfile:
open(self.options.pidfile, "wb").write("%d\n" % os.getpid()) open(self.options.pidfile, "wb").write("%d\n" % os.getpid())
@ -133,7 +133,7 @@ class Web(_UI):
if self.options.profile: if self.options.profile:
import cProfile import cProfile
profiler = cProfile.Profile() profiler = cProfile.Profile()
profile_output = deluge.configmanager.get_config_dir("delugeweb.profile") profile_output = get_config_dir("delugeweb.profile")
# Twisted catches signals to terminate # Twisted catches signals to terminate
def save_profile_stats(): def save_profile_stats():

View file

@ -63,13 +63,15 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes # no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W" # --disable=W"
# #
# Arranged by category (convention, error, information, refactor, warning). # Arranged by category: Convention, Error, Information, Refactor, Warning.
# One category per line using symbolic names instead of ids. # Category per line (wrapped categories are indented) using symbolic names instead of ids.
disable=missing-docstring, invalid-name, old-style-class, bad-continuation, disable=missing-docstring, invalid-name, old-style-class, bad-continuation,
no-member, not-callable, no-name-in-module, no-member, not-callable, no-name-in-module,
locally-disabled, locally-disabled,
R, R,
W unused-argument, broad-except, fixme, protected-access, import-error, unidiomatic-typecheck,
unused-variable, global-statement, attribute-defined-outside-init, arguments-differ,
no-init, non-parent-init-called, super-init-not-called, signature-differs
[REPORTS] [REPORTS]