summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorCalum Lind <calumlind@gmail.com>2018-06-01 15:35:19 +0100
committerCalum Lind <calumlind@gmail.com>2018-06-01 23:41:17 +0100
commitd642fa398924913c04eea3c2ddb769a4a6857fc3 (patch)
tree420c6e4d20b5550d1fc2ac2586968df4bf407ac6
parentbae1647e99e68244607e50633ca67a8c5b16ebfb (diff)
downloaddeluge-d642fa398924913c04eea3c2ddb769a4a6857fc3.tar.gz
deluge-d642fa398924913c04eea3c2ddb769a4a6857fc3.tar.bz2
deluge-d642fa398924913c04eea3c2ddb769a4a6857fc3.zip
Fix files to pass new Flake8 checkers
Some new flake8 checkers were added so fix these new warnings and any issues uncovered. Use add-trailing-comma to fix missing trailing commas. It does not format it as well as I would like however it was fast to change and helps with git changes in future. Removed pylint from tox due to large number of warnings.
-rw-r--r--deluge/__rpcapi.py2
-rw-r--r--deluge/bencode.py14
-rw-r--r--deluge/common.py66
-rw-r--r--deluge/component.py30
-rw-r--r--deluge/config.py23
-rw-r--r--deluge/configmanager.py8
-rw-r--r--deluge/core/alertmanager.py16
-rw-r--r--deluge/core/authmanager.py21
-rw-r--r--deluge/core/core.py71
-rw-r--r--deluge/core/daemon.py22
-rw-r--r--deluge/core/daemon_entry.py56
-rw-r--r--deluge/core/filtermanager.py2
-rw-r--r--deluge/core/pluginmanager.py3
-rw-r--r--deluge/core/preferencesmanager.py48
-rw-r--r--deluge/core/rpcserver.py51
-rw-r--r--deluge/core/torrent.py42
-rw-r--r--deluge/core/torrentmanager.py127
-rw-r--r--deluge/decorators.py6
-rw-r--r--deluge/error.py15
-rw-r--r--deluge/httpdownloader.py32
-rw-r--r--deluge/log.py50
-rw-r--r--deluge/maketorrent.py2
-rw-r--r--deluge/metafile.py46
-rw-r--r--deluge/pluginmanagerbase.py18
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py75
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py117
-rw-r--r--deluge/plugins/AutoAdd/setup.py2
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py2
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py24
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/decompressers.py12
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py6
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py54
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py2
-rw-r--r--deluge/plugins/Blocklist/setup.py2
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/core.py10
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/gtkui.py2
-rw-r--r--deluge/plugins/Execute/setup.py2
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/core.py2
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py2
-rw-r--r--deluge/plugins/Extractor/setup.py2
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/core.py17
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py8
-rw-r--r--deluge/plugins/Label/setup.py2
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/common.py12
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/core.py24
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py263
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/test.py10
-rwxr-xr-xdeluge/plugins/Notifications/setup.py2
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py8
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py39
-rw-r--r--deluge/plugins/Scheduler/setup.py2
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/core.py15
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/graph.py7
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/gtkui.py38
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py16
-rw-r--r--deluge/plugins/Stats/setup.py2
-rw-r--r--deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py6
-rw-r--r--deluge/plugins/Toggle/setup.py2
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/core.py2
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py8
-rw-r--r--deluge/plugins/WebUi/setup.py2
-rw-r--r--deluge/rencode.py24
-rw-r--r--deluge/scripts/create_plugin.py14
-rw-r--r--deluge/scripts/deluge_remote.py48
-rw-r--r--deluge/tests/basetest.py8
-rw-r--r--deluge/tests/common.py24
-rw-r--r--deluge/tests/daemon_base.py20
-rw-r--r--deluge/tests/test_authmanager.py2
-rw-r--r--deluge/tests/test_client.py16
-rw-r--r--deluge/tests/test_common.py27
-rw-r--r--deluge/tests/test_component.py11
-rw-r--r--deluge/tests/test_core.py8
-rw-r--r--deluge/tests/test_error.py6
-rw-r--r--deluge/tests/test_files_tab.py40
-rw-r--r--deluge/tests/test_httpdownloader.py6
-rw-r--r--deluge/tests/test_json_api.py23
-rw-r--r--deluge/tests/test_torrent.py17
-rw-r--r--deluge/tests/test_torrentview.py92
-rw-r--r--deluge/tests/test_transfer.py10
-rw-r--r--deluge/tests/test_ui_common.py24
-rw-r--r--deluge/tests/test_ui_entry.py8
-rw-r--r--deluge/tests/test_web_api.py18
-rw-r--r--deluge/tests/test_webserver.py12
-rw-r--r--deluge/tests/twisted/plugins/delugereporter.py14
-rw-r--r--deluge/ui/Win32IconImagePlugin.py9
-rw-r--r--deluge/ui/baseargparser.py98
-rw-r--r--deluge/ui/client.py68
-rw-r--r--deluge/ui/common.py36
-rw-r--r--deluge/ui/console/cmdline/commands/__init__.py1
-rw-r--r--deluge/ui/console/cmdline/commands/add.py14
-rw-r--r--deluge/ui/console/cmdline/commands/info.py65
-rw-r--r--deluge/ui/console/cmdline/commands/manage.py8
-rw-r--r--deluge/ui/console/cmdline/commands/pause.py6
-rw-r--r--deluge/ui/console/cmdline/commands/plugin.py18
-rw-r--r--deluge/ui/console/cmdline/commands/resume.py6
-rw-r--r--deluge/ui/console/cmdline/commands/rm.py20
-rw-r--r--deluge/ui/console/cmdline/commands/status.py16
-rw-r--r--deluge/ui/console/cmdline/commands/update_tracker.py6
-rw-r--r--deluge/ui/console/console.py66
-rw-r--r--deluge/ui/console/main.py34
-rw-r--r--deluge/ui/console/modes/add_util.py2
-rw-r--r--deluge/ui/console/modes/basemode.py22
-rw-r--r--deluge/ui/console/modes/cmdline.py14
-rw-r--r--deluge/ui/console/modes/connectionmanager.py15
-rw-r--r--deluge/ui/console/modes/preferences/preference_panes.py370
-rw-r--r--deluge/ui/console/modes/preferences/preferences.py26
-rw-r--r--deluge/ui/console/modes/torrentdetail.py125
-rw-r--r--deluge/ui/console/modes/torrentlist/add_torrents_popup.py12
-rw-r--r--deluge/ui/console/modes/torrentlist/filtersidebar.py6
-rw-r--r--deluge/ui/console/modes/torrentlist/queue_mode.py10
-rw-r--r--deluge/ui/console/modes/torrentlist/search_mode.py2
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentactions.py46
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentlist.py6
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentview.py53
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentviewcolumns.py46
-rw-r--r--deluge/ui/console/utils/colors.py12
-rw-r--r--deluge/ui/console/utils/format_utils.py8
-rw-r--r--deluge/ui/console/widgets/fields.py116
-rw-r--r--deluge/ui/console/widgets/inputpane.py32
-rw-r--r--deluge/ui/console/widgets/popup.py30
-rw-r--r--deluge/ui/console/widgets/statusbars.py3
-rw-r--r--deluge/ui/console/widgets/window.py12
-rw-r--r--deluge/ui/gtkui/__init__.py21
-rw-r--r--deluge/ui/gtkui/aboutdialog.py18
-rw-r--r--deluge/ui/gtkui/addtorrentdialog.py137
-rw-r--r--deluge/ui/gtkui/common.py6
-rw-r--r--deluge/ui/gtkui/connectionmanager.py41
-rw-r--r--deluge/ui/gtkui/createtorrentdialog.py96
-rw-r--r--deluge/ui/gtkui/dialogs.py45
-rw-r--r--deluge/ui/gtkui/edittrackersdialog.py14
-rw-r--r--deluge/ui/gtkui/files_tab.py76
-rw-r--r--deluge/ui/gtkui/filtertreeview.py16
-rw-r--r--deluge/ui/gtkui/gtkui.py24
-rw-r--r--deluge/ui/gtkui/listview.py163
-rw-r--r--deluge/ui/gtkui/mainwindow.py23
-rw-r--r--deluge/ui/gtkui/menubar.py105
-rw-r--r--deluge/ui/gtkui/new_release_dialog.py12
-rw-r--r--deluge/ui/gtkui/options_tab.py13
-rwxr-xr-xdeluge/ui/gtkui/path_combo_chooser.py79
-rw-r--r--deluge/ui/gtkui/peers_tab.py25
-rw-r--r--deluge/ui/gtkui/piecesbar.py6
-rw-r--r--deluge/ui/gtkui/pluginmanager.py5
-rw-r--r--deluge/ui/gtkui/preferences.py218
-rw-r--r--deluge/ui/gtkui/queuedtorrents.py6
-rw-r--r--deluge/ui/gtkui/removetorrentdialog.py3
-rw-r--r--deluge/ui/gtkui/status_tab.py30
-rw-r--r--deluge/ui/gtkui/statusbar.py71
-rw-r--r--deluge/ui/gtkui/systemtray.py48
-rw-r--r--deluge/ui/gtkui/toolbar.py5
-rw-r--r--deluge/ui/gtkui/torrentdetails.py23
-rw-r--r--deluge/ui/gtkui/torrentview.py168
-rw-r--r--deluge/ui/gtkui/torrentview_data_funcs.py4
-rw-r--r--deluge/ui/sessionproxy.py2
-rw-r--r--deluge/ui/tracker_icons.py50
-rw-r--r--deluge/ui/ui_entry.py32
-rw-r--r--deluge/ui/web/auth.py14
-rw-r--r--deluge/ui/web/common.py10
-rw-r--r--deluge/ui/web/json_api.py32
-rw-r--r--deluge/ui/web/pluginmanager.py2
-rw-r--r--deluge/ui/web/server.py38
-rw-r--r--deluge/ui/web/web.py18
-rw-r--r--docs/source/conf.py2
-rwxr-xr-xgen_web_gettext.py2
-rw-r--r--packaging/win32/deluge-bbfreeze.py2
-rwxr-xr-xsetup.py10
-rw-r--r--tox.ini9
166 files changed, 3297 insertions, 1910 deletions
diff --git a/deluge/__rpcapi.py b/deluge/__rpcapi.py
index 8e5de1285..5f2934a32 100644
--- a/deluge/__rpcapi.py
+++ b/deluge/__rpcapi.py
@@ -19,7 +19,7 @@ class RpcApi(object):
def scan_for_methods(obj):
methods = {
- '__doc__': 'Methods available in %s' % obj.__name__.lower()
+ '__doc__': 'Methods available in %s' % obj.__name__.lower(),
}
for d in dir(obj):
if not hasattr(getattr(obj, d), '_rpcserver_export'):
diff --git a/deluge/bencode.py b/deluge/bencode.py
index 20abf45a4..e9610a0da 100644
--- a/deluge/bencode.py
+++ b/deluge/bencode.py
@@ -31,9 +31,9 @@ def decode_int(x, f):
f += 1
newf = x.index(END_DELIM, f)
n = int(x[f:newf])
- if x[f:f+1] == b'-' and x[f+1:f+2] == b'0':
+ if x[f:f + 1] == b'-' and x[f + 1:f + 2] == b'0':
raise ValueError
- elif x[f:f+1] == b'0' and newf != f + 1:
+ elif x[f:f + 1] == b'0' and newf != f + 1:
raise ValueError
return (n, newf + 1)
@@ -41,7 +41,7 @@ def decode_int(x, f):
def decode_string(x, f):
colon = x.index(BYTE_SEP, f)
n = int(x[f:colon])
- if x[f:f+1] == b'0' and colon != f + 1:
+ if x[f:f + 1] == b'0' and colon != f + 1:
raise ValueError
colon += 1
return (x[colon:colon + n], colon + n)
@@ -49,17 +49,17 @@ def decode_string(x, f):
def decode_list(x, f):
r, f = [], f + 1
- while x[f:f+1] != END_DELIM:
- v, f = decode_func[x[f:f+1]](x, f)
+ while x[f:f + 1] != END_DELIM:
+ v, f = decode_func[x[f:f + 1]](x, f)
r.append(v)
return (r, f + 1)
def decode_dict(x, f):
r, f = {}, f + 1
- while x[f:f+1] != END_DELIM:
+ while x[f:f + 1] != END_DELIM:
k, f = decode_string(x, f)
- r[k], f = decode_func[x[f:f+1]](x, f)
+ r[k], f = decode_func[x[f:f + 1]](x, f)
return (r, f + 1)
diff --git a/deluge/common.py b/deluge/common.py
index aef5a3d3c..225d3e797 100644
--- a/deluge/common.py
+++ b/deluge/common.py
@@ -63,7 +63,7 @@ TORRENT_STATE = [
'Paused',
'Error',
'Queued',
- 'Moving'
+ 'Moving',
]
# The output formatting for json.dump
@@ -103,7 +103,8 @@ def get_default_config_dir(filename=None):
import _winreg as winreg # For Python 2.
hkey = winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
- 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
+ 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders',
+ )
app_data_reg = winreg.QueryValueEx(hkey, 'AppData')
app_data_path = app_data_reg[0]
winreg.CloseKey(hkey)
@@ -273,7 +274,7 @@ def resource_filename(module, path):
This is a work-around that.
"""
return pkg_resources.require('Deluge>=%s' % get_version())[0].get_resource_filename(
- pkg_resources._manager, os.path.join(*(module.split('.') + [path]))
+ pkg_resources._manager, os.path.join(*(module.split('.') + [path])),
)
@@ -554,18 +555,20 @@ def tokenize(text):
return tokenized_input
-size_units = (dict(prefix='b', divider=1, singular='byte', plural='bytes'),
- dict(prefix='KiB', divider=1024**1),
- dict(prefix='MiB', divider=1024**2),
- dict(prefix='GiB', divider=1024**3),
- dict(prefix='TiB', divider=1024**4),
- dict(prefix='PiB', divider=1024**5),
- dict(prefix='KB', divider=1000**1),
- dict(prefix='MB', divider=1000**2),
- dict(prefix='GB', divider=1000**3),
- dict(prefix='TB', divider=1000**4),
- dict(prefix='PB', divider=1000**5),
- dict(prefix='m', divider=1000**2))
+size_units = [
+ {'prefix': 'b', 'divider': 1, 'singular': 'byte', 'plural': 'bytes'},
+ {'prefix': 'KiB', 'divider': 1024**1},
+ {'prefix': 'MiB', 'divider': 1024**2},
+ {'prefix': 'GiB', 'divider': 1024**3},
+ {'prefix': 'TiB', 'divider': 1024**4},
+ {'prefix': 'PiB', 'divider': 1024**5},
+ {'prefix': 'KB', 'divider': 1000**1},
+ {'prefix': 'MB', 'divider': 1000**2},
+ {'prefix': 'GB', 'divider': 1000**3},
+ {'prefix': 'TB', 'divider': 1000**4},
+ {'prefix': 'PB', 'divider': 1000**5},
+ {'prefix': 'm', 'divider': 1000**2},
+]
class InvalidSize(Exception):
@@ -906,10 +909,12 @@ def decode_bytes(byte_str, encoding='utf8'):
elif not isinstance(byte_str, bytes):
return byte_str
- encodings = [lambda: ('utf8', 'strict'),
- lambda: ('iso-8859-1', 'strict'),
- lambda: (chardet.detect(byte_str)['encoding'], 'strict'),
- lambda: (encoding, 'ignore')]
+ encodings = [
+ lambda: ('utf8', 'strict'),
+ lambda: ('iso-8859-1', 'strict'),
+ lambda: (chardet.detect(byte_str)['encoding'], 'strict'),
+ lambda: (encoding, 'ignore'),
+ ]
if encoding is not 'utf8':
encodings.insert(0, lambda: (encoding, 'strict'))
@@ -949,7 +954,10 @@ def utf8_encode_structure(data):
if isinstance(data, (list, tuple)):
return type(data)([utf8_encode_structure(d) for d in data])
elif isinstance(data, dict):
- return dict([utf8_encode_structure(d) for d in data.items()])
+ return {
+ utf8_encode_structure(k): utf8_encode_structure(v)
+ for k, v in data.items()
+ }
elif not isinstance(data, bytes):
try:
return data.encode('utf8')
@@ -968,7 +976,8 @@ class VersionSplit(object):
"""
def __init__(self, ver):
- version_re = re.compile(r"""
+ version_re = re.compile(
+ r"""
^
(?P<version>\d+\.\d+) # minimum 'N.N'
(?P<extraversion>(?:\.\d+)*) # any number of extra '.N' segments
@@ -978,7 +987,8 @@ class VersionSplit(object):
(?P<prerelversion>\d+(?:\.\d+)*)
)?
(?P<postdev>(\.post(?P<post>\d+))?(\.dev(?P<dev>\d+))?)?
- $""", re.VERBOSE)
+ $""", re.VERBOSE,
+ )
# Check for PEP 386 compliant version
match = re.search(version_re, ver)
@@ -1061,11 +1071,13 @@ def create_localclient_account(append=False):
create_auth_file()
with open(auth_file, 'a' if append else 'w') as _file:
- _file.write(':'.join([
- 'localclient',
- sha(str(random.random()).encode('utf8')).hexdigest(),
- str(AUTH_LEVEL_ADMIN)
- ]) + '\n')
+ _file.write(
+ ':'.join([
+ 'localclient',
+ sha(str(random.random()).encode('utf8')).hexdigest(),
+ str(AUTH_LEVEL_ADMIN),
+ ]) + '\n',
+ )
_file.flush()
os.fsync(_file.fileno())
diff --git a/deluge/component.py b/deluge/component.py
index de94e021d..8264a5e64 100644
--- a/deluge/component.py
+++ b/deluge/component.py
@@ -146,10 +146,12 @@ class Component(object):
elif self._component_state == 'Started':
d = succeed(True)
else:
- d = fail(ComponentException('Trying to start component "%s" but it is '
- 'not in a stopped state. Current state: %s' %
- (self._component_name, self._component_state),
- traceback.format_stack(limit=4)))
+ d = fail(ComponentException(
+ 'Trying to start component "%s" but it is '
+ 'not in a stopped state. Current state: %s' %
+ (self._component_name, self._component_state),
+ traceback.format_stack(limit=4),
+ ))
return d
def _component_stop(self):
@@ -193,10 +195,12 @@ class Component(object):
elif self._component_state == 'Paused':
d = succeed(None)
else:
- d = fail(ComponentException('Trying to pause component "%s" but it is '
- 'not in a started state. Current state: %s' %
- (self._component_name, self._component_state),
- traceback.format_stack(limit=4)))
+ d = fail(ComponentException(
+ 'Trying to pause component "%s" but it is '
+ 'not in a started state. Current state: %s' %
+ (self._component_name, self._component_state),
+ traceback.format_stack(limit=4),
+ ))
return d
def _component_resume(self):
@@ -207,10 +211,12 @@ class Component(object):
d = maybeDeferred(self._component_start_timer)
d.addCallback(on_resume)
else:
- d = fail(ComponentException('Trying to resume component "%s" but it is '
- 'not in a paused state. Current state: %s' %
- (self._component_name, self._component_state),
- traceback.format_stack(limit=4)))
+ d = fail(ComponentException(
+ 'Trying to resume component "%s" but it is '
+ 'not in a paused state. Current state: %s' %
+ (self._component_name, self._component_state),
+ traceback.format_stack(limit=4),
+ ))
return d
def _component_shutdown(self):
diff --git a/deluge/config.py b/deluge/config.py
index 1bf433683..9e3ee9187 100644
--- a/deluge/config.py
+++ b/deluge/config.py
@@ -128,7 +128,7 @@ class Config(object):
# These hold the version numbers and they will be set when loaded
self.__version = {
'format': 1,
- 'file': file_version
+ 'file': file_version,
}
# This will get set with a reactor.callLater whenever a config option
@@ -189,7 +189,8 @@ class Config(object):
# Do not allow the type to change unless it is None
if value is not None and not isinstance(
- self.__config[key], type(None)) and not isinstance(self.__config[key], type(value)):
+ self.__config[key], type(None),
+ ) and not isinstance(self.__config[key], type(value)):
try:
oldtype = type(self.__config[key])
value = oldtype(value)
@@ -427,8 +428,10 @@ class Config(object):
log.exception(ex)
log.warning('Unable to load config file: %s', filename)
- log.debug('Config %s version: %s.%s loaded: %s', filename,
- self.__version['format'], self.__version['file'], self.__config)
+ log.debug(
+ 'Config %s version: %s.%s loaded: %s', filename,
+ self.__version['format'], self.__version['file'], self.__config,
+ )
def save(self, filename=None):
"""Save configuration to disk.
@@ -510,16 +513,20 @@ class Config(object):
raise ValueError('output_version needs to be greater than input_range')
if self.__version['file'] not in input_range:
- log.debug('File version %s is not in input_range %s, ignoring converter function..',
- self.__version['file'], input_range)
+ log.debug(
+ 'File version %s is not in input_range %s, ignoring converter function..',
+ self.__version['file'], input_range,
+ )
return
try:
self.__config = func(self.__config)
except Exception as ex:
log.exception(ex)
- log.error('There was an exception try to convert config file %s %s to %s',
- self.__config_file, self.__version['file'], output_version)
+ log.error(
+ 'There was an exception try to convert config file %s %s to %s',
+ self.__config_file, self.__version['file'], output_version,
+ )
raise ex
else:
self.__version['file'] = output_version
diff --git a/deluge/configmanager.py b/deluge/configmanager.py
index b4c09b669..db4de51f6 100644
--- a/deluge/configmanager.py
+++ b/deluge/configmanager.py
@@ -94,9 +94,11 @@ class _ConfigManager(object):
log.debug('Getting config: %s', config_file)
# Create the config object if not already created
if config_file not in self.config_files:
- self.config_files[config_file] = Config(config_file, defaults,
- config_dir=self.config_directory,
- file_version=file_version)
+ self.config_files[config_file] = Config(
+ config_file, defaults,
+ config_dir=self.config_directory,
+ file_version=file_version,
+ )
return self.config_files[config_file]
diff --git a/deluge/core/alertmanager.py b/deluge/core/alertmanager.py
index ed17341a0..af4fa4287 100644
--- a/deluge/core/alertmanager.py
+++ b/deluge/core/alertmanager.py
@@ -39,13 +39,15 @@ class AlertManager(component.Component):
self.alert_queue_size = 10000
self.set_alert_queue_size(self.alert_queue_size)
- alert_mask = (lt.alert.category_t.error_notification |
- lt.alert.category_t.port_mapping_notification |
- lt.alert.category_t.storage_notification |
- lt.alert.category_t.tracker_notification |
- lt.alert.category_t.status_notification |
- lt.alert.category_t.ip_block_notification |
- lt.alert.category_t.performance_warning)
+ alert_mask = (
+ lt.alert.category_t.error_notification |
+ lt.alert.category_t.port_mapping_notification |
+ lt.alert.category_t.storage_notification |
+ lt.alert.category_t.tracker_notification |
+ lt.alert.category_t.status_notification |
+ lt.alert.category_t.ip_block_notification |
+ lt.alert.category_t.performance_warning
+ )
self.session.apply_settings({'alert_mask': alert_mask})
diff --git a/deluge/core/authmanager.py b/deluge/core/authmanager.py
index 60452f828..b241d9a75 100644
--- a/deluge/core/authmanager.py
+++ b/deluge/core/authmanager.py
@@ -28,7 +28,8 @@ AUTH_LEVELS_MAPPING = {
'READONLY': AUTH_LEVEL_READONLY,
'DEFAULT': AUTH_LEVEL_NORMAL,
'NORMAL': AUTH_LEVEL_DEFAULT,
- 'ADMIN': AUTH_LEVEL_ADMIN}
+ 'ADMIN': AUTH_LEVEL_ADMIN,
+}
AUTH_LEVELS_MAPPING_REVERSE = {v: k for k, v in AUTH_LEVELS_MAPPING.items()}
@@ -45,7 +46,7 @@ class Account(object):
'username': self.username,
'password': self.password,
'authlevel': AUTH_LEVELS_MAPPING_REVERSE[self.authlevel],
- 'authlevel_int': self.authlevel
+ 'authlevel_int': self.authlevel,
}
def __repr__(self):
@@ -98,7 +99,7 @@ class AuthManager(component.Component):
"""
if not username:
raise AuthenticationRequired(
- 'Username and Password are required.', username
+ 'Username and Password are required.', username,
)
if username not in self.__auth:
@@ -129,8 +130,10 @@ class AuthManager(component.Component):
if authlevel not in AUTH_LEVELS_MAPPING:
raise AuthManagerError('Invalid auth level: %s' % authlevel)
try:
- self.__auth[username] = Account(username, password,
- AUTH_LEVELS_MAPPING[authlevel])
+ self.__auth[username] = Account(
+ username, password,
+ AUTH_LEVELS_MAPPING[authlevel],
+ )
self.write_auth_file()
return True
except Exception as ex:
@@ -157,7 +160,7 @@ class AuthManager(component.Component):
raise AuthManagerError('Username not known', username)
elif username == component.get('RPCServer').get_session_user():
raise AuthManagerError(
- 'You cannot delete your own account while logged in!', username
+ 'You cannot delete your own account while logged in!', username,
)
del self.__auth[username]
@@ -232,8 +235,10 @@ class AuthManager(component.Component):
lsplit = line.split(':')
if len(lsplit) == 2:
username, password = lsplit
- log.warning('Your auth entry for %s contains no auth level, '
- 'using AUTH_LEVEL_DEFAULT(%s)..', username, AUTH_LEVEL_DEFAULT)
+ log.warning(
+ 'Your auth entry for %s contains no auth level, '
+ 'using AUTH_LEVEL_DEFAULT(%s)..', username, AUTH_LEVEL_DEFAULT,
+ )
if username == 'localclient':
authlevel = AUTH_LEVEL_ADMIN
else:
diff --git a/deluge/core/core.py b/deluge/core/core.py
index 10861c631..80c14f6a2 100644
--- a/deluge/core/core.py
+++ b/deluge/core/core.py
@@ -109,7 +109,8 @@ class Core(component.Component):
peer_id = self._create_peer_id(DELUGE_VER)
log.debug(
'Starting session (peer_id: %s, user_agent: %s)',
- peer_id, user_agent)
+ peer_id, user_agent,
+ )
settings_pack = {
'peer_fingerprint': peer_id,
'user_agent': user_agent,
@@ -390,7 +391,7 @@ class Core(component.Component):
try:
d = self.torrentmanager.add_async(
- filedump=filedump, options=options, filename=filename, save_state=save_state
+ filedump=filedump, options=options, filename=filename, save_state=save_state,
)
except RuntimeError as ex:
log.error('There was an error adding the torrent file %s: %s', filename, ex)
@@ -418,7 +419,8 @@ class Core(component.Component):
try:
return self.torrentmanager.add(
- filedump=filedump, options=options, filename=filename)
+ filedump=filedump, options=options, filename=filename,
+ )
except RuntimeError as ex:
log.error('There was an error adding the torrent file %s: %s', filename, ex)
raise
@@ -441,7 +443,8 @@ class Core(component.Component):
for idx, torrent in enumerate(torrent_files):
try:
yield self.add_torrent_file_async(
- torrent[0], torrent[1], torrent[2], save_state=idx == last_index)
+ torrent[0], torrent[1], torrent[2], save_state=idx == last_index,
+ )
except AddTorrentError as ex:
log.warn('Error when adding torrent: %s', ex)
errors.append(ex)
@@ -651,8 +654,10 @@ class Core(component.Component):
@export
def get_torrent_status(self, torrent_id, keys, diff=False):
torrent_keys, plugin_keys = self.torrentmanager.separate_keys(keys, [torrent_id])
- return self.create_torrent_status(torrent_id, torrent_keys, plugin_keys, diff=diff, update=True,
- all_keys=not keys)
+ return self.create_torrent_status(
+ torrent_id, torrent_keys, plugin_keys, diff=diff, update=True,
+ all_keys=not keys,
+ )
@export
def get_torrents_status(self, filter_dict, keys, diff=False):
@@ -699,7 +704,7 @@ class Core(component.Component):
@export
def get_config_values(self, keys):
"""Get the config values for the entered keys"""
- return dict((key, self.config.get(key)) for key in keys)
+ return {key: self.config.get(key) for key in keys}
@export
def set_config(self, config):
@@ -740,7 +745,7 @@ class Core(component.Component):
'port': proxy_port,
'proxy_hostnames': settings['proxy_hostnames'],
'proxy_peer_connections': settings['proxy_peer_connections'],
- 'proxy_tracker_connections': settings['proxy_tracker_connections']
+ 'proxy_tracker_connections': settings['proxy_tracker_connections'],
}
return proxy_dict
@@ -870,25 +875,32 @@ class Core(component.Component):
return deluge.common.get_path_size(path)
@export
- def create_torrent(self, path, tracker, piece_length, comment, target,
- webseeds, private, created_by, trackers, add_to_session):
+ def create_torrent(
+ self, path, tracker, piece_length, comment, target,
+ webseeds, private, created_by, trackers, add_to_session,
+ ):
log.debug('creating torrent..')
- threading.Thread(target=self._create_torrent_thread,
- args=(
- path,
- tracker,
- piece_length,
- comment,
- target,
- webseeds,
- private,
- created_by,
- trackers,
- add_to_session)).start()
-
- def _create_torrent_thread(self, path, tracker, piece_length, comment, target,
- webseeds, private, created_by, trackers, add_to_session):
+ threading.Thread(
+ target=self._create_torrent_thread,
+ args=(
+ path,
+ tracker,
+ piece_length,
+ comment,
+ target,
+ webseeds,
+ private,
+ created_by,
+ trackers,
+ add_to_session,
+ ),
+ ).start()
+
+ def _create_torrent_thread(
+ self, path, tracker, piece_length, comment, target,
+ webseeds, private, created_by, trackers, add_to_session,
+ ):
from deluge import metafile
metafile.make_meta_file(
path,
@@ -899,7 +911,8 @@ class Core(component.Component):
webseeds=webseeds,
private=private,
created_by=created_by,
- trackers=trackers)
+ trackers=trackers,
+ )
log.debug('torrent created!')
if add_to_session:
options = {}
@@ -1055,8 +1068,10 @@ class Core(component.Component):
:rtype: bool
"""
- d = getPage(b'http://deluge-torrent.org/test_port.php?port=%s' %
- self.get_listen_port(), timeout=30)
+ d = getPage(
+ b'http://deluge-torrent.org/test_port.php?port=%s' %
+ self.get_listen_port(), timeout=30,
+ )
def on_get_page(result):
return bool(int(result))
diff --git a/deluge/core/daemon.py b/deluge/core/daemon.py
index 5f4ae4fb1..e92377b21 100644
--- a/deluge/core/daemon.py
+++ b/deluge/core/daemon.py
@@ -65,8 +65,10 @@ def is_daemon_running(pid_file):
class Daemon(object):
"""The Deluge Daemon class"""
- def __init__(self, listen_interface=None, outgoing_interface=None, interface=None, port=None, standalone=False,
- read_only_config_keys=None):
+ def __init__(
+ self, listen_interface=None, outgoing_interface=None, interface=None, port=None, standalone=False,
+ read_only_config_keys=None,
+ ):
"""
Args:
listen_interface (str, optional): The IP address to listen to bittorrent connections on.
@@ -98,9 +100,11 @@ class Daemon(object):
SetConsoleCtrlHandler(win_handler)
# Start the core as a thread and join it until it's done
- self.core = Core(listen_interface=listen_interface,
- outgoing_interface=outgoing_interface,
- read_only_config_keys=read_only_config_keys)
+ self.core = Core(
+ listen_interface=listen_interface,
+ outgoing_interface=outgoing_interface,
+ read_only_config_keys=read_only_config_keys,
+ )
if port is None:
port = self.core.config['daemon_port']
@@ -114,11 +118,13 @@ class Daemon(object):
port=port,
allow_remote=self.core.config['allow_remote'],
listen=not standalone,
- interface=interface
+ interface=interface,
)
- log.debug('Listening to UI on: %s:%s and bittorrent on: %s Making connections out on: %s',
- interface, port, listen_interface, outgoing_interface)
+ log.debug(
+ 'Listening to UI on: %s:%s and bittorrent on: %s Making connections out on: %s',
+ interface, port, listen_interface, outgoing_interface,
+ )
def start(self):
# Register the daemon and the core RPCs
diff --git a/deluge/core/daemon_entry.py b/deluge/core/daemon_entry.py
index d045ca10d..0500986f3 100644
--- a/deluge/core/daemon_entry.py
+++ b/deluge/core/daemon_entry.py
@@ -23,16 +23,26 @@ from deluge.ui.translations_util import set_dummy_trans
def add_daemon_options(parser):
group = parser.add_argument_group(_('Daemon Options'))
- group.add_argument('-u', '--ui-interface', metavar='<ip-addr>', action='store',
- help=_('IP address to listen for UI connections'))
- group.add_argument('-p', '--port', metavar='<port>', action='store', type=int,
- help=_('Port to listen for UI connections on'))
- group.add_argument('-i', '--interface', metavar='<ip-addr>', dest='listen_interface', action='store',
- help=_('IP address to listen for BitTorrent connections'))
- group.add_argument('-o', '--outinterface', metavar='<ip-addr>', dest='outgoing_interface',
- action='store', help=_('The IP address for outgoing BitTorrent connections.'))
- group.add_argument('--read-only-config-keys', metavar='<comma-separated-keys>', action='store',
- help=_('Config keys to be unmodified by `set_config` RPC'), type=str, default='')
+ group.add_argument(
+ '-u', '--ui-interface', metavar='<ip-addr>', action='store',
+ help=_('IP address to listen for UI connections'),
+ )
+ group.add_argument(
+ '-p', '--port', metavar='<port>', action='store', type=int,
+ help=_('Port to listen for UI connections on'),
+ )
+ group.add_argument(
+ '-i', '--interface', metavar='<ip-addr>', dest='listen_interface', action='store',
+ help=_('IP address to listen for BitTorrent connections'),
+ )
+ group.add_argument(
+ '-o', '--outinterface', metavar='<ip-addr>', dest='outgoing_interface',
+ action='store', help=_('The IP address for outgoing BitTorrent connections.'),
+ )
+ group.add_argument(
+ '--read-only-config-keys', metavar='<comma-separated-keys>', action='store',
+ help=_('Config keys to be unmodified by `set_config` RPC'), type=str, default='',
+ )
parser.add_process_arg_group()
@@ -59,8 +69,10 @@ def start_daemon(skip_start=False):
from deluge.core.daemon import is_daemon_running
pid_file = get_config_dir('deluged.pid')
if is_daemon_running(pid_file):
- print('Cannot run multiple daemons with same config directory.\n'
- 'If you believe this is an error, force starting by deleting: %s' % pid_file)
+ print(
+ 'Cannot run multiple daemons with same config directory.\n'
+ 'If you believe this is an error, force starting by deleting: %s' % pid_file,
+ )
sys.exit(1)
log = getLogger(__name__)
@@ -74,19 +86,23 @@ def start_daemon(skip_start=False):
def run_daemon(options):
try:
from deluge.core.daemon import Daemon
- daemon = Daemon(listen_interface=options.listen_interface,
- outgoing_interface=options.outgoing_interface,
- interface=options.ui_interface,
- port=options.port,
- read_only_config_keys=options.read_only_config_keys.split(','))
+ daemon = Daemon(
+ listen_interface=options.listen_interface,
+ outgoing_interface=options.outgoing_interface,
+ interface=options.ui_interface,
+ port=options.port,
+ read_only_config_keys=options.read_only_config_keys.split(','),
+ )
if skip_start:
return daemon
else:
daemon.start()
except CannotListenError as ex:
- log.error('Cannot start deluged, listen port in use.\n'
- ' Check for other running daemons or services using this port: %s:%s',
- ex.interface, ex.port)
+ log.error(
+ 'Cannot start deluged, listen port in use.\n'
+ ' Check for other running daemons or services using this port: %s:%s',
+ ex.interface, ex.port,
+ )
sys.exit(1)
except Exception as ex:
log.error('Unable to start deluged: %s', ex)
diff --git a/deluge/core/filtermanager.py b/deluge/core/filtermanager.py
index afced7c14..09d3e1e2a 100644
--- a/deluge/core/filtermanager.py
+++ b/deluge/core/filtermanager.py
@@ -194,7 +194,7 @@ class FilterManager(component.Component):
tree_keys.remove(cat)
torrent_keys, plugin_keys = self.torrents.separate_keys(tree_keys, torrent_ids)
- items = dict((field, self.tree_fields[field]()) for field in tree_keys)
+ items = {field: self.tree_fields[field]() for field in tree_keys}
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys) # status={key:value}
diff --git a/deluge/core/pluginmanager.py b/deluge/core/pluginmanager.py
index a67e92b4b..0f5f14ec8 100644
--- a/deluge/core/pluginmanager.py
+++ b/deluge/core/pluginmanager.py
@@ -33,7 +33,8 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
# Call the PluginManagerBase constructor
deluge.pluginmanagerbase.PluginManagerBase.__init__(
- self, 'core.conf', 'deluge.plugin.core')
+ self, 'core.conf', 'deluge.plugin.core',
+ )
def start(self):
# Enable plugins that are enabled in the config
diff --git a/deluge/core/preferencesmanager.py b/deluge/core/preferencesmanager.py
index 54a94e42a..d4ba358b7 100644
--- a/deluge/core/preferencesmanager.py
+++ b/deluge/core/preferencesmanager.py
@@ -72,8 +72,10 @@ DEFAULT_PREFS = {
'max_upload_speed': -1.0,
'max_download_speed': -1.0,
'max_upload_slots_global': 4,
- 'max_half_open_connections': (lambda: deluge.common.windows_check() and
- (lambda: deluge.common.vista_check() and 4 or 8)() or 50)(),
+ 'max_half_open_connections': (
+ lambda: deluge.common.windows_check() and
+ (lambda: deluge.common.vista_check() and 4 or 8)() or 50
+ )(),
'max_connections_per_second': 20,
'ignore_limits_on_local_network': True,
'max_connections_per_torrent': -1,
@@ -123,7 +125,7 @@ DEFAULT_PREFS = {
'cache_expiry': 60,
'auto_manage_prefer_seeds': False,
'shared': False,
- 'super_seeding': False
+ 'super_seeding': False,
}
@@ -207,19 +209,28 @@ class PreferencesManager(component.Component):
interface = str(self.config['listen_interface'].strip())
interface = interface if interface else '0.0.0.0'
- log.debug('Listen Interface: %s, Ports: %s with use_sys_port: %s',
- interface, listen_ports, self.config['listen_use_sys_port'])
- interfaces = ['%s:%s' % (interface, port) for port in range(listen_ports[0], listen_ports[1]+1)]
+ log.debug(
+ 'Listen Interface: %s, Ports: %s with use_sys_port: %s',
+ interface, listen_ports, self.config['listen_use_sys_port'],
+ )
+ interfaces = [
+ '%s:%s' % (interface, port)
+ for port in range(listen_ports[0], listen_ports[1] + 1)
+ ]
self.core.apply_session_settings(
- {'listen_system_port_fallback': self.config['listen_use_sys_port'],
- 'listen_interfaces': ''.join(interfaces)})
+ {
+ 'listen_system_port_fallback': self.config['listen_use_sys_port'],
+ 'listen_interfaces': ''.join(interfaces),
+ },
+ )
def __set_outgoing_on(self):
""" Set the interface address for outgoing BitTorrent connections."""
outinterface = self.config['outgoing_interface'].strip()
outinterface = outinterface if outinterface else '0.0.0.0'
self.core.apply_session_settings(
- {'outgoing_interfaces': outinterface})
+ {'outgoing_interfaces': outinterface},
+ )
def _on_set_outgoing_ports(self, key, value):
self.__set_outgoing_ports()
@@ -254,7 +265,8 @@ class PreferencesManager(component.Component):
'router.bitcomet.com:6881',
'dht.transmissionbt.com:6881',
'dht.aelitis.com:6881',
- ])
+ ],
+ )
self.core.apply_session_settings({
'dht_bootstrap_nodes': ','.join(dht_bootstraps),
'enable_dht': value,
@@ -286,10 +298,13 @@ class PreferencesManager(component.Component):
# Convert Deluge enc_level values to libtorrent enc_level values.
pe_enc_level = {0: lt.enc_level.plaintext, 1: lt.enc_level.rc4, 2: lt.enc_level.both}
self.core.apply_session_settings(
- {'out_enc_policy': lt.enc_policy(self.config['enc_out_policy']),
- 'in_enc_policy': lt.enc_policy(self.config['enc_in_policy']),
- 'allowed_enc_level': lt.enc_level(pe_enc_level[self.config['enc_level']]),
- 'prefer_rc4': True})
+ {
+ 'out_enc_policy': lt.enc_policy(self.config['enc_out_policy']),
+ 'in_enc_policy': lt.enc_policy(self.config['enc_in_policy']),
+ 'allowed_enc_level': lt.enc_level(pe_enc_level[self.config['enc_level']]),
+ 'prefer_rc4': True,
+ },
+ )
def _on_set_max_connections_global(self, key, value):
self.core.apply_session_setting('connections_limit', value)
@@ -376,7 +391,8 @@ class PreferencesManager(component.Component):
self.new_release_timer.stop()
# Set a timer to check for a new release every 3 days
self.new_release_timer = LoopingCall(
- self._on_set_new_release_check, 'new_release_check', True)
+ self._on_set_new_release_check, 'new_release_check', True,
+ )
self.new_release_timer.start(72 * 60 * 60, False)
else:
if self.new_release_timer and self.new_release_timer.running:
@@ -392,7 +408,7 @@ class PreferencesManager(component.Component):
'proxy_peer_connections': value['proxy_peer_connections'],
'proxy_tracker_connections': value['proxy_tracker_connections'],
'force_proxy': value['force_proxy'],
- 'anonymous_mode': value['anonymous_mode']
+ 'anonymous_mode': value['anonymous_mode'],
}
if value['type'] == lt.proxy_type.i2p_proxy:
diff --git a/deluge/core/rpcserver.py b/deluge/core/rpcserver.py
index 0d56b2bcf..c8532475a 100644
--- a/deluge/core/rpcserver.py
+++ b/deluge/core/rpcserver.py
@@ -134,8 +134,10 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
for call in request:
if len(call) != 4:
- log.debug('Received invalid rpc request: number of items '
- 'in request is %s', len(call))
+ log.debug(
+ 'Received invalid rpc request: number of items '
+ 'in request is %s', len(call),
+ )
continue
# log.debug('RPCRequest: %s', format_request(call))
reactor.callLater(0, self.dispatch, *call)
@@ -161,11 +163,14 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
This method is called when a new client connects.
"""
peer = self.transport.getPeer()
- log.info('Deluge Client connection made from: %s:%s',
- peer.host, peer.port)
+ log.info(
+ 'Deluge Client connection made from: %s:%s',
+ peer.host, peer.port,
+ )
# Set the initial auth level of this session to AUTH_LEVEL_NONE
self.factory.authorized_sessions[
- self.transport.sessionno] = self.AuthLevel(AUTH_LEVEL_NONE, '')
+ self.transport.sessionno
+ ] = self.AuthLevel(AUTH_LEVEL_NONE, '')
def connectionLost(self, reason=connectionDone): # NOQA: N802
"""
@@ -219,16 +224,19 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
exc_type.__name__,
exc_value._args,
exc_value._kwargs,
- formated_tb
+ formated_tb,
))
except AttributeError:
# This is not a deluge exception (object has no attribute '_args), let's wrap it
- log.warning('An exception occurred while sending RPC_ERROR to '
- 'client. Wrapping it and resending. Error to '
- 'send(causing exception goes next):\n%s', formated_tb)
+ log.warning(
+ 'An exception occurred while sending RPC_ERROR to '
+ 'client. Wrapping it and resending. Error to '
+ 'send(causing exception goes next):\n%s', formated_tb,
+ )
try:
raise WrappedException(
- str(exc_value), exc_type.__name__, formated_tb)
+ str(exc_value), exc_type.__name__, formated_tb,
+ )
except WrappedException:
send_error()
except Exception as ex:
@@ -249,7 +257,8 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
ret = component.get('AuthManager').authorize(*args, **kwargs)
if ret:
self.factory.authorized_sessions[
- self.transport.sessionno] = self.AuthLevel(ret, args[0])
+ self.transport.sessionno
+ ] = self.AuthLevel(ret, args[0])
self.factory.session_protocols[self.transport.sessionno] = self
except Exception as ex:
send_error()
@@ -294,8 +303,10 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
auth_level = self.factory.authorized_sessions[self.transport.sessionno].auth_level
if auth_level < method_auth_requirement:
# This session is not allowed to call this method
- log.debug('Session %s is attempting an unauthorized method call!',
- self.transport.sessionno)
+ log.debug(
+ 'Session %s is attempting an unauthorized method call!',
+ self.transport.sessionno,
+ )
raise NotAuthorizedError(auth_level, method_auth_requirement)
# Set the session_id in the factory so that methods can know
# which session is calling it.
@@ -514,7 +525,7 @@ class RPCServer(component.Component):
log.debug('Emit Event: %s %s', event.name, event.args)
# This session is interested so send a RPC_EVENT
self.factory.session_protocols[session_id].sendData(
- (RPC_EVENT, event.name, event.args)
+ (RPC_EVENT, event.name, event.args),
)
def emit_event_for_session_id(self, session_id, event):
@@ -530,14 +541,18 @@ class RPCServer(component.Component):
log.debug('Session ID %s is not valid. Not sending event "%s".', session_id, event.name)
return
if session_id not in self.factory.interested_events:
- log.debug('Session ID %s is not interested in any events. Not sending event "%s".',
- session_id, event.name)
+ log.debug(
+ 'Session ID %s is not interested in any events. Not sending event "%s".',
+ session_id, event.name,
+ )
return
if event.name not in self.factory.interested_events[session_id]:
log.debug('Session ID %s is not interested in event "%s". Not sending it.', session_id, event.name)
return
- log.debug('Sending event "%s" with args "%s" to session id "%s".',
- event.name, event.args, session_id)
+ log.debug(
+ 'Sending event "%s" with args "%s" to session id "%s".',
+ event.name, event.args, session_id,
+ )
self.factory.session_protocols[session_id].sendData((RPC_EVENT, event.name, event.args))
def stop(self):
diff --git a/deluge/core/torrent.py b/deluge/core/torrent.py
index ac37dec36..fcb001b65 100644
--- a/deluge/core/torrent.py
+++ b/deluge/core/torrent.py
@@ -52,7 +52,7 @@ LT_TORRENT_STATE_MAP = {
'finished': 'Seeding',
'seeding': 'Seeding',
'allocating': 'Allocating',
- 'checking_resume_data': 'Checking'
+ 'checking_resume_data': 'Checking',
}
@@ -114,7 +114,7 @@ def convert_lt_files(files):
'index': index,
'path': file_path.replace('\\', '/'),
'size': _file.size,
- 'offset': _file.offset
+ 'offset': _file.offset,
})
return filelist
@@ -172,7 +172,7 @@ class TorrentOptions(dict):
'shared': 'shared',
'stop_at_ratio': 'stop_seed_at_ratio',
'stop_ratio': 'stop_seed_ratio',
- 'super_seeding': 'super_seeding'
+ 'super_seeding': 'super_seeding',
}
for opt_k, conf_k in options_conf_map.items():
self[opt_k] = config[conf_k]
@@ -639,8 +639,10 @@ class Torrent(object):
component.get('EventManager').emit(TorrentStateChangedEvent(self.torrent_id, self.state))
if log.isEnabledFor(logging.DEBUG):
- log.debug('State from lt was: %s | Session is paused: %s\nTorrent state set from "%s" to "%s" (%s)',
- 'error' if status_error else status.state, session_paused, old_state, self.state, self.torrent_id)
+ log.debug(
+ 'State from lt was: %s | Session is paused: %s\nTorrent state set from "%s" to "%s" (%s)',
+ 'error' if status_error else status.state, session_paused, old_state, self.state, self.torrent_id,
+ )
if self.forced_error:
log.debug('Torrent Error state message: %s', self.forced_error.error_message)
@@ -699,8 +701,10 @@ class Torrent(object):
eta = 0
if self.is_finished and self.options['stop_at_ratio'] and status.upload_payload_rate:
# We're a seed, so calculate the time to the 'stop_share_ratio'
- eta = ((status.all_time_download * self.options['stop_ratio']) -
- status.all_time_upload) // status.upload_payload_rate
+ eta = (
+ (status.all_time_download * self.options['stop_ratio']) -
+ status.all_time_upload
+ ) // status.upload_payload_rate
elif status.download_payload_rate:
left = status.total_wanted - status.total_wanted_done
if left > 0:
@@ -825,8 +829,10 @@ class Torrent(object):
"""
if not self.has_metadata:
return []
- return [progress / _file.size if _file.size else 0.0 for progress, _file in
- zip(self.handle.file_progress(), self.torrent_info.files())]
+ return [
+ progress / _file.size if _file.size else 0.0 for progress, _file in
+ zip(self.handle.file_progress(), self.torrent_info.files())
+ ]
def get_tracker_host(self):
"""Get the hostname of the currently connected tracker.
@@ -1019,7 +1025,8 @@ class Torrent(object):
'save_path': lambda: self.options['download_location'], # Deprecated: Use download_location
'download_location': lambda: self.options['download_location'],
'seeds_peers_ratio': lambda: -1.0 if self.status.num_incomplete == 0 else ( # Use -1.0 to signify infinity
- self.status.num_complete / self.status.num_incomplete),
+ self.status.num_complete / self.status.num_incomplete
+ ),
'seed_rank': lambda: self.status.seed_rank,
'state': lambda: self.state,
'stop_at_ratio': lambda: self.options['stop_at_ratio'],
@@ -1061,7 +1068,7 @@ class Torrent(object):
'super_seeding': lambda: self.status.super_seeding,
'time_since_download': lambda: self.status.time_since_download,
'time_since_upload': lambda: self.status.time_since_upload,
- 'time_since_transfer': self.get_time_since_transfer
+ 'time_since_transfer': self.get_time_since_transfer,
}
def pause(self):
@@ -1147,9 +1154,11 @@ class Torrent(object):
try:
os.makedirs(dest)
except OSError as ex:
- log.error('Could not move storage for torrent %s since %s does '
- 'not exist and could not create the directory: %s',
- self.torrent_id, dest, ex)
+ log.error(
+ 'Could not move storage for torrent %s since %s does '
+ 'not exist and could not create the directory: %s',
+ self.torrent_id, dest, ex,
+ )
return False
try:
@@ -1183,7 +1192,8 @@ class Torrent(object):
# Don't generate fastresume data if torrent is in a Deluge Error state.
if self.forced_error:
component.get('TorrentManager').waiting_on_resume_data[self.torrent_id].errback(
- UserWarning('Skipped creating resume_data while in Error state'))
+ UserWarning('Skipped creating resume_data while in Error state'),
+ )
else:
self.handle.save_resume_data(flags)
@@ -1315,7 +1325,7 @@ class Torrent(object):
if _file['path'].startswith(folder):
# Keep track of filerenames we're waiting on
wait_on_folder[_file['index']] = Deferred().addBoth(
- on_file_rename_complete, wait_on_folder, _file['index']
+ on_file_rename_complete, wait_on_folder, _file['index'],
)
new_path = _file['path'].replace(folder, new_folder, 1)
try:
diff --git a/deluge/core/torrentmanager.py b/deluge/core/torrentmanager.py
index 9739ad556..2004dd5c8 100644
--- a/deluge/core/torrentmanager.py
+++ b/deluge/core/torrentmanager.py
@@ -38,7 +38,8 @@ LT_DEFAULT_ADD_TORRENT_FLAGS = (
lt.add_torrent_params_flags_t.flag_paused |
lt.add_torrent_params_flags_t.flag_auto_managed |
lt.add_torrent_params_flags_t.flag_update_subscribe |
- lt.add_torrent_params_flags_t.flag_apply_ip_filter)
+ lt.add_torrent_params_flags_t.flag_apply_ip_filter
+)
class TorrentState: # pylint: disable=old-style-class
@@ -48,33 +49,35 @@ class TorrentState: # pylint: disable=old-style-class
This must be old style class to avoid breaking torrent.state file.
"""
- def __init__(self,
- torrent_id=None,
- filename=None,
- trackers=None,
- storage_mode='sparse',
- paused=False,
- save_path=None,
- max_connections=-1,
- max_upload_slots=-1,
- max_upload_speed=-1.0,
- max_download_speed=-1.0,
- prioritize_first_last=False,
- sequential_download=False,
- file_priorities=None,
- queue=None,
- auto_managed=True,
- is_finished=False,
- stop_ratio=2.00,
- stop_at_ratio=False,
- remove_at_ratio=False,
- move_completed=False,
- move_completed_path=None,
- magnet=None,
- owner=None,
- shared=False,
- super_seeding=False,
- name=None):
+ def __init__(
+ self,
+ torrent_id=None,
+ filename=None,
+ trackers=None,
+ storage_mode='sparse',
+ paused=False,
+ save_path=None,
+ max_connections=-1,
+ max_upload_slots=-1,
+ max_upload_speed=-1.0,
+ max_download_speed=-1.0,
+ prioritize_first_last=False,
+ sequential_download=False,
+ file_priorities=None,
+ queue=None,
+ auto_managed=True,
+ is_finished=False,
+ stop_ratio=2.00,
+ stop_at_ratio=False,
+ remove_at_ratio=False,
+ move_completed=False,
+ move_completed_path=None,
+ magnet=None,
+ owner=None,
+ shared=False,
+ super_seeding=False,
+ name=None,
+ ):
# Build the class atrribute list from args
for key, value in locals().items():
if key == 'self':
@@ -113,8 +116,10 @@ class TorrentManager(component.Component):
"""
def __init__(self):
- component.Component.__init__(self, 'TorrentManager', interval=5,
- depend=['CorePluginManager', 'AlertManager'])
+ component.Component.__init__(
+ self, 'TorrentManager', interval=5,
+ depend=['CorePluginManager', 'AlertManager'],
+ )
log.debug('TorrentManager init...')
# Set the libtorrent session
self.session = component.get('Core').session
@@ -154,8 +159,10 @@ class TorrentManager(component.Component):
self.prev_saved_state = None
# Register set functions
- set_config_keys = ['max_connections_per_torrent', 'max_upload_slots_per_torrent',
- 'max_upload_speed_per_torrent', 'max_download_speed_per_torrent']
+ set_config_keys = [
+ 'max_connections_per_torrent', 'max_upload_slots_per_torrent',
+ 'max_upload_speed_per_torrent', 'max_download_speed_per_torrent',
+ ]
for config_key in set_config_keys:
on_set_func = getattr(self, ''.join(['on_set_', config_key]))
@@ -170,7 +177,7 @@ class TorrentManager(component.Component):
'file_renamed_alert', 'file_error_alert', 'file_completed_alert',
'storage_moved_alert', 'storage_moved_failed_alert', 'state_update_alert',
'state_changed_alert', 'save_resume_data_alert', 'save_resume_data_failed_alert',
- 'fastresume_rejected_alert'
+ 'fastresume_rejected_alert',
]
for alert_handle in alert_handles:
@@ -230,7 +237,8 @@ class TorrentManager(component.Component):
for torrent_id, torrent in self.torrents.items():
# XXX: Should the state check be those that _can_ be stopped at ratio
if torrent.options['stop_at_ratio'] and torrent.state not in (
- 'Checking', 'Allocating', 'Paused', 'Queued'):
+ 'Checking', 'Allocating', 'Paused', 'Queued',
+ ):
# If the global setting is set, but the per-torrent isn't...
# Just skip to the next torrent.
# This is so that a user can turn-off the stop at ratio option on a per-torrent basis
@@ -308,7 +316,7 @@ class TorrentManager(component.Component):
return options
def _build_torrent_params(
- self, torrent_info=None, magnet=None, options=None, resume_data=None
+ self, torrent_info=None, magnet=None, options=None, resume_data=None,
):
"""Create the add_torrent_params dict for adding torrent to libtorrent."""
add_torrent_params = {}
@@ -361,10 +369,14 @@ class TorrentManager(component.Component):
add_torrent_params['resume_data'] = resume_data
# Set flags: enable duplicate_is_error & override_resume_data, disable auto_managed.
- add_torrent_params['flags'] = ((LT_DEFAULT_ADD_TORRENT_FLAGS |
- lt.add_torrent_params_flags_t.flag_duplicate_is_error |
- lt.add_torrent_params_flags_t.flag_override_resume_data) ^
- lt.add_torrent_params_flags_t.flag_auto_managed)
+ add_torrent_params['flags'] = (
+ (
+ LT_DEFAULT_ADD_TORRENT_FLAGS |
+ lt.add_torrent_params_flags_t.flag_duplicate_is_error |
+ lt.add_torrent_params_flags_t.flag_override_resume_data
+ ) ^
+ lt.add_torrent_params_flags_t.flag_auto_managed
+ )
if options['seed_mode']:
add_torrent_params['flags'] |= lt.add_torrent_params_flags_t.flag_seed_mode
@@ -411,7 +423,8 @@ class TorrentManager(component.Component):
options = self._build_torrent_options(options)
__, add_torrent_params = self._build_torrent_params(
- torrent_info, magnet, options, resume_data)
+ torrent_info, magnet, options, resume_data,
+ )
# We need to pause the AlertManager momentarily to prevent alerts
# for this torrent being generated before a Torrent object is created.
@@ -426,7 +439,8 @@ class TorrentManager(component.Component):
raise AddTorrentError('Unable to add torrent to session: %s' % ex)
torrent = self._add_torrent_obj(
- handle, options, state, filename, magnet, resume_data, filedump, save_state)
+ handle, options, state, filename, magnet, resume_data, filedump, save_state,
+ )
return torrent.torrent_id
def add_async(
@@ -470,7 +484,8 @@ class TorrentManager(component.Component):
options = self._build_torrent_options(options)
torrent_id, add_torrent_params = self._build_torrent_params(
- torrent_info, magnet, options, resume_data)
+ torrent_info, magnet, options, resume_data,
+ )
d = Deferred()
self.torrents_loading[torrent_id] = (d, options, state, filename, magnet, resume_data, filedump, save_state)
@@ -509,10 +524,12 @@ class TorrentManager(component.Component):
log.debug('Torrent added: %s', str(handle.info_hash()))
if log.isEnabledFor(logging.INFO):
name_and_owner = torrent.get_status(['name', 'owner'])
- log.info('Torrent %s from user "%s" %s',
- name_and_owner['name'],
- name_and_owner['owner'],
- from_state and 'loaded' or 'added')
+ log.info(
+ 'Torrent %s from user "%s" %s',
+ name_and_owner['name'],
+ name_and_owner['owner'],
+ from_state and 'loaded' or 'added',
+ )
# Write the .torrent file to the state directory.
if filedump:
@@ -525,10 +542,11 @@ class TorrentManager(component.Component):
return torrent
def add_async_callback(
- self, handle, d, options, state, filename, magnet, resume_data, filedump, save_state
+ self, handle, d, options, state, filename, magnet, resume_data, filedump, save_state,
):
torrent = self._add_torrent_obj(
- handle, options, state, filename, magnet, resume_data, filedump, save_state)
+ handle, options, state, filename, magnet, resume_data, filedump, save_state,
+ )
d.callback(torrent.torrent_id)
@@ -670,7 +688,8 @@ class TorrentManager(component.Component):
magnet = t_state.magnet
torrent_info = self.get_torrent_info_from_file(
- os.path.join(self.state_dir, t_state.torrent_id + '.torrent'))
+ os.path.join(self.state_dir, t_state.torrent_id + '.torrent'),
+ )
if torrent_info:
magnet = None
@@ -740,7 +759,7 @@ class TorrentManager(component.Component):
torrent.options['owner'],
torrent.options['shared'],
torrent.options['super_seeding'],
- torrent.options['name']
+ torrent.options['name'],
)
state.torrents.append(torrent_state)
return state
@@ -1058,9 +1077,11 @@ class TorrentManager(component.Component):
if log.isEnabledFor(logging.DEBUG):
log.debug('Finished %s ', torrent_id)
- log.debug('Torrent settings: is_finished: %s, total_download: %s, move_completed: %s, move_path: %s',
- torrent.is_finished, total_download, torrent.options['move_completed'],
- torrent.options['move_completed_path'])
+ log.debug(
+ 'Torrent settings: is_finished: %s, total_download: %s, move_completed: %s, move_path: %s',
+ torrent.is_finished, total_download, torrent.options['move_completed'],
+ torrent.options['move_completed_path'],
+ )
torrent.update_state()
if not torrent.is_finished and total_download:
diff --git a/deluge/decorators.py b/deluge/decorators.py
index 856c4e894..bd0ca02d9 100644
--- a/deluge/decorators.py
+++ b/deluge/decorators.py
@@ -129,8 +129,10 @@ def deprecated(func):
@wraps(func)
def depr_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # Turn off filter
- warnings.warn('Call to deprecated function {}.'.format(func.__name__),
- category=DeprecationWarning, stacklevel=2)
+ warnings.warn(
+ 'Call to deprecated function {}.'.format(func.__name__),
+ category=DeprecationWarning, stacklevel=2,
+ )
warnings.simplefilter('default', DeprecationWarning) # Reset filter
return func(*args, **kwargs)
diff --git a/deluge/error.py b/deluge/error.py
index bbee4dae2..526168d46 100644
--- a/deluge/error.py
+++ b/deluge/error.py
@@ -63,17 +63,22 @@ class IncompatibleClient(_ClientSideRecreateError):
def __init__(self, daemon_version):
self.daemon_version = daemon_version
- msg = 'Your deluge client is not compatible with the daemon. '\
- 'Please upgrade your client to %(daemon_version)s' % \
- dict(daemon_version=self.daemon_version)
+ msg = (
+ 'Your deluge client is not compatible with the daemon. '
+ 'Please upgrade your client to %(daemon_version)s'
+ ) % {'daemon_version': self.daemon_version}
super(IncompatibleClient, self).__init__(message=msg)
class NotAuthorizedError(_ClientSideRecreateError):
def __init__(self, current_level, required_level):
- msg = 'Auth level too low: %(current_level)s < %(required_level)s' % \
- dict(current_level=current_level, required_level=required_level)
+ msg = (
+ 'Auth level too low: %(current_level)s < %(required_level)s'
+ ) % {
+ 'current_level': current_level,
+ 'required_level': required_level,
+ }
super(NotAuthorizedError, self).__init__(message=msg)
self.current_level = current_level
self.required_level = required_level
diff --git a/deluge/httpdownloader.py b/deluge/httpdownloader.py
index d42d27570..312249020 100644
--- a/deluge/httpdownloader.py
+++ b/deluge/httpdownloader.py
@@ -34,8 +34,10 @@ class HTTPDownloader(client.HTTPDownloader):
"""
Factory class for downloading files and keeping track of progress.
"""
- def __init__(self, url, filename, part_callback=None, headers=None,
- force_filename=False, allow_compression=True):
+ def __init__(
+ self, url, filename, part_callback=None, headers=None,
+ force_filename=False, allow_compression=True,
+ ):
"""
:param url: the url to download from
:type url: string
@@ -227,8 +229,10 @@ def _download_file(url, filename, callback=None, headers=None, force_filename=Fa
return factory.deferred
-def download_file(url, filename, callback=None, headers=None, force_filename=False,
- allow_compression=True, handle_redirects=True):
+def download_file(
+ url, filename, callback=None, headers=None, force_filename=False,
+ allow_compression=True, handle_redirects=True,
+):
"""
Downloads a file from a specific URL and returns a Deferred. A callback
function can be specified to be called as parts are received.
@@ -259,18 +263,24 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
def on_download_fail(failure):
if failure.check(PageRedirect) and handle_redirects:
new_url = urljoin(url, failure.getErrorMessage().split(' to ')[1])
- result = _download_file(new_url, filename, callback=callback, headers=headers,
- force_filename=force_filename,
- allow_compression=allow_compression)
+ result = _download_file(
+ new_url, filename, callback=callback, headers=headers,
+ force_filename=force_filename,
+ allow_compression=allow_compression,
+ )
result.addCallbacks(on_download_success, on_download_fail)
else:
# Log the failure and pass to the caller
- log.warning('Error occurred downloading file from "%s": %s',
- url, failure.getErrorMessage())
+ log.warning(
+ 'Error occurred downloading file from "%s": %s',
+ url, failure.getErrorMessage(),
+ )
result = failure
return result
- d = _download_file(url, filename, callback=callback, headers=headers,
- force_filename=force_filename, allow_compression=allow_compression)
+ d = _download_file(
+ url, filename, callback=callback, headers=headers,
+ force_filename=force_filename, allow_compression=allow_compression,
+ )
d.addCallbacks(on_download_success, on_download_fail)
return d
diff --git a/deluge/log.py b/deluge/log.py
index bbf57f73f..fe61ff3da 100644
--- a/deluge/log.py
+++ b/deluge/log.py
@@ -45,7 +45,7 @@ class Logging(LoggingLoggerClass):
for handler in logging.getLogger().handlers:
handler.setFormatter(logging.Formatter(
DEFAULT_LOGGING_FORMAT % MAX_LOGGER_NAME_LENGTH,
- datefmt='%H:%M:%S'
+ datefmt='%H:%M:%S',
))
@defer.inlineCallbacks
@@ -88,8 +88,10 @@ class Logging(LoggingLoggerClass):
while hasattr(f, 'f_code'):
co = f.f_code
filename = os.path.normcase(co.co_filename)
- if filename in (__file__.replace('.pyc', '.py'),
- defer.__file__.replace('.pyc', '.py')):
+ if filename in (
+ __file__.replace('.pyc', '.py'),
+ defer.__file__.replace('.pyc', '.py'),
+ ):
f = f.f_back
continue
rv = (filename, f.f_lineno, co.co_name)
@@ -105,12 +107,14 @@ levels = {
'none': logging.CRITICAL,
'debug': logging.DEBUG,
'trace': 5,
- 'garbage': 1
+ 'garbage': 1,
}
-def setup_logger(level='error', filename=None, filemode='w', logrotate=None,
- output_stream=sys.stdout, twisted_observer=True):
+def setup_logger(
+ level='error', filename=None, filemode='w', logrotate=None,
+ output_stream=sys.stdout, twisted_observer=True,
+):
"""
Sets up the basic logger and if `:param:filename` is set, then it will log
to that file instead of stdout.
@@ -137,7 +141,7 @@ def setup_logger(level='error', filename=None, filemode='w', logrotate=None,
if filename and logrotate:
handler = logging.handlers.RotatingFileHandler(
filename, maxBytes=logrotate,
- backupCount=5, encoding='utf-8'
+ backupCount=5, encoding='utf-8',
)
elif filename and filemode == 'w':
handler_cls = logging.FileHandler
@@ -151,7 +155,7 @@ def setup_logger(level='error', filename=None, filemode='w', logrotate=None,
formatter = logging.Formatter(
DEFAULT_LOGGING_FORMAT % MAX_LOGGER_NAME_LENGTH,
- datefmt='%H:%M:%S'
+ datefmt='%H:%M:%S',
)
handler.setFormatter(formatter)
@@ -214,8 +218,10 @@ def tweak_logging_levels():
if not os.path.isfile(logging_config_file):
return
log = logging.getLogger(__name__)
- log.warn('logging.conf found! tweaking logging levels from %s',
- logging_config_file)
+ log.warn(
+ 'logging.conf found! tweaking logging levels from %s',
+ logging_config_file,
+ )
with open(logging_config_file, 'r') as _file:
for line in _file:
if line.strip().startswith('#'):
@@ -249,9 +255,11 @@ def get_plugin_logger(logger_name):
caller_module = inspect.getmodule(module_stack[0])
# In some weird cases caller_module might be None, try to continue
caller_module_name = getattr(caller_module, '__name__', '')
- warnings.warn_explicit(DEPRECATION_WARNING, DeprecationWarning,
- module_stack[1], module_stack[2],
- caller_module_name)
+ warnings.warn_explicit(
+ DEPRECATION_WARNING, DeprecationWarning,
+ module_stack[1], module_stack[2],
+ caller_module_name,
+ )
if 'deluge.plugins.' in logger_name:
return logging.getLogger(logger_name)
@@ -291,16 +299,20 @@ class _BackwardsCompatibleLOG(object):
caller_module = inspect.getmodule(module_stack[0])
# In some weird cases caller_module might be None, try to continue
caller_module_name = getattr(caller_module, '__name__', '')
- warnings.warn_explicit(DEPRECATION_WARNING, DeprecationWarning,
- module_stack[1], module_stack[2],
- caller_module_name)
+ warnings.warn_explicit(
+ DEPRECATION_WARNING, DeprecationWarning,
+ module_stack[1], module_stack[2],
+ caller_module_name,
+ )
if caller_module:
for member in stack:
module = inspect.getmodule(member[0])
if not module:
continue
- if module.__name__ in ('deluge.plugins.pluginbase',
- 'deluge.plugins.init'):
+ if module.__name__ in (
+ 'deluge.plugins.pluginbase',
+ 'deluge.plugins.init',
+ ):
logger_name += '.plugin.%s' % caller_module_name
# Monkey Patch The Plugin Module
caller_module.log = logging.getLogger(logger_name)
@@ -308,7 +320,7 @@ class _BackwardsCompatibleLOG(object):
else:
logging.getLogger(logger_name).warning(
"Unable to monkey-patch the calling module's `log` attribute! "
- 'You should really update and rebuild your plugins...'
+ 'You should really update and rebuild your plugins...',
)
return getattr(logging.getLogger(logger_name), name)
diff --git a/deluge/maketorrent.py b/deluge/maketorrent.py
index 82599ac0b..2e91ca723 100644
--- a/deluge/maketorrent.py
+++ b/deluge/maketorrent.py
@@ -68,7 +68,7 @@ class TorrentMetadata(object):
raise InvalidPath('Need to set a data_path!')
torrent = {
- 'info': {}
+ 'info': {},
}
if self.comment:
diff --git a/deluge/metafile.py b/deluge/metafile.py
index 8784fe357..29c020e9f 100644
--- a/deluge/metafile.py
+++ b/deluge/metafile.py
@@ -50,13 +50,15 @@ class RemoteFileProgress(object):
def __call__(self, piece_count, num_pieces):
component.get('RPCServer').emit_event_for_session_id(
- self.session_id, CreateTorrentProgressEvent(piece_count, num_pieces)
+ self.session_id, CreateTorrentProgressEvent(piece_count, num_pieces),
)
-def make_meta_file(path, url, piece_length, progress=None, title=None, comment=None,
- safe=None, content_type=None, target=None, webseeds=None, name=None,
- private=False, created_by=None, trackers=None):
+def make_meta_file(
+ path, url, piece_length, progress=None, title=None, comment=None,
+ safe=None, content_type=None, target=None, webseeds=None, name=None,
+ private=False, created_by=None, trackers=None,
+):
data = {'creation date': int(gmtime())}
if url:
data['announce'] = url.strip()
@@ -147,8 +149,10 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
size = os.path.getsize(f)
p2 = [n.encode('utf8') for n in p]
if content_type:
- fs.append({'length': size, 'path': p2,
- 'content_type': content_type}) # HEREDAVE. bad for batch!
+ fs.append({
+ 'length': size, 'path': p2,
+ 'content_type': content_type,
+ }) # HEREDAVE. bad for batch!
else:
fs.append({'length': size, 'path': p2})
with open(f, 'rb') as file_:
@@ -173,11 +177,13 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
if not name:
name = os.path.split(path)[1]
- return {'pieces': b''.join(pieces),
- 'piece length': piece_length,
- 'files': fs,
- 'name': name.encode('utf8'),
- 'private': private}
+ return {
+ 'pieces': b''.join(pieces),
+ 'piece length': piece_length,
+ 'files': fs,
+ 'name': name.encode('utf8'),
+ 'private': private,
+ }
else:
size = os.path.getsize(path)
if size >= piece_length:
@@ -198,15 +204,19 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
progress(piece_count, num_pieces)
name = os.path.split(path)[1].encode('utf8')
if content_type is not None:
- return {'pieces': b''.join(pieces),
- 'piece length': piece_length, 'length': size,
- 'name': name,
- 'content_type': content_type,
- 'private': private}
- return {'pieces': b''.join(pieces),
+ return {
+ 'pieces': b''.join(pieces),
'piece length': piece_length, 'length': size,
'name': name,
- 'private': private}
+ 'content_type': content_type,
+ 'private': private,
+ }
+ return {
+ 'pieces': b''.join(pieces),
+ 'piece length': piece_length, 'length': size,
+ 'name': name,
+ 'private': private,
+ }
def subfiles(d):
diff --git a/deluge/pluginmanagerbase.py b/deluge/pluginmanagerbase.py
index 8d249100a..439ebf5ed 100644
--- a/deluge/pluginmanagerbase.py
+++ b/deluge/pluginmanagerbase.py
@@ -108,10 +108,12 @@ class PluginManagerBase(object):
self.available_plugins = []
for name in self.pkg_env:
- log.debug('Found plugin: %s %s at %s',
- self.pkg_env[name][0].project_name,
- self.pkg_env[name][0].version,
- self.pkg_env[name][0].location)
+ log.debug(
+ 'Found plugin: %s %s at %s',
+ self.pkg_env[name][0].project_name,
+ self.pkg_env[name][0].version,
+ self.pkg_env[name][0].location,
+ )
self.available_plugins.append(self.pkg_env[name][0].project_name)
def enable_plugin(self, plugin_name):
@@ -162,7 +164,7 @@ class PluginManagerBase(object):
warnings.warn_explicit(
DEPRECATION_WARNING % name,
DeprecationWarning,
- instance.__module__, 0
+ instance.__module__, 0,
)
if self._component_state == 'Started':
def on_enabled(result, instance):
@@ -179,8 +181,10 @@ class PluginManagerBase(object):
return True
def on_started_error(result, instance):
- log.error('Failed to start plugin: %s\n%s', plugin_name,
- result.getTraceback(elideFrameworkCode=1, detail='brief'))
+ log.error(
+ 'Failed to start plugin: %s\n%s', plugin_name,
+ result.getTraceback(elideFrameworkCode=1, detail='brief'),
+ )
self.plugins[plugin_name.replace('-', ' ')] = instance
self.disable_plugin(plugin_name)
return False
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
index 43dc48eeb..81c33de4b 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
@@ -37,7 +37,7 @@ log = logging.getLogger(__name__)
DEFAULT_PREFS = {
'watchdirs': {},
- 'next_id': 1
+ 'next_id': 1,
}
@@ -64,7 +64,7 @@ OPTIONS_AVAILABLE = { # option: builtin
'add_paused': True,
'queue_to_top': False,
'owner': True,
- 'seed_mode': True
+ 'seed_mode': True,
}
MAX_NUM_ATTEMPTS = 10
@@ -91,7 +91,7 @@ class Core(CorePluginBase):
self.watchdirs = self.config['watchdirs']
component.get('EventManager').register_event_handler(
- 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed
+ 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed,
)
# Dict of Filename:Attempts
@@ -109,7 +109,7 @@ class Core(CorePluginBase):
def disable(self):
# disable all running looping calls
component.get('EventManager').deregister_event_handler(
- 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed
+ 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed,
)
for loopingcall in self.update_timers.values():
loopingcall.stop()
@@ -124,12 +124,12 @@ class Core(CorePluginBase):
watchdir_id = str(watchdir_id)
options = self._make_unicode(options)
check_input(
- watchdir_id in self.watchdirs, _('Watch folder does not exist.')
+ watchdir_id in self.watchdirs, _('Watch folder does not exist.'),
)
if 'path' in options:
options['abspath'] = os.path.abspath(options['path'])
check_input(
- os.path.isdir(options['abspath']), _('Path does not exist.')
+ os.path.isdir(options['abspath']), _('Path does not exist.'),
)
for w_id, w in self.watchdirs.items():
if options['abspath'] == w['abspath'] and watchdir_id != w_id:
@@ -210,8 +210,10 @@ class Core(CorePluginBase):
watchdir = self.watchdirs[watchdir_id]
if not watchdir['enabled']:
# We shouldn't be updating because this watchdir is not enabled
- log.debug('Watchdir id %s is not enabled. Disabling it.',
- watchdir_id)
+ log.debug(
+ 'Watchdir id %s is not enabled. Disabling it.',
+ watchdir_id,
+ )
self.disable_watchdir(watchdir_id)
return
@@ -271,8 +273,10 @@ class Core(CorePluginBase):
if filename in self.invalid_torrents:
self.invalid_torrents[filename] += 1
if self.invalid_torrents[filename] >= MAX_NUM_ATTEMPTS:
- log.warning('Maximum attempts reached while trying to add the '
- 'torrent file with the path %s', filepath)
+ log.warning(
+ 'Maximum attempts reached while trying to add the '
+ 'torrent file with the path %s', filepath,
+ )
os.rename(filepath, filepath + '.invalid')
del self.invalid_torrents[filename]
else:
@@ -305,8 +309,10 @@ class Core(CorePluginBase):
elif watchdir.get('copy_torrent_toggle'):
copy_torrent_path = watchdir['copy_torrent']
copy_torrent_file = os.path.join(copy_torrent_path, filename)
- log.debug('Moving added torrent file "%s" to "%s"',
- os.path.basename(filepath), copy_torrent_path)
+ log.debug(
+ 'Moving added torrent file "%s" to "%s"',
+ os.path.basename(filepath), copy_torrent_path,
+ )
shutil.move(filepath, copy_torrent_file)
else:
os.remove(filepath)
@@ -322,7 +328,8 @@ class Core(CorePluginBase):
d = component.get('Core').add_torrent_magnet(filedump.strip(), options)
else:
d = component.get('Core').add_torrent_file_async(
- filename, base64.encodestring(filedump), options)
+ filename, base64.encodestring(filedump), options,
+ )
d.addCallback(on_torrent_added, filename, filepath)
d.addErrback(fail_torrent_add, filepath, magnet)
except AddTorrentError as ex:
@@ -331,8 +338,10 @@ class Core(CorePluginBase):
def on_update_watchdir_error(self, failure, watchdir_id):
"""Disables any watch folders with un-handled exceptions."""
self.disable_watchdir(watchdir_id)
- log.error('Disabling "%s", error during update: %s',
- self.watchdirs[watchdir_id]['path'], failure)
+ log.error(
+ 'Disabling "%s", error during update: %s',
+ self.watchdirs[watchdir_id]['path'], failure,
+ )
@export
def enable_watchdir(self, watchdir_id):
@@ -341,7 +350,7 @@ class Core(CorePluginBase):
if w_id not in self.update_timers or not self.update_timers[w_id].running:
self.update_timers[w_id] = LoopingCall(self.update_watchdir, w_id)
self.update_timers[w_id].start(5).addErrback(
- self.on_update_watchdir_error, w_id
+ self.on_update_watchdir_error, w_id,
)
# Update the config
if not self.watchdirs[w_id]['enabled']:
@@ -383,8 +392,10 @@ class Core(CorePluginBase):
session_user = rpcserver.get_session_user()
session_auth_level = rpcserver.get_session_auth_level()
if session_auth_level == AUTH_LEVEL_ADMIN:
- log.debug('Current logged in user %s is an ADMIN, send all '
- 'watchdirs', session_user)
+ log.debug(
+ 'Current logged in user %s is an ADMIN, send all '
+ 'watchdirs', session_user,
+ )
return self.watchdirs
watchdirs = {}
@@ -392,8 +403,10 @@ class Core(CorePluginBase):
if watchdir.get('owner', 'localclient') == session_user:
watchdirs[watchdir_id] = watchdir
- log.debug('Current logged in user %s is not an ADMIN, send only '
- 'their watchdirs: %s', session_user, list(watchdirs))
+ log.debug(
+ 'Current logged in user %s is not an ADMIN, send only '
+ 'their watchdirs: %s', session_user, list(watchdirs),
+ )
return watchdirs
def _make_unicode(self, options):
@@ -414,7 +427,7 @@ class Core(CorePluginBase):
check_input(os.path.isdir(abswatchdir), _('Path does not exist.'))
check_input(
os.access(abswatchdir, os.R_OK | os.W_OK),
- 'You must have read and write access to watch folder.'
+ 'You must have read and write access to watch folder.',
)
if abswatchdir in [wd['abspath'] for wd in self.watchdirs.values()]:
raise Exception('Path is already being watched.')
@@ -449,9 +462,11 @@ class Core(CorePluginBase):
try:
torrent = component.get('TorrentManager')[torrent_id]
except KeyError:
- log.warning('Unable to remove torrent file for torrent id %s. It'
- 'was already deleted from the TorrentManager',
- torrent_id)
+ log.warning(
+ 'Unable to remove torrent file for torrent id %s. It'
+ 'was already deleted from the TorrentManager',
+ torrent_id,
+ )
return
torrent_fname = torrent.filename
for watchdir in self.watchdirs.values():
@@ -466,9 +481,13 @@ class Core(CorePluginBase):
if os.path.isfile(torrent_fname_path):
try:
os.remove(torrent_fname_path)
- log.info('Removed torrent file "%s" from "%s"',
- torrent_fname, copy_torrent_path)
+ log.info(
+ 'Removed torrent file "%s" from "%s"',
+ torrent_fname, copy_torrent_path,
+ )
break
except OSError as ex:
- log.info('Failed to removed torrent file "%s" from "%s": %s',
- torrent_fname, copy_torrent_path, ex)
+ log.info(
+ 'Failed to removed torrent file "%s" from "%s": %s',
+ torrent_fname, copy_torrent_path, ex,
+ )
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
index 27e34449b..083a1bcb2 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
@@ -37,8 +37,10 @@ class IncompatibleOption(Exception):
class OptionsDialog(object):
spin_ids = ['max_download_speed', 'max_upload_speed', 'stop_ratio']
spin_int_ids = ['max_upload_slots', 'max_connections']
- chk_ids = ['stop_at_ratio', 'remove_at_ratio', 'move_completed',
- 'add_paused', 'auto_managed', 'queue_to_top']
+ chk_ids = [
+ 'stop_at_ratio', 'remove_at_ratio', 'move_completed',
+ 'add_paused', 'auto_managed', 'queue_to_top',
+ ]
def __init__(self):
self.accounts = gtk.ListStore(str)
@@ -55,7 +57,7 @@ class OptionsDialog(object):
'on_opts_apply': self.on_apply,
'on_opts_cancel': self.on_cancel,
'on_options_dialog_close': self.on_cancel,
- 'on_toggle_toggled': self.on_toggle_toggled
+ 'on_toggle_toggled': self.on_toggle_toggled,
})
self.dialog = self.builder.get_object('options_dialog')
self.dialog.set_transient_for(component.get('Preferences').pref_dialog)
@@ -77,22 +79,22 @@ class OptionsDialog(object):
def load_options(self, options):
self.builder.get_object('enabled').set_active(options.get('enabled', True))
self.builder.get_object('append_extension_toggle').set_active(
- options.get('append_extension_toggle', False)
+ options.get('append_extension_toggle', False),
)
self.builder.get_object('append_extension').set_text(
- options.get('append_extension', '.added')
+ options.get('append_extension', '.added'),
)
self.builder.get_object('download_location_toggle').set_active(
- options.get('download_location_toggle', False)
+ options.get('download_location_toggle', False),
)
self.builder.get_object('copy_torrent_toggle').set_active(
- options.get('copy_torrent_toggle', False)
+ options.get('copy_torrent_toggle', False),
)
self.builder.get_object('delete_copy_torrent_toggle').set_active(
- options.get('delete_copy_torrent_toggle', False)
+ options.get('delete_copy_torrent_toggle', False),
)
self.builder.get_object('seed_mode').set_active(
- options.get('seed_mode', False)
+ options.get('seed_mode', False),
)
self.accounts.clear()
self.labels.clear()
@@ -120,17 +122,19 @@ class OptionsDialog(object):
self.builder.get_object('isnt_queue_to_top').set_active(True)
if not options.get('auto_managed', True):
self.builder.get_object('isnt_auto_managed').set_active(True)
- for field in ['move_completed_path', 'path', 'download_location',
- 'copy_torrent']:
+ for field in [
+ 'move_completed_path', 'path', 'download_location',
+ 'copy_torrent',
+ ]:
if client.is_localhost():
self.builder.get_object(field + '_chooser').set_current_folder(
- options.get(field, os.path.expanduser('~'))
+ options.get(field, os.path.expanduser('~')),
)
self.builder.get_object(field + '_chooser').show()
self.builder.get_object(field + '_entry').hide()
else:
self.builder.get_object(field + '_entry').set_text(
- options.get(field, '')
+ options.get(field, ''),
)
self.builder.get_object(field + '_entry').show()
self.builder.get_object(field + '_chooser').hide()
@@ -139,33 +143,33 @@ class OptionsDialog(object):
def on_core_config(config):
if client.is_localhost():
self.builder.get_object('download_location_chooser').set_current_folder(
- options.get('download_location', config['download_location'])
+ options.get('download_location', config['download_location']),
)
if options.get('move_completed_toggle', config['move_completed']):
self.builder.get_object('move_completed_toggle').set_active(True)
self.builder.get_object('move_completed_path_chooser').set_current_folder(
- options.get('move_completed_path', config['move_completed_path'])
+ options.get('move_completed_path', config['move_completed_path']),
)
if options.get('copy_torrent_toggle', config['copy_torrent_file']):
self.builder.get_object('copy_torrent_toggle').set_active(True)
self.builder.get_object('copy_torrent_chooser').set_current_folder(
- options.get('copy_torrent', config['torrentfiles_location'])
+ options.get('copy_torrent', config['torrentfiles_location']),
)
else:
self.builder.get_object('download_location_entry').set_text(
- options.get('download_location', config['download_location'])
+ options.get('download_location', config['download_location']),
)
if options.get('move_completed_toggle', config['move_completed']):
self.builder.get_object('move_completed_toggle').set_active(
- options.get('move_completed_toggle', False)
+ options.get('move_completed_toggle', False),
)
self.builder.get_object('move_completed_path_entry').set_text(
- options.get('move_completed_path', config['move_completed_path'])
+ options.get('move_completed_path', config['move_completed_path']),
)
if options.get('copy_torrent_toggle', config['copy_torrent_file']):
self.builder.get_object('copy_torrent_toggle').set_active(True)
self.builder.get_object('copy_torrent_entry').set_text(
- options.get('copy_torrent', config['torrentfiles_location'])
+ options.get('copy_torrent', config['torrentfiles_location']),
)
if options.get('delete_copy_torrent_toggle', config['del_copy_torrent_file']):
@@ -180,7 +184,7 @@ class OptionsDialog(object):
for account in accounts:
acc_iter = self.accounts.append()
self.accounts.set_value(
- acc_iter, 0, account['username']
+ acc_iter, 0, account['username'],
)
if account['username'] == owner:
selected_iter = acc_iter
@@ -215,7 +219,7 @@ class OptionsDialog(object):
client.core.get_enabled_plugins().addCallback(on_get_enabled_plugins)
if client.get_auth_level() == deluge.common.AUTH_LEVEL_ADMIN:
client.core.get_known_accounts().addCallback(
- on_accounts, options.get('owner', client.get_auth_user())
+ on_accounts, options.get('owner', client.get_auth_user()),
).addErrback(on_accounts_failure)
else:
acc_iter = self.accounts.append()
@@ -224,11 +228,13 @@ class OptionsDialog(object):
self.builder.get_object('OwnerCombobox').set_sensitive(False)
def set_sensitive(self):
- maintoggles = ['download_location', 'append_extension',
- 'move_completed', 'label', 'max_download_speed',
- 'max_upload_speed', 'max_connections',
- 'max_upload_slots', 'add_paused', 'auto_managed',
- 'stop_at_ratio', 'queue_to_top', 'copy_torrent']
+ maintoggles = [
+ 'download_location', 'append_extension',
+ 'move_completed', 'label', 'max_download_speed',
+ 'max_upload_speed', 'max_connections',
+ 'max_upload_slots', 'add_paused', 'auto_managed',
+ 'stop_at_ratio', 'queue_to_top', 'copy_torrent',
+ ]
for maintoggle in maintoggles:
self.on_toggle_toggled(self.builder.get_object(maintoggle + '_toggle'))
@@ -278,7 +284,7 @@ class OptionsDialog(object):
try:
options = self.generate_opts()
client.autoadd.set_options(
- str(self.watchdir_id), options
+ str(self.watchdir_id), options,
).addCallbacks(self.on_added, self.on_error_show)
except IncompatibleOption as ex:
dialogs.ErrorDialog(_('Incompatible Option'), str(ex), self.dialog).run()
@@ -308,28 +314,37 @@ class OptionsDialog(object):
if client.is_localhost():
options['path'] = self.builder.get_object('path_chooser').get_filename()
options['download_location'] = self.builder.get_object(
- 'download_location_chooser').get_filename()
+ 'download_location_chooser',
+ ).get_filename()
options['move_completed_path'] = self.builder.get_object(
- 'move_completed_path_chooser').get_filename()
+ 'move_completed_path_chooser',
+ ).get_filename()
options['copy_torrent'] = self.builder.get_object(
- 'copy_torrent_chooser').get_filename()
+ 'copy_torrent_chooser',
+ ).get_filename()
else:
options['path'] = self.builder.get_object('path_entry').get_text()
options['download_location'] = self.builder.get_object(
- 'download_location_entry').get_text()
+ 'download_location_entry',
+ ).get_text()
options['move_completed_path'] = self.builder.get_object(
- 'move_completed_path_entry').get_text()
+ 'move_completed_path_entry',
+ ).get_text()
options['copy_torrent'] = self.builder.get_object(
- 'copy_torrent_entry').get_text()
+ 'copy_torrent_entry',
+ ).get_text()
options['label'] = self.builder.get_object('label').child.get_text().lower()
options['append_extension'] = self.builder.get_object('append_extension').get_text()
options['owner'] = self.accounts[
- self.builder.get_object('OwnerCombobox').get_active()][0]
-
- for key in ['append_extension_toggle', 'download_location_toggle',
- 'label_toggle', 'copy_torrent_toggle',
- 'delete_copy_torrent_toggle', 'seed_mode']:
+ self.builder.get_object('OwnerCombobox').get_active()
+ ][0]
+
+ for key in [
+ 'append_extension_toggle', 'download_location_toggle',
+ 'label_toggle', 'copy_torrent_toggle',
+ 'delete_copy_torrent_toggle', 'seed_mode',
+ ]:
options[key] = self.builder.get_object(key).get_active()
for spin_id in self.spin_ids:
@@ -343,8 +358,10 @@ class OptionsDialog(object):
options[chk_id + '_toggle'] = self.builder.get_object(chk_id + '_toggle').get_active()
if options['copy_torrent_toggle'] and options['path'] == options['copy_torrent']:
- raise IncompatibleOption(_('"Watch Folder" directory and "Copy of .torrent'
- ' files to" directory cannot be the same!'))
+ raise IncompatibleOption(_(
+ '"Watch Folder" directory and "Copy of .torrent'
+ ' files to" directory cannot be the same!',
+ ))
return options
@@ -357,13 +374,13 @@ class GtkUI(GtkPluginBase):
self.opts_dialog = OptionsDialog()
component.get('PluginManager').register_hook(
- 'on_apply_prefs', self.on_apply_prefs
+ 'on_apply_prefs', self.on_apply_prefs,
)
component.get('PluginManager').register_hook(
- 'on_show_prefs', self.on_show_prefs
+ 'on_show_prefs', self.on_show_prefs,
)
client.register_event_handler(
- 'AutoaddOptionsChangedEvent', self.on_options_changed_event
+ 'AutoaddOptionsChangedEvent', self.on_options_changed_event,
)
self.watchdirs = {}
@@ -386,16 +403,16 @@ class GtkUI(GtkPluginBase):
sw.add(self.treeView)
sw.show_all()
component.get('Preferences').add_page(
- _('AutoAdd'), self.builder.get_object('prefs_box')
+ _('AutoAdd'), self.builder.get_object('prefs_box'),
)
def disable(self):
component.get('Preferences').remove_page(_('AutoAdd'))
component.get('PluginManager').deregister_hook(
- 'on_apply_prefs', self.on_apply_prefs
+ 'on_apply_prefs', self.on_apply_prefs,
)
component.get('PluginManager').deregister_hook(
- 'on_show_prefs', self.on_show_prefs
+ 'on_show_prefs', self.on_show_prefs,
)
def create_model(self):
@@ -403,14 +420,14 @@ class GtkUI(GtkPluginBase):
for watchdir_id, watchdir in self.watchdirs.items():
store.append([
watchdir_id, watchdir['enabled'],
- watchdir.get('owner', 'localclient'), watchdir['path']
+ watchdir.get('owner', 'localclient'), watchdir['path'],
])
return store
def create_columns(self, treeview):
renderer_toggle = gtk.CellRendererToggle()
column = gtk.TreeViewColumn(
- _('Active'), renderer_toggle, activatable=1, active=1
+ _('Active'), renderer_toggle, activatable=1, active=1,
)
column.set_sort_column_id(1)
treeview.append_column(column)
@@ -490,7 +507,7 @@ class GtkUI(GtkPluginBase):
for watchdir_id, watchdir in self.watchdirs.items():
self.store.append([
watchdir_id, watchdir['enabled'],
- watchdir.get('owner', 'localclient'), watchdir['path']
+ watchdir.get('owner', 'localclient'), watchdir['path'],
])
# Workaround for cached glade signal appearing when re-enabling plugin in same session
if self.builder.get_object('edit_button'):
diff --git a/deluge/plugins/AutoAdd/setup.py b/deluge/plugins/AutoAdd/setup.py
index 079c1bf76..77ca16267 100644
--- a/deluge/plugins/AutoAdd/setup.py
+++ b/deluge/plugins/AutoAdd/setup.py
@@ -45,5 +45,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
index f2b976c75..5a9d525a3 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
@@ -165,5 +165,5 @@ class IP(object):
def __repr__(self):
return '<%s long=%s address="%s">' % (
- self.__class__.__name__, self.long, self.address
+ self.__class__.__name__, self.long, self.address,
)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
index 73f917a50..18d0d036b 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
@@ -104,14 +104,14 @@ class Core(CorePluginBase):
self.update_timer = LoopingCall(self.check_import)
if self.config['check_after_days'] > 0:
self.update_timer.start(
- self.config['check_after_days'] * 24 * 60 * 60, update_now
+ self.config['check_after_days'] * 24 * 60 * 60, update_now,
)
def disable(self):
self.config.save()
log.debug('Reset IP filter')
self.core.session.get_ip_filter().add_rule(
- '0.0.0.0', '255.255.255.255', ALLOW_RANGE
+ '0.0.0.0', '255.255.255.255', ALLOW_RANGE,
)
log.debug('Blocklist: Plugin disabled')
@@ -189,7 +189,7 @@ class Core(CorePluginBase):
try:
ip = IP.parse(ip)
self.blocklist.add_rule(
- ip.address, ip.address, ALLOW_RANGE
+ ip.address, ip.address, ALLOW_RANGE,
)
saved.add(ip.address)
log.debug('Added %s to whitelisted', ip)
@@ -223,15 +223,17 @@ class Core(CorePluginBase):
self.update_timer.stop()
if self.config['check_after_days'] > 0:
self.update_timer.start(
- self.config['check_after_days'] * 24 * 60 * 60, update_now
+ self.config['check_after_days'] * 24 * 60 * 60, update_now,
)
continue
self.config[key] = config[key]
if needs_blocklist_import:
- log.debug('IP addresses were removed from the whitelist. Since we '
- 'do not know if they were blocked before. Re-import '
- 'current blocklist and re-add whitelisted.')
+ log.debug(
+ 'IP addresses were removed from the whitelist. Since we '
+ 'do not know if they were blocked before. Re-import '
+ 'current blocklist and re-add whitelisted.',
+ )
self.has_imported = False
d = self.import_list(deluge.configmanager.get_config_dir('blocklist.cache'))
d.addCallbacks(self.on_import_complete, self.on_import_error)
@@ -318,7 +320,7 @@ class Core(CorePluginBase):
self.is_downloading = True
return download_file(
url, deluge.configmanager.get_config_dir('blocklist.download'),
- on_retrieve_data, headers
+ on_retrieve_data, headers,
)
def on_download_complete(self, blocklist):
@@ -365,8 +367,10 @@ class Core(CorePluginBase):
else:
log.warning('Blocklist download failed: %s', error_msg)
if self.failed_attempts < self.config['try_times']:
- log.debug('Try downloading blocklist again... (%s/%s)',
- self.failed_attempts, self.config['try_times'])
+ log.debug(
+ 'Try downloading blocklist again... (%s/%s)',
+ self.failed_attempts, self.config['try_times'],
+ )
self.failed_attempts += 1
d = self.download_list()
d.addCallbacks(self.on_download_complete, self.on_download_error)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/decompressers.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/decompressers.py
index 6096d9935..8b9a0f4fb 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/decompressers.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/decompressers.py
@@ -17,25 +17,25 @@ import zipfile
def Zipped(reader): # NOQA: N802
"""Blocklist reader for zipped blocklists"""
- def open(self):
+ def _open(self):
z = zipfile.ZipFile(self.file)
f = z.open(z.namelist()[0])
return f
- reader.open = open
+ reader.open = _open
return reader
def GZipped(reader): # NOQA: N802
"""Blocklist reader for gzipped blocklists"""
- def open(self):
+ def _open(self):
return gzip.open(self.file)
- reader.open = open
+ reader.open = _open
return reader
def BZipped2(reader): # NOQA: N802
"""Blocklist reader for bzipped2 blocklists"""
- def open(self):
+ def _open(self):
return bz2.BZ2File(self.file)
- reader.open = open
+ reader.open = _open
return reader
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
index 96450278f..1d8b5d864 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
@@ -15,19 +15,19 @@ from .readers import EmuleReader, PeerGuardianReader, SafePeerReader
COMPRESSION_TYPES = {
'PK': 'Zip',
'\x1f\x8b': 'GZip',
- 'BZ': 'BZip2'
+ 'BZ': 'BZip2',
}
DECOMPRESSERS = {
'Zip': Zipped,
'GZip': GZipped,
- 'BZip2': BZipped2
+ 'BZip2': BZipped2,
}
READERS = {
'Emule': EmuleReader,
'SafePeer': SafePeerReader,
- 'PeerGuardian': PeerGuardianReader
+ 'PeerGuardian': PeerGuardianReader,
}
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
index 390c928a5..3d5df6c41 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
@@ -35,7 +35,7 @@ class GtkUI(GtkPluginBase):
image=common.get_resource('blocklist16.png'),
text='',
callback=self._on_status_item_clicked,
- tooltip=_('Blocked IP Ranges /Whitelisted IP Ranges')
+ tooltip=_('Blocked IP Ranges /Whitelisted IP Ranges'),
)
# Register some hooks
@@ -67,7 +67,8 @@ class GtkUI(GtkPluginBase):
self.builder.get_object('image_up_to_date').hide()
self.status_item.set_text(
- 'Downloading %.2f%%' % (status['file_progress'] * 100))
+ 'Downloading %.2f%%' % (status['file_progress'] * 100),
+ )
self.progress_bar.set_text('Downloading %.2f%%' % (status['file_progress'] * 100))
self.progress_bar.set_fraction(status['file_progress'])
self.progress_bar.show()
@@ -79,7 +80,8 @@ class GtkUI(GtkPluginBase):
self.builder.get_object('image_up_to_date').hide()
self.status_item.set_text(
- 'Importing ' + str(status['num_blocked']))
+ 'Importing ' + str(status['num_blocked']),
+ )
self.progress_bar.set_text('Importing %s' % (status['num_blocked']))
self.progress_bar.pulse()
self.progress_bar.show()
@@ -97,12 +99,15 @@ class GtkUI(GtkPluginBase):
self.status_item.set_text('%(num_blocked)s/%(num_whited)s' % status)
self.builder.get_object('label_filesize').set_text(
- deluge.common.fsize(status['file_size']))
+ deluge.common.fsize(status['file_size']),
+ )
self.builder.get_object('label_modified').set_text(
- datetime.fromtimestamp(status['file_date']).strftime('%c'))
+ datetime.fromtimestamp(status['file_date']).strftime('%c'),
+ )
self.builder.get_object('label_type').set_text(status['file_type'])
self.builder.get_object('label_url').set_text(
- status['file_url'])
+ status['file_url'],
+ )
client.blocklist.get_status().addCallback(_on_get_status)
@@ -155,18 +160,24 @@ class GtkUI(GtkPluginBase):
self.builder.connect_signals({
'on_button_check_download_clicked': self._on_button_check_download_clicked,
'on_button_force_download_clicked': self._on_button_force_download_clicked,
- 'on_whitelist_add_clicked': (self.on_add_button_clicked,
- self.whitelist_treeview),
- 'on_whitelist_remove_clicked': (self.on_delete_button_clicked,
- self.whitelist_treeview),
+ 'on_whitelist_add_clicked': (
+ self.on_add_button_clicked,
+ self.whitelist_treeview,
+ ),
+ 'on_whitelist_remove_clicked': (
+ self.on_delete_button_clicked,
+ self.whitelist_treeview,
+ ),
})
# Set button icons
self.builder.get_object('image_download').set_from_file(
- common.get_resource('blocklist_download24.png'))
+ common.get_resource('blocklist_download24.png'),
+ )
self.builder.get_object('image_import').set_from_file(
- common.get_resource('blocklist_import24.png'))
+ common.get_resource('blocklist_import24.png'),
+ )
# Update the preferences page with config values from the core
self._on_show_prefs()
@@ -174,13 +185,14 @@ class GtkUI(GtkPluginBase):
# Add the page to the preferences dialog
self.plugin.add_preferences_page(
_('Blocklist'),
- self.builder.get_object('blocklist_prefs_box'))
+ self.builder.get_object('blocklist_prefs_box'),
+ )
def build_whitelist_model_treeview(self):
self.whitelist_treeview = self.builder.get_object('whitelist_treeview')
treeview_selection = self.whitelist_treeview.get_selection()
treeview_selection.connect(
- 'changed', self.on_whitelist_treeview_selection_changed
+ 'changed', self.on_whitelist_treeview_selection_changed,
)
self.whitelist_model = gtk.ListStore(str, bool)
renderer = gtk.CellRendererText()
@@ -207,11 +219,15 @@ class GtkUI(GtkPluginBase):
def on_whitelist_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected()
if selected_connection_iter:
- self.builder.get_object('whitelist_delete').set_property('sensitive',
- True)
+ self.builder.get_object('whitelist_delete').set_property(
+ 'sensitive',
+ True,
+ )
else:
- self.builder.get_object('whitelist_delete').set_property('sensitive',
- False)
+ self.builder.get_object('whitelist_delete').set_property(
+ 'sensitive',
+ False,
+ )
def on_add_button_clicked(self, widget, treeview):
model = treeview.get_model()
@@ -228,5 +244,5 @@ class GtkUI(GtkPluginBase):
self.whitelist_model.clear()
for ip in whitelist:
self.whitelist_model.set(
- self.whitelist_model.append(), 0, ip, 1, True
+ self.whitelist_model.append(), 0, ip, 1, True,
)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
index 2f743427d..3da43c451 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
@@ -21,7 +21,7 @@ FORMAT_LIST = [
('gzmule', _('Emule IP list (GZip)')),
('spzip', _('SafePeer Text (Zipped)')),
('pgtext', _('PeerGuardian Text (Uncompressed)')),
- ('p2bgz', _('PeerGuardian P2B (GZip)'))
+ ('p2bgz', _('PeerGuardian P2B (GZip)')),
]
diff --git a/deluge/plugins/Blocklist/setup.py b/deluge/plugins/Blocklist/setup.py
index c49fb4f1c..03e2e189d 100644
--- a/deluge/plugins/Blocklist/setup.py
+++ b/deluge/plugins/Blocklist/setup.py
@@ -39,5 +39,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/core.py b/deluge/plugins/Execute/deluge/plugins/execute/core.py
index 5c5f622db..2dbf1c64d 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/core.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/core.py
@@ -26,7 +26,7 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
DEFAULT_CONFIG = {
- 'commands': []
+ 'commands': [],
}
EXECUTE_ID = 0
@@ -36,7 +36,7 @@ EXECUTE_COMMAND = 2
EVENT_MAP = {
'complete': 'TorrentFinishedEvent',
'added': 'TorrentAddedEvent',
- 'removed': 'TorrentRemovedEvent'
+ 'removed': 'TorrentRemovedEvent',
}
@@ -118,8 +118,10 @@ class Core(CorePluginBase):
command = os.path.expandvars(command[EXECUTE_COMMAND])
command = os.path.expanduser(command)
- cmd_args = [torrent_id.encode('utf8'), torrent_name.encode('utf8'),
- download_location.encode('utf8')]
+ cmd_args = [
+ torrent_id.encode('utf8'), torrent_name.encode('utf8'),
+ download_location.encode('utf8'),
+ ]
if windows_check():
# Escape ampersand on windows (see #2784)
cmd_args = [cmd_arg.replace('&', '^^^&') for cmd_arg in cmd_args]
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py b/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
index a00025042..f74e72007 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
@@ -30,7 +30,7 @@ EXECUTE_COMMAND = 2
EVENT_MAP = {
'complete': _('Torrent Complete'),
'added': _('Torrent Added'),
- 'removed': _('Torrent Removed')
+ 'removed': _('Torrent Removed'),
}
EVENTS = ['complete', 'added', 'removed']
diff --git a/deluge/plugins/Execute/setup.py b/deluge/plugins/Execute/setup.py
index 090131d1f..55d0ed56b 100644
--- a/deluge/plugins/Execute/setup.py
+++ b/deluge/plugins/Execute/setup.py
@@ -40,5 +40,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
index 27b0d3a2d..dbedb23e8 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
@@ -30,7 +30,7 @@ log = logging.getLogger(__name__)
DEFAULT_PREFS = {
'extract_path': '',
- 'use_name_folder': True
+ 'use_name_folder': True,
}
if windows_check():
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py b/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
index b0192256a..2adea4368 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
@@ -51,7 +51,7 @@ class GtkUI(GtkPluginBase):
config = {
'extract_path': path,
- 'use_name_folder': self.builder.get_object('chk_use_name').get_active()
+ 'use_name_folder': self.builder.get_object('chk_use_name').get_active(),
}
client.extractor.set_config(config)
diff --git a/deluge/plugins/Extractor/setup.py b/deluge/plugins/Extractor/setup.py
index a38f4d76e..9be0652a7 100644
--- a/deluge/plugins/Extractor/setup.py
+++ b/deluge/plugins/Extractor/setup.py
@@ -53,5 +53,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Label/deluge/plugins/label/core.py b/deluge/plugins/Label/deluge/plugins/label/core.py
index 9e3b4987c..4a1976edd 100644
--- a/deluge/plugins/Label/deluge/plugins/label/core.py
+++ b/deluge/plugins/Label/deluge/plugins/label/core.py
@@ -57,7 +57,7 @@ OPTIONS_DEFAULTS = {
'move_completed': False,
'move_completed_path': '',
'auto_add': False,
- 'auto_add_trackers': []
+ 'auto_add_trackers': [],
}
NO_LABEL = 'No Label'
@@ -108,7 +108,7 @@ class Core(CorePluginBase):
pass
def init_filter_dict(self):
- filter_dict = dict([(label, 0) for label in self.labels])
+ filter_dict = {label: 0 for label in self.labels}
filter_dict['All'] = len(self.torrents)
return filter_dict
@@ -208,8 +208,8 @@ class Core(CorePluginBase):
torrent.set_options(
{
'move_completed': options['move_completed'],
- 'move_completed_path': options['move_completed_path']
- }
+ 'move_completed_path': options['move_completed_path'],
+ },
)
def _unset_torrent_options(self, torrent_id, label_id):
@@ -233,8 +233,8 @@ class Core(CorePluginBase):
torrent.set_options(
{
'move_completed': self.core_cfg.config['move_completed'],
- 'move_completed_path': self.core_cfg.config['move_completed_path']
- }
+ 'move_completed_path': self.core_cfg.config['move_completed_path'],
+ },
)
def _has_auto_match(self, torrent, label_options):
@@ -310,7 +310,10 @@ class Core(CorePluginBase):
@export
def get_config(self):
"""see : label_set_config"""
- return dict((key, self.config[key]) for key in CORE_OPTIONS if key in self.config.config)
+ return {
+ key: self.config[key]
+ for key in CORE_OPTIONS if key in self.config.config
+ }
@export
def set_config(self, options):
diff --git a/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py b/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py
index 834a45836..cdb298ccb 100644
--- a/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py
+++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py
@@ -126,8 +126,10 @@ class AddDialog(object):
class OptionsDialog(object):
spin_ids = ['max_download_speed', 'max_upload_speed', 'stop_ratio']
spin_int_ids = ['max_upload_slots', 'max_connections']
- chk_ids = ['apply_max', 'apply_queue', 'stop_at_ratio', 'apply_queue', 'remove_at_ratio',
- 'apply_move_completed', 'move_completed', 'is_auto_managed', 'auto_add']
+ chk_ids = [
+ 'apply_max', 'apply_queue', 'stop_at_ratio', 'apply_queue', 'remove_at_ratio',
+ 'apply_move_completed', 'move_completed', 'is_auto_managed', 'auto_add',
+ ]
# list of tuples, because order matters when nesting.
sensitive_groups = [
@@ -136,7 +138,7 @@ class OptionsDialog(object):
('stop_at_ratio', ['remove_at_ratio', 'stop_ratio']), # nested
('apply_move_completed', ['move_completed']),
('move_completed', ['move_completed_path']), # nested
- ('auto_add', ['auto_add_trackers'])
+ ('auto_add', ['auto_add_trackers']),
]
def __init__(self):
diff --git a/deluge/plugins/Label/setup.py b/deluge/plugins/Label/setup.py
index b69438d0b..a0c048416 100644
--- a/deluge/plugins/Label/setup.py
+++ b/deluge/plugins/Label/setup.py
@@ -44,5 +44,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/common.py b/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
index 8b4d68e9d..5d6029cc1 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
@@ -37,7 +37,7 @@ class CustomNotifications(object):
'email': {},
'popup': {},
'blink': {},
- 'sound': {}
+ 'sound': {},
}
def enable(self):
@@ -72,7 +72,7 @@ class CustomNotifications(object):
wrapper, handler = self.custom_notifications[kind][eventtype]
try:
component.get('EventManager').register_event_handler(
- eventtype, wrapper
+ eventtype, wrapper,
)
except KeyError:
from deluge.ui.client import client
@@ -83,7 +83,7 @@ class CustomNotifications(object):
wrapper, handler = self.custom_notifications[kind][eventtype]
try:
component.get('EventManager').deregister_event_handler(
- eventtype, wrapper
+ eventtype, wrapper,
)
except KeyError:
from deluge.ui.client import client
@@ -99,8 +99,10 @@ class CustomNotifications(object):
if known_events[eventtype].__module__.startswith('deluge.event'):
if handler.__self__ is self:
return True
- log.error('You cannot register custom notification providers '
- 'for built-in event types.')
+ log.error(
+ 'You cannot register custom notification providers '
+ 'for built-in event types.',
+ )
return False
return True
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
index 46c6812d4..66c3ee078 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
@@ -41,8 +41,8 @@ DEFAULT_PREFS = {
'smtp_recipients': [],
# Subscriptions
'subscriptions': {
- 'email': []
- }
+ 'email': [],
+ },
}
@@ -53,8 +53,10 @@ class CoreNotifications(CustomNotifications):
def enable(self):
CustomNotifications.enable(self)
- self.register_custom_email_notification('TorrentFinishedEvent',
- self._on_torrent_finished_event)
+ self.register_custom_email_notification(
+ 'TorrentFinishedEvent',
+ self._on_torrent_finished_event,
+ )
def disable(self):
self.deregister_custom_email_notification('TorrentFinishedEvent')
@@ -77,8 +79,10 @@ class CoreNotifications(CustomNotifications):
if not self.config['smtp_enabled']:
return defer.succeed('SMTP notification not enabled.')
subject, message = result
- log.debug('Spawning new thread to send email with subject: %s: %s',
- subject, message)
+ log.debug(
+ 'Spawning new thread to send email with subject: %s: %s',
+ subject, message,
+ )
# Spawn thread because we don't want Deluge to lock up while we send the
# email.
return threads.deferToThread(self._notify_email, subject, message)
@@ -103,7 +107,8 @@ class CoreNotifications(CustomNotifications):
'smtp_from': self.config['smtp_from'],
'subject': subject,
'smtp_recipients': to_addrs_str,
- 'date': formatdate()}
+ 'date': formatdate(),
+ }
headers = """\
From: %(smtp_from)s
To: %(smtp_recipients)s
@@ -176,7 +181,7 @@ Date: %(date)s
'downloading "%(name)s", which includes %(num_files)i files.'
'\nTo stop receiving these alerts, simply turn off email '
"notification in Deluge's preferences.\n\n"
- 'Thank you,\nDeluge.'
+ 'Thank you,\nDeluge.',
) % torrent_status
return subject, message
@@ -196,7 +201,8 @@ class Core(CorePluginBase, CoreNotifications):
def enable(self):
CoreNotifications.enable(self)
self.config = deluge.configmanager.ConfigManager(
- 'notifications-core.conf', DEFAULT_PREFS)
+ 'notifications-core.conf', DEFAULT_PREFS,
+ )
log.debug('ENABLING CORE NOTIFICATIONS')
def disable(self):
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
index 51030377c..86a3daf8c 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
@@ -67,8 +67,10 @@ DEFAULT_PREFS = {
}
RECIPIENT_FIELD, RECIPIENT_EDIT = list(range(2))
-(SUB_EVENT, SUB_EVENT_DOC, SUB_NOT_EMAIL, SUB_NOT_POPUP, SUB_NOT_BLINK,
- SUB_NOT_SOUND) = list(range(6))
+(
+ SUB_EVENT, SUB_EVENT_DOC, SUB_NOT_EMAIL, SUB_NOT_POPUP, SUB_NOT_BLINK,
+ SUB_NOT_SOUND,
+) = list(range(6))
SND_EVENT, SND_EVENT_DOC, SND_NAME, SND_PATH = list(range(4))
@@ -80,13 +82,13 @@ class GtkUiNotifications(CustomNotifications):
def enable(self):
CustomNotifications.enable(self)
self.register_custom_blink_notification(
- 'TorrentFinishedEvent', self._on_torrent_finished_event_blink
+ 'TorrentFinishedEvent', self._on_torrent_finished_event_blink,
)
self.register_custom_sound_notification(
- 'TorrentFinishedEvent', self._on_torrent_finished_event_sound
+ 'TorrentFinishedEvent', self._on_torrent_finished_event_sound,
)
self.register_custom_popup_notification(
- 'TorrentFinishedEvent', self._on_torrent_finished_event_popup
+ 'TorrentFinishedEvent', self._on_torrent_finished_event_popup,
)
def disable(self):
@@ -146,17 +148,22 @@ class GtkUiNotifications(CustomNotifications):
def handle_custom_blink_notification(self, result, eventtype):
if result:
return defer.maybeDeferred(self.__blink)
- return defer.succeed('Will not blink. The returned value from the custom '
- 'handler was: %s' % result)
+ return defer.succeed(
+ 'Will not blink. The returned value from the custom '
+ 'handler was: %s' % result,
+ )
def handle_custom_sound_notification(self, result, eventtype):
if isinstance(result, ''.__class__):
if not result and eventtype in self.config['custom_sounds']:
return defer.maybeDeferred(
- self.__play_sound, self.config['custom_sounds'][eventtype])
+ self.__play_sound, self.config['custom_sounds'][eventtype],
+ )
return defer.maybeDeferred(self.__play_sound, result)
- return defer.succeed('Will not play sound. The returned value from the '
- 'custom handler was: %s' % result)
+ return defer.succeed(
+ 'Will not play sound. The returned value from the '
+ 'custom handler was: %s' % result,
+ )
def __blink(self):
self.systray.blink(True)
@@ -219,12 +226,16 @@ class GtkUiNotifications(CustomNotifications):
log.debug('Failed to get torrent status to be able to show the popup')
def _on_torrent_finished_event_got_torrent_status(self, torrent_status):
- log.debug('Handler for TorrentFinishedEvent GTKUI called. '
- 'Got Torrent Status')
+ log.debug(
+ 'Handler for TorrentFinishedEvent GTKUI called. '
+ 'Got Torrent Status',
+ )
title = _('Finished Torrent')
torrent_status['num_files'] = torrent_status['file_progress'].count(1.0)
- message = _('The torrent "%(name)s" including %(num_files)i file(s) '
- 'has finished downloading.') % torrent_status
+ message = _(
+ 'The torrent "%(name)s" including %(num_files)i file(s) '
+ 'has finished downloading.',
+ ) % torrent_status
return title, message
@@ -235,7 +246,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def enable(self):
self.config = deluge.configmanager.ConfigManager(
- 'notifications-gtk.conf', DEFAULT_PREFS
+ 'notifications-gtk.conf', DEFAULT_PREFS,
)
self.builder = gtk.Builder()
self.builder.add_from_file(get_resource('config.ui'))
@@ -248,73 +259,97 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.build_notifications_model_populate_treeview()
client.notifications.get_handled_events().addCallback(
- self.popuplate_what_needs_handled_events
+ self.popuplate_what_needs_handled_events,
)
self.builder.connect_signals({
- 'on_add_button_clicked': (self.on_add_button_clicked,
- self.recipients_treeview),
- 'on_delete_button_clicked': (self.on_delete_button_clicked,
- self.recipients_treeview),
+ 'on_add_button_clicked': (
+ self.on_add_button_clicked,
+ self.recipients_treeview,
+ ),
+ 'on_delete_button_clicked': (
+ self.on_delete_button_clicked,
+ self.recipients_treeview,
+ ),
'on_enabled_toggled': self.on_enabled_toggled,
'on_sound_enabled_toggled': self.on_sound_enabled_toggled,
'on_sounds_edit_button_clicked': self.on_sounds_edit_button_clicked,
'on_sounds_revert_button_clicked': self.on_sounds_revert_button_clicked,
- 'on_sound_path_update_preview': self.on_sound_path_update_preview
+ 'on_sound_path_update_preview': self.on_sound_path_update_preview,
})
component.get('Preferences').add_page(_('Notifications'), self.prefs)
- component.get('PluginManager').register_hook('on_apply_prefs',
- self.on_apply_prefs)
- component.get('PluginManager').register_hook('on_show_prefs',
- self.on_show_prefs)
+ component.get('PluginManager').register_hook(
+ 'on_apply_prefs',
+ self.on_apply_prefs,
+ )
+ component.get('PluginManager').register_hook(
+ 'on_show_prefs',
+ self.on_show_prefs,
+ )
if not POPUP_AVAILABLE:
- self.builder.get_object('popup_enabled').set_property('sensitive',
- False)
+ self.builder.get_object('popup_enabled').set_property(
+ 'sensitive',
+ False,
+ )
if not SOUND_AVAILABLE:
# for widget_name in ('sound_enabled', 'sound_path', 'sounds_page', 'sounds_page_label'):
# self.builder.get_object(widget_name).set_property('sensitive', False)
- self.builder.get_object('sound_enabled').set_property('sensitive',
- False)
+ self.builder.get_object('sound_enabled').set_property(
+ 'sensitive',
+ False,
+ )
self.builder.get_object('sound_path').set_property('sensitive', False)
- self.builder.get_object('sounds_page').set_property('sensitive',
- False)
- self.builder.get_object('sounds_page_label').set_property('sensitive',
- False)
+ self.builder.get_object('sounds_page').set_property(
+ 'sensitive',
+ False,
+ )
+ self.builder.get_object('sounds_page_label').set_property(
+ 'sensitive',
+ False,
+ )
self.systray = component.get('SystemTray')
if not hasattr(self.systray, 'tray'):
# Tray is not beeing used
- self.builder.get_object('blink_enabled').set_property('sensitive',
- False)
+ self.builder.get_object('blink_enabled').set_property(
+ 'sensitive',
+ False,
+ )
GtkUiNotifications.enable(self)
def disable(self):
GtkUiNotifications.disable(self)
component.get('Preferences').remove_page(_('Notifications'))
- component.get('PluginManager').deregister_hook('on_apply_prefs',
- self.on_apply_prefs)
- component.get('PluginManager').deregister_hook('on_show_prefs',
- self.on_show_prefs)
+ component.get('PluginManager').deregister_hook(
+ 'on_apply_prefs',
+ self.on_apply_prefs,
+ )
+ component.get('PluginManager').deregister_hook(
+ 'on_show_prefs',
+ self.on_show_prefs,
+ )
def build_recipients_model_populate_treeview(self):
# SMTP Recipients treeview/model
self.recipients_treeview = self.builder.get_object('smtp_recipients')
treeview_selection = self.recipients_treeview.get_selection()
treeview_selection.connect(
- 'changed', self.on_recipients_treeview_selection_changed
+ 'changed', self.on_recipients_treeview_selection_changed,
)
self.recipients_model = gtk.ListStore(str, bool)
renderer = gtk.CellRendererText()
renderer.connect('edited', self.on_cell_edited, self.recipients_model)
renderer.set_data('recipient', RECIPIENT_FIELD)
- column = gtk.TreeViewColumn('Recipients', renderer,
- text=RECIPIENT_FIELD,
- editable=RECIPIENT_EDIT)
+ column = gtk.TreeViewColumn(
+ 'Recipients', renderer,
+ text=RECIPIENT_FIELD,
+ editable=RECIPIENT_EDIT,
+ )
column.set_expand(True)
self.recipients_treeview.append_column(column)
self.recipients_treeview.set_model(self.recipients_model)
@@ -324,7 +359,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.sounds_treeview = self.builder.get_object('sounds_treeview')
sounds_selection = self.sounds_treeview.get_selection()
sounds_selection.connect(
- 'changed', self.on_sounds_treeview_selection_changed
+ 'changed', self.on_sounds_treeview_selection_changed,
)
self.sounds_treeview.set_tooltip_column(SND_EVENT_DOC)
@@ -360,7 +395,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.subscriptions_treeview = self.builder.get_object('subscriptions_treeview')
subscriptions_selection = self.subscriptions_treeview.get_selection()
subscriptions_selection.connect(
- 'changed', self.on_subscriptions_treeview_selection_changed
+ 'changed', self.on_subscriptions_treeview_selection_changed,
)
self.subscriptions_treeview.set_tooltip_column(SUB_EVENT_DOC)
self.subscriptions_model = gtk.ListStore(str, str, bool, bool, bool, bool)
@@ -426,7 +461,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
SND_EVENT, event_name,
SND_EVENT_DOC, event_doc,
SND_NAME, basename(snd_path),
- SND_PATH, snd_path
+ SND_PATH, snd_path,
)
def populate_subscriptions(self, handled_events, email_subscriptions=None):
@@ -443,7 +478,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
SUB_NOT_EMAIL, event_name in email_subscriptions,
SUB_NOT_POPUP, event_name in subscriptions_dict['popup'],
SUB_NOT_BLINK, event_name in subscriptions_dict['blink'],
- SUB_NOT_SOUND, event_name in subscriptions_dict['sound']
+ SUB_NOT_SOUND, event_name in subscriptions_dict['sound'],
)
def on_apply_prefs(self):
@@ -465,8 +500,10 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
old_sound_file = self.config['sound_path']
new_sound_file = self.builder.get_object('sound_path').get_filename()
- log.debug('Old Default sound file: %s New one: %s',
- old_sound_file, new_sound_file)
+ log.debug(
+ 'Old Default sound file: %s New one: %s',
+ old_sound_file, new_sound_file,
+ )
custom_sounds = {}
for event_name, event_doc, filename, filepath in self.sounds_model:
log.debug('Custom sound for event "%s": %s', event_name, filename)
@@ -482,9 +519,9 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
'subscriptions': {
'popup': current_popup_subscriptions,
'blink': current_blink_subscriptions,
- 'sound': current_sound_subscriptions
+ 'sound': current_sound_subscriptions,
},
- 'custom_sounds': custom_sounds
+ 'custom_sounds': custom_sounds,
})
self.config.save()
@@ -496,9 +533,11 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
'smtp_pass': self.builder.get_object('smtp_pass').get_text(),
'smtp_from': self.builder.get_object('smtp_from').get_text(),
'smtp_tls': self.builder.get_object('smtp_tls').get_active(),
- 'smtp_recipients': [dest[0] for dest in self.recipients_model if
- dest[0] != 'USER@HOST'],
- 'subscriptions': {'email': current_email_subscriptions}
+ 'smtp_recipients': [
+ dest[0] for dest in self.recipients_model if
+ dest[0] != 'USER@HOST'
+ ],
+ 'subscriptions': {'email': current_email_subscriptions},
}
client.notifications.set_config(core_config)
@@ -517,20 +556,22 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.builder.get_object('smtp_tls').set_active(core_config['smtp_tls'])
self.recipients_model.clear()
for recipient in core_config['smtp_recipients']:
- self.recipients_model.set(self.recipients_model.append(),
- RECIPIENT_FIELD, recipient,
- RECIPIENT_EDIT, False)
+ self.recipients_model.set(
+ self.recipients_model.append(),
+ RECIPIENT_FIELD, recipient,
+ RECIPIENT_EDIT, False,
+ )
self.builder.get_object('smtp_enabled').set_active(
- core_config['smtp_enabled']
+ core_config['smtp_enabled'],
)
self.builder.get_object('sound_enabled').set_active(
- self.config['sound_enabled']
+ self.config['sound_enabled'],
)
self.builder.get_object('popup_enabled').set_active(
- self.config['popup_enabled']
+ self.config['popup_enabled'],
)
self.builder.get_object('blink_enabled').set_active(
- self.config['blink_enabled']
+ self.config['blink_enabled'],
)
if self.config['sound_path']:
sound_path = self.config['sound_path']
@@ -543,19 +584,21 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
client.notifications.get_handled_events().addCallback(
self.popuplate_what_needs_handled_events,
- core_config['subscriptions']['email']
+ core_config['subscriptions']['email'],
)
def on_sound_path_update_preview(self, filechooser):
client.notifications.get_handled_events().addCallback(
- self.populate_sounds
+ self.populate_sounds,
)
def on_add_button_clicked(self, widget, treeview):
model = treeview.get_model()
- model.set(model.append(),
- RECIPIENT_FIELD, 'USER@HOST',
- RECIPIENT_EDIT, True)
+ model.set(
+ model.append(),
+ RECIPIENT_FIELD, 'USER@HOST',
+ RECIPIENT_EDIT, True,
+ )
def on_delete_button_clicked(self, widget, treeview):
selection = treeview.get_selection()
@@ -570,20 +613,28 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def on_recipients_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected()
if selected_connection_iter:
- self.builder.get_object('delete_button').set_property('sensitive',
- True)
+ self.builder.get_object('delete_button').set_property(
+ 'sensitive',
+ True,
+ )
else:
- self.builder.get_object('delete_button').set_property('sensitive',
- False)
+ self.builder.get_object('delete_button').set_property(
+ 'sensitive',
+ False,
+ )
def on_subscriptions_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected()
if selected_connection_iter:
- self.builder.get_object('delete_button').set_property('sensitive',
- True)
+ self.builder.get_object('delete_button').set_property(
+ 'sensitive',
+ True,
+ )
else:
- self.builder.get_object('delete_button').set_property('sensitive',
- False)
+ self.builder.get_object('delete_button').set_property(
+ 'sensitive',
+ False,
+ )
def on_sounds_treeview_selection_changed(self, selection):
model, selected_iter = selection.get_selected()
@@ -605,9 +656,11 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
model, selected_iter = selection.get_selected()
if selected_iter:
log.debug('on_sounds_revert_button_clicked: got iter')
- model.set(selected_iter,
- SND_PATH, self.config['sound_path'],
- SND_NAME, basename(self.config['sound_path']))
+ model.set(
+ selected_iter,
+ SND_PATH, self.config['sound_path'],
+ SND_NAME, basename(self.config['sound_path']),
+ )
def on_sounds_edit_button_clicked(self, widget):
log.debug('on_sounds_edit_button_clicked')
@@ -617,10 +670,12 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
path = model.get(selected_iter, SND_PATH)[0]
dialog = gtk.FileChooserDialog(
title=_('Choose Sound File'),
- buttons=(gtk.STOCK_CANCEL,
- gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN,
- gtk.RESPONSE_OK)
+ buttons=(
+ gtk.STOCK_CANCEL,
+ gtk.RESPONSE_CANCEL,
+ gtk.STOCK_OPEN,
+ gtk.RESPONSE_OK,
+ ),
)
dialog.set_filename(path)
@@ -629,34 +684,48 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
new_filename = dialog.get_filename()
dialog.destroy()
log.debug(new_filename)
- model.set(selected_iter,
- SND_PATH, new_filename,
- SND_NAME, basename(new_filename))
+ model.set(
+ selected_iter,
+ SND_PATH, new_filename,
+ SND_NAME, basename(new_filename),
+ )
d = defer.maybeDeferred(dialog.run)
d.addCallback(update_model)
log.debug('dialog should have been shown')
def on_enabled_toggled(self, widget):
- for widget_name in ('smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass',
- 'smtp_pass', 'smtp_tls', 'smtp_from',
- 'smtp_recipients'):
- self.builder.get_object(widget_name).set_property('sensitive',
- widget.get_active())
+ for widget_name in (
+ 'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass',
+ 'smtp_pass', 'smtp_tls', 'smtp_from',
+ 'smtp_recipients',
+ ):
+ self.builder.get_object(widget_name).set_property(
+ 'sensitive',
+ widget.get_active(),
+ )
def on_sound_enabled_toggled(self, widget):
if widget.get_active():
self.builder.get_object('sound_path').set_property('sensitive', True)
- self.builder.get_object('sounds_page').set_property('sensitive',
- True)
- self.builder.get_object('sounds_page_label').set_property('sensitive',
- True)
+ self.builder.get_object('sounds_page').set_property(
+ 'sensitive',
+ True,
+ )
+ self.builder.get_object('sounds_page_label').set_property(
+ 'sensitive',
+ True,
+ )
else:
self.builder.get_object('sound_path').set_property('sensitive', False)
- self.builder.get_object('sounds_page').set_property('sensitive',
- False)
- self.builder.get_object('sounds_page_label').set_property('sensitive',
- False)
+ self.builder.get_object('sounds_page').set_property(
+ 'sensitive',
+ False,
+ )
+ self.builder.get_object('sounds_page_label').set_property(
+ 'sensitive',
+ False,
+ )
# for widget_name in ('sounds_path', 'sounds_page', 'sounds_page_label'):
# self.builder.get_object(widget_name).set_property('sensitive',
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/test.py b/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
index 9d2ea83c6..642442c5e 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
@@ -34,7 +34,7 @@ class TestEmailNotifications(component.Component):
self.n = 1
self.events = [
FooEvent(),
- CustomEvent()
+ CustomEvent(),
]
self.events_classes = []
@@ -45,21 +45,21 @@ class TestEmailNotifications(component.Component):
# component.get('CorePlugin.Notifications').register_custom_email_notification(
component.get('Notifications').register_custom_email_notification(
event.__class__.__name__,
- self.custom_email_message_provider
+ self.custom_email_message_provider,
)
elif self.__imp == 'gtk':
notifications_component = component.get('Notifications')
notifications_component.register_custom_popup_notification(
event.__class__.__name__,
- self.custom_popup_message_provider
+ self.custom_popup_message_provider,
)
notifications_component.register_custom_blink_notification(
event.__class__.__name__,
- self.custom_blink_message_provider
+ self.custom_blink_message_provider,
)
notifications_component.register_custom_sound_notification(
event.__class__.__name__,
- self.custom_sound_message_provider
+ self.custom_sound_message_provider,
)
self.lc.start(60, False)
diff --git a/deluge/plugins/Notifications/setup.py b/deluge/plugins/Notifications/setup.py
index 9c94dd34b..84893f53c 100755
--- a/deluge/plugins/Notifications/setup.py
+++ b/deluge/plugins/Notifications/setup.py
@@ -52,5 +52,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
index 37830de6e..c1e9da999 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
@@ -32,13 +32,13 @@ DEFAULT_PREFS = {
'low_active': -1,
'low_active_down': -1,
'low_active_up': -1,
- 'button_state': [[0] * 7 for dummy in range(24)]
+ 'button_state': [[0] * 7 for dummy in range(24)],
}
STATES = {
0: 'Green',
1: 'Yellow',
- 2: 'Red'
+ 2: 'Red',
}
CONTROLLED_SETTINGS = [
@@ -46,7 +46,7 @@ CONTROLLED_SETTINGS = [
'max_upload_speed',
'max_active_limit',
'max_active_downloading',
- 'max_active_seeding'
+ 'max_active_seeding',
]
@@ -127,7 +127,7 @@ class Core(CorePluginBase):
'active_downloads': self.config['low_active_down'],
'active_seeds': self.config['low_active_up'],
'download_rate_limit': int(self.config['low_down'] * 1024),
- 'upload_rate_limit': int(self.config['low_up'] * 1024)
+ 'upload_rate_limit': int(self.config['low_up'] * 1024),
}
component.get('Core').apply_session_settings(settings)
# Resume the session if necessary
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
index 217525d34..660101f7f 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
@@ -31,8 +31,10 @@ DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
class SchedulerSelectWidget(gtk.DrawingArea):
def __init__(self, hover):
super(SchedulerSelectWidget, self).__init__()
- self.set_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK |
- gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.LEAVE_NOTIFY_MASK)
+ self.set_events(
+ gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK |
+ gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.LEAVE_NOTIFY_MASK,
+ )
self.connect('expose_event', self.expose)
self.connect('button_press_event', self.mouse_down)
@@ -40,9 +42,11 @@ class SchedulerSelectWidget(gtk.DrawingArea):
self.connect('motion_notify_event', self.mouse_hover)
self.connect('leave_notify_event', self.mouse_leave)
- self.colors = [[115 / 255, 210 / 255, 22 / 255],
- [237 / 255, 212 / 255, 0 / 255],
- [204 / 255, 0 / 255, 0 / 255]]
+ self.colors = [
+ [115 / 255, 210 / 255, 22 / 255],
+ [237 / 255, 212 / 255, 0 / 255],
+ [204 / 255, 0 / 255, 0 / 255],
+ ]
self.button_state = [[0] * 7 for dummy in range(24)]
self.start_point = [0, 0]
@@ -69,11 +73,15 @@ class SchedulerSelectWidget(gtk.DrawingArea):
for y in range(7):
for x in range(24):
- context.set_source_rgba(self.colors[self.button_state[x][y]][0],
- self.colors[self.button_state[x][y]][1],
- self.colors[self.button_state[x][y]][2], 0.7)
- context.rectangle(width * (6 * x / 145 + 1 / 145), height * (6 * y / 43 + 1 / 43),
- 5 * width / 145, 5 * height / 43)
+ context.set_source_rgba(
+ self.colors[self.button_state[x][y]][0],
+ self.colors[self.button_state[x][y]][1],
+ self.colors[self.button_state[x][y]][2], 0.7,
+ )
+ context.rectangle(
+ width * (6 * x / 145 + 1 / 145), height * (6 * y / 43 + 1 / 43),
+ 5 * width / 145, 5 * height / 43,
+ )
context.fill_preserve()
context.set_source_rgba(0.5, 0.5, 0.5, 0.5)
context.stroke()
@@ -123,9 +131,11 @@ class SchedulerSelectWidget(gtk.DrawingArea):
if self.get_point(event) != self.hover_point:
self.hover_point = self.get_point(event)
- self.hover_label.set_text(self.hover_days[self.hover_point[1]] +
- ' ' + str(self.hover_point[0]) +
- ':00 - ' + str(self.hover_point[0]) + ':59')
+ self.hover_label.set_text(
+ self.hover_days[self.hover_point[1]] +
+ ' ' + str(self.hover_point[0]) +
+ ':00 - ' + str(self.hover_point[0]) + ':59',
+ )
if self.mouse_press:
points = [[self.hover_point[0], self.start_point[0]], [self.hover_point[1], self.start_point[1]]]
@@ -153,7 +163,8 @@ class GtkUI(GtkPluginBase):
image=get_resource('green.png'),
text='',
callback=self.on_status_item_clicked,
- tooltip='Scheduler')
+ tooltip='Scheduler',
+ )
def on_state_deferred(state):
self.state = state
diff --git a/deluge/plugins/Scheduler/setup.py b/deluge/plugins/Scheduler/setup.py
index c5ab60a8a..ea9c6bbcf 100644
--- a/deluge/plugins/Scheduler/setup.py
+++ b/deluge/plugins/Scheduler/setup.py
@@ -44,5 +44,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/core.py b/deluge/plugins/Stats/deluge/plugins/stats/core.py
index af2ccd26b..a269516a3 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/core.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/core.py
@@ -32,7 +32,7 @@ DEFAULT_TOTALS = {
'total_download': 0,
'total_payload_upload': 0,
'total_payload_download': 0,
- 'stats': {}
+ 'stats': {},
}
log = logging.getLogger(__name__)
@@ -85,7 +85,7 @@ class Core(CorePluginBase):
'dht_cache_nodes',
'dht_torrents',
'num_peers',
- 'num_connections'
+ 'num_connections',
)
self.update_stats()
@@ -121,9 +121,11 @@ class Core(CorePluginBase):
pass
stats['num_connections'] = stats['num_peers'] + stats['peer.num_peers_half_open']
stats['dht_cache_nodes'] = stats['dht.dht_node_cache']
- stats.update(self.core.get_config_values(['max_download',
- 'max_upload',
- 'max_num_connections']))
+ stats.update(self.core.get_config_values([
+ 'max_download',
+ 'max_upload',
+ 'max_num_connections',
+ ]))
# status = self.core.session.status()
# for stat in dir(status):
# if not stat.startswith('_') and stat not in stats:
@@ -193,7 +195,8 @@ class Core(CorePluginBase):
@export
def get_session_totals(self):
return self.core.get_session_status(
- ['total_upload', 'total_download', 'total_payload_upload', 'total_payload_download'])
+ ['total_upload', 'total_download', 'total_payload_upload', 'total_payload_download'],
+ )
@export
def set_config(self, config):
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/graph.py b/deluge/plugins/Stats/deluge/plugins/stats/graph.py
index d58af1fab..e87148e70 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/graph.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/graph.py
@@ -69,7 +69,7 @@ class Graph(object):
self.mean_selected = True
self.legend_selected = True
self.max_selected = True
- self.black = (0, 0, 0,)
+ self.black = (0, 0, 0)
self.interval = 2 # 2 secs
self.text_bg = (255, 255, 255, 128) # prototyping
self.set_left_axis()
@@ -83,7 +83,7 @@ class Graph(object):
'label': label,
'line': line,
'fill': fill,
- 'color': color
+ 'color': color,
}
def set_stats(self, stats):
@@ -273,7 +273,8 @@ class Graph(object):
self.ctx.line_to(
int(right - (len(values) - 1) * step),
- bottom)
+ bottom,
+ )
self.ctx.close_path()
def draw_value_poly(self, values, color, max_value, bounds, fill=False):
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py b/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
index 670e3cd82..f1d664f31 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
@@ -45,7 +45,9 @@ DEFAULT_CONF = {
},
'seeds_graph': {
'num_peers': str(gtk.gdk.Color('blue')),
- }}}
+ },
+ },
+}
def neat_time(column, cell, model, data):
@@ -126,9 +128,11 @@ class GraphsTab(Tab):
# set a clip region
context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height)
context.clip()
- self.graph.draw_to_context(context,
- self.graph_widget.allocation.width,
- self.graph_widget.allocation.height)
+ self.graph.draw_to_context(
+ context,
+ self.graph_widget.allocation.width,
+ self.graph_widget.allocation.height,
+ )
# Do not propagate the event
return False
@@ -153,12 +157,18 @@ class GraphsTab(Tab):
self.graph_widget = self.bandwidth_graph
self.graph = Graph()
colors = self.colors['bandwidth_graph']
- self.graph.add_stat('download_rate', label='Download Rate',
- color=gtk_to_graph_color(colors['download_rate']))
- self.graph.add_stat('upload_rate', label='Upload Rate',
- color=gtk_to_graph_color(colors['upload_rate']))
- self.graph.set_left_axis(formatter=fspeed_shortform, min=10240,
- formatter_scale=size_formatter_scale)
+ self.graph.add_stat(
+ 'download_rate', label='Download Rate',
+ color=gtk_to_graph_color(colors['download_rate']),
+ )
+ self.graph.add_stat(
+ 'upload_rate', label='Upload Rate',
+ color=gtk_to_graph_color(colors['upload_rate']),
+ )
+ self.graph.set_left_axis(
+ formatter=fspeed_shortform, min=10240,
+ formatter_scale=size_formatter_scale,
+ )
def select_connections_graph(self):
log.debug('Selecting connections graph')
@@ -183,9 +193,11 @@ class GraphsTab(Tab):
def set_colors(self, colors):
self.colors = colors
# Fake switch page to update the graph colors (HACKY)
- self._on_notebook_switch_page(self.notebook,
- None, # This is unused
- self.notebook.get_current_page())
+ self._on_notebook_switch_page(
+ self.notebook,
+ None, # This is unused
+ self.notebook.get_current_page(),
+ )
def _on_intervals_changed(self, intervals):
liststore = gtk.ListStore(int)
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py b/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py
index 34c54bf36..ca5f2bdf7 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py
@@ -46,10 +46,10 @@ class StatsTestCase(BaseTestCase):
raise unittest.SkipTest('WebUi plugin not available for testing')
totals = yield client.stats.get_totals()
- self.assertEquals(totals['total_upload'], 0)
- self.assertEquals(totals['total_payload_upload'], 0)
- self.assertEquals(totals['total_payload_download'], 0)
- self.assertEquals(totals['total_download'], 0)
+ self.assertEqual(totals['total_upload'], 0)
+ self.assertEqual(totals['total_payload_upload'], 0)
+ self.assertEqual(totals['total_payload_download'], 0)
+ self.assertEqual(totals['total_download'], 0)
# print_totals(totals)
@defer.inlineCallbacks
@@ -59,10 +59,10 @@ class StatsTestCase(BaseTestCase):
raise unittest.SkipTest('WebUi plugin not available for testing')
totals = yield client.stats.get_session_totals()
- self.assertEquals(totals['total_upload'], 0)
- self.assertEquals(totals['total_payload_upload'], 0)
- self.assertEquals(totals['total_payload_download'], 0)
- self.assertEquals(totals['total_download'], 0)
+ self.assertEqual(totals['total_upload'], 0)
+ self.assertEqual(totals['total_payload_upload'], 0)
+ self.assertEqual(totals['total_payload_download'], 0)
+ self.assertEqual(totals['total_download'], 0)
# print_totals(totals)
@pytest.mark.gtkui
diff --git a/deluge/plugins/Stats/setup.py b/deluge/plugins/Stats/setup.py
index 64b12373b..593f68271 100644
--- a/deluge/plugins/Stats/setup.py
+++ b/deluge/plugins/Stats/setup.py
@@ -48,5 +48,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py b/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
index dc257d8c7..7fcce70f0 100644
--- a/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
+++ b/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
@@ -28,8 +28,10 @@ class GtkUI(GtkPluginBase):
self.core = client.toggle
self.plugin = component.get('PluginManager')
self.separator = self.plugin.add_toolbar_separator()
- self.button = self.plugin.add_toolbar_button(self._on_button_clicked, label='Pause Session',
- stock='gtk-media-pause', tooltip='Pause the session')
+ self.button = self.plugin.add_toolbar_button(
+ self._on_button_clicked, label='Pause Session',
+ stock='gtk-media-pause', tooltip='Pause the session',
+ )
def disable(self):
component.get('PluginManager').remove_toolbar_button(self.button)
diff --git a/deluge/plugins/Toggle/setup.py b/deluge/plugins/Toggle/setup.py
index 89fe9e35f..d3a754bdc 100644
--- a/deluge/plugins/Toggle/setup.py
+++ b/deluge/plugins/Toggle/setup.py
@@ -45,5 +45,5 @@ setup(
%s = deluge.plugins.%s:GtkUIPlugin
[deluge.plugin.web]
%s = deluge.plugins.%s:WebUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 3)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 3),
)
diff --git a/deluge/plugins/WebUi/deluge/plugins/webui/core.py b/deluge/plugins/WebUi/deluge/plugins/webui/core.py
index 2e94b7556..55d269cd6 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/core.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/core.py
@@ -33,7 +33,7 @@ log = logging.getLogger(__name__)
DEFAULT_PREFS = {
'enabled': False,
'ssl': False,
- 'port': 8112
+ 'port': 8112,
}
diff --git a/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py b/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
index 91d85dfd8..992c9b038 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
@@ -49,7 +49,7 @@ class GtkUI(GtkPluginBase):
config = {
'enabled': self.builder.get_object('enabled_checkbutton').get_active(),
'ssl': self.builder.get_object('ssl_checkbutton').get_active(),
- 'port': self.builder.get_object('port_spinbutton').get_value_as_int()
+ 'port': self.builder.get_object('port_spinbutton').get_value_as_int(),
}
client.webui.set_config(config)
@@ -75,8 +75,10 @@ class GtkUI(GtkPluginBase):
icon.set_padding(5, 5)
hbox.pack_start(icon, False, False)
- label = gtk.Label(_('The Deluge web interface is not installed, '
- 'please install the\ninterface and try again'))
+ label = gtk.Label(_(
+ 'The Deluge web interface is not installed, '
+ 'please install the\ninterface and try again',
+ ))
label.set_alignment(0, 0.5)
label.set_padding(5, 5)
hbox.pack_start(label)
diff --git a/deluge/plugins/WebUi/setup.py b/deluge/plugins/WebUi/setup.py
index 3a7b130f0..7bc61259e 100644
--- a/deluge/plugins/WebUi/setup.py
+++ b/deluge/plugins/WebUi/setup.py
@@ -42,5 +42,5 @@ setup(
%s = deluge.plugins.%s:CorePlugin
[deluge.plugin.gtkui]
%s = deluge.plugins.%s:GtkUIPlugin
- """ % ((__plugin_name__, __plugin_name__.lower()) * 2)
+ """ % ((__plugin_name__, __plugin_name__.lower()) * 2),
)
diff --git a/deluge/rencode.py b/deluge/rencode.py
index 4d281942f..7f5378dee 100644
--- a/deluge/rencode.py
+++ b/deluge/rencode.py
@@ -73,8 +73,8 @@ __all__ = ['dumps', 'loads']
py3 = sys.version_info[0] >= 3
if py3:
- long = int # pylint: disable=redefined-builtin
- unicode = str # pylint: disable=redefined-builtin
+ long = int # noqa: A001, pylint: disable=redefined-builtin
+ unicode = str # noqa: A001, pylint: disable=redefined-builtin
def int2byte(c):
return bytes([c])
@@ -434,9 +434,13 @@ def test():
f1 = struct.unpack('!f', struct.pack('!f', 25.5))[0]
f2 = struct.unpack('!f', struct.pack('!f', 29.3))[0]
f3 = struct.unpack('!f', struct.pack('!f', -0.6))[0]
- ld = (({b'a': 15, b'bb': f1, b'ccc': f2, b'': (f3, (), False, True, b'')}, (b'a', 10**20),
- tuple(range(-100000, 100000)), b'b' * 31, b'b' * 62, b'b' * 64, 2**30, 2**33, 2**62,
- 2**64, 2**30, 2**33, 2**62, 2**64, False, False, True, -1, 2, 0),)
+ ld = (
+ (
+ {b'a': 15, b'bb': f1, b'ccc': f2, b'': (f3, (), False, True, b'')}, (b'a', 10**20),
+ tuple(range(-100000, 100000)), b'b' * 31, b'b' * 62, b'b' * 64, 2**30, 2**33, 2**62,
+ 2**64, 2**30, 2**33, 2**62, 2**64, False, False, True, -1, 2, 0,
+ ),
+ )
assert loads(dumps(ld)) == ld
d = dict(zip(range(-100000, 100000), range(-100000, 100000)))
d.update({b'a': 20, 20: 40, 40: 41, f1: f2, f2: f3, f3: False, False: True, True: False})
@@ -444,15 +448,15 @@ def test():
assert loads(dumps(ld)) == ld
ld = (b'', b'a' * 10, b'a' * 100, b'a' * 1000, b'a' * 10000, b'a' * 100000, b'a' * 1000000, b'a' * 10000000)
assert loads(dumps(ld)) == ld
- ld = tuple([dict(zip(range(n), range(n))) for n in range(100)]) + (b'b',)
+ ld = tuple(dict(zip(range(n), range(n))) for n in range(100)) + (b'b',)
assert loads(dumps(ld)) == ld
- ld = tuple([dict(zip(range(n), range(-n, 0))) for n in range(100)]) + (b'b',)
+ ld = tuple(dict(zip(range(n), range(-n, 0))) for n in range(100)) + (b'b',)
assert loads(dumps(ld)) == ld
- ld = tuple([tuple(range(n)) for n in range(100)]) + (b'b',)
+ ld = tuple(tuple(range(n)) for n in range(100)) + (b'b',)
assert loads(dumps(ld)) == ld
- ld = tuple([b'a' * n for n in range(1000)]) + (b'b',)
+ ld = tuple(b'a' * n for n in range(1000)) + (b'b',)
assert loads(dumps(ld)) == ld
- ld = tuple([b'a' * n for n in range(1000)]) + (None, True, None)
+ ld = tuple(b'a' * n for n in range(1000)) + (None, True, None)
assert loads(dumps(ld)) == ld
assert loads(dumps(None)) is None
assert loads(dumps({None: None})) == {None: None}
diff --git a/deluge/scripts/create_plugin.py b/deluge/scripts/create_plugin.py
index a1dd356d2..93b6f8d95 100644
--- a/deluge/scripts/create_plugin.py
+++ b/deluge/scripts/create_plugin.py
@@ -20,10 +20,14 @@ parser = ArgumentParser()
parser.add_argument('-n', '--name', metavar='<plugin name>', required=True, help='Plugin name')
parser.add_argument('-m', '--module-name', metavar='<module name>', help='Module name')
parser.add_argument('-p', '--basepath', metavar='<path>', required=True, help='Base path')
-parser.add_argument('-a', '--author-name', metavar='<author name>', required=True,
- help='Author name,for the GPL header')
-parser.add_argument('-e', '--author-email', metavar='<author email>', required=True,
- help='Author email,for the GPL header')
+parser.add_argument(
+ '-a', '--author-name', metavar='<author name>', required=True,
+ help='Author name,for the GPL header',
+)
+parser.add_argument(
+ '-e', '--author-email', metavar='<author email>', required=True,
+ help='Author email,for the GPL header',
+)
parser.add_argument('-u', '--url', metavar='<URL>', help='Homepage URL')
parser.add_argument('-c', '--config', metavar='<Config dir>', dest='configdir', help='Location of deluge configuration')
@@ -71,7 +75,7 @@ def create_plugin():
'python_path': python_path,
'url': options.url,
'configdir': options.configdir,
- 'current_year': datetime.utcnow().year
+ 'current_year': datetime.utcnow().year,
}
filename = os.path.join(path, filename)
diff --git a/deluge/scripts/deluge_remote.py b/deluge/scripts/deluge_remote.py
index d68715d57..c1b5de7b4 100644
--- a/deluge/scripts/deluge_remote.py
+++ b/deluge/scripts/deluge_remote.py
@@ -33,20 +33,34 @@ def is_float_digit(string):
# set up command-line options
parser = OptionParser()
parser.add_option('--port', help='port for deluge backend host (default: 58846)', default='58846', dest='port')
-parser.add_option('--host', help='hostname of deluge backend to connect to (default: localhost)',
- default='localhost', dest='host')
-parser.add_option('--max_active_limit', dest='max_active_limit',
- help='sets the absolute maximum number of active torrents on the deluge backend')
-parser.add_option('--max_active_downloading', dest='max_active_downloading',
- help='sets the maximum number of active downloading torrents on the deluge backend')
-parser.add_option('--max_active_seeding', dest='max_active_seeding',
- help='sets the maximum number of active seeding torrents on the deluge backend')
-parser.add_option('--max_download_speed', help='sets the maximum global download speed on the deluge backend',
- dest='max_download_speed')
-parser.add_option('--max_upload_speed', help='sets the maximum global upload speed on the deluge backend',
- dest='max_upload_speed')
-parser.add_option('--debug', help='outputs debug information to the console', default=False, action='store_true',
- dest='debug')
+parser.add_option(
+ '--host', help='hostname of deluge backend to connect to (default: localhost)',
+ default='localhost', dest='host',
+)
+parser.add_option(
+ '--max_active_limit', dest='max_active_limit',
+ help='sets the absolute maximum number of active torrents on the deluge backend',
+)
+parser.add_option(
+ '--max_active_downloading', dest='max_active_downloading',
+ help='sets the maximum number of active downloading torrents on the deluge backend',
+)
+parser.add_option(
+ '--max_active_seeding', dest='max_active_seeding',
+ help='sets the maximum number of active seeding torrents on the deluge backend',
+)
+parser.add_option(
+ '--max_download_speed', help='sets the maximum global download speed on the deluge backend',
+ dest='max_download_speed',
+)
+parser.add_option(
+ '--max_upload_speed', help='sets the maximum global upload speed on the deluge backend',
+ dest='max_upload_speed',
+)
+parser.add_option(
+ '--debug', help='outputs debug information to the console', default=False, action='store_true',
+ dest='debug',
+)
# grab command-line options
(options, args) = parser.parse_args()
@@ -80,7 +94,8 @@ if options.max_active_seeding:
if options.max_download_speed:
if is_float_digit(options.max_download_speed) and (
- float(options.max_download_speed) >= 0.0 or float(options.max_download_speed) == -1.0):
+ float(options.max_download_speed) >= 0.0 or float(options.max_download_speed) == -1.0
+ ):
settings['max_download_speed'] = float(options.max_download_speed)
else:
sys.stderr.write('ERROR: Invalid max_download_speed parameter!\n')
@@ -88,7 +103,8 @@ if options.max_download_speed:
if options.max_upload_speed:
if is_float_digit(options.max_upload_speed) and (
- float(options.max_upload_speed) >= 0.0 or float(options.max_upload_speed) == -1.0):
+ float(options.max_upload_speed) >= 0.0 or float(options.max_upload_speed) == -1.0
+ ):
settings['max_upload_speed'] = float(options.max_upload_speed)
else:
sys.stderr.write('ERROR: Invalid max_upload_speed parameter!\n')
diff --git a/deluge/tests/basetest.py b/deluge/tests/basetest.py
index 7070e6d0a..19796dca2 100644
--- a/deluge/tests/basetest.py
+++ b/deluge/tests/basetest.py
@@ -25,9 +25,11 @@ class BaseTestCase(unittest.TestCase):
def setUp(self): # NOQA: N803
if len(component._ComponentRegistry.components) != 0:
- warnings.warn('The component._ComponentRegistry.components is not empty on test setup.\n'
- 'This is probably caused by another test that did not clean up after finishing!: %s' %
- component._ComponentRegistry.components)
+ warnings.warn(
+ 'The component._ComponentRegistry.components is not empty on test setup.\n'
+ 'This is probably caused by another test that did not clean up after finishing!: %s' %
+ component._ComponentRegistry.components,
+ )
d = maybeDeferred(self.set_up)
def on_setup_error(error):
diff --git a/deluge/tests/common.py b/deluge/tests/common.py
index 3be51f4a4..b7b38f680 100644
--- a/deluge/tests/common.py
+++ b/deluge/tests/common.py
@@ -209,8 +209,10 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
print('\n%s' % prefixed)
-def start_core(listen_port=58846, logfile=None, timeout=10, timeout_msg=None,
- custom_script='', print_stdout=True, print_stderr=True, extra_callbacks=None):
+def start_core(
+ listen_port=58846, logfile=None, timeout=10, timeout_msg=None,
+ custom_script='', print_stdout=True, print_stderr=True, extra_callbacks=None,
+):
"""Start the deluge core as a daemon.
Args:
@@ -242,7 +244,7 @@ try:
daemon = deluge.core.daemon_entry.start_daemon(skip_start=True)
%s
daemon.start()
-except:
+except Exception:
import traceback
sys.stderr.write('Exception raised:\\n %%s' %% traceback.format_exc())
""" % (config_directory, listen_port, custom_script)
@@ -254,11 +256,17 @@ except:
# Specify the triggers for daemon log output
default_core_cb['triggers'] = [
{'expr': 'Finished loading ', 'value': lambda reader, data, data_all: reader},
- {'expr': 'Could not listen on localhost:%d' % (listen_port), 'type': 'errback', # Error from libtorrent
- 'value': lambda reader, data, data_all: CannotListenError('localhost', listen_port,
- 'Could not start deluge test client!\n%s' % data)},
- {'expr': 'Traceback', 'type': 'errback',
- 'value': lambda reader, data, data_all: DelugeError('Traceback found when starting daemon:\n%s' % data)}
+ {
+ 'expr': 'Could not listen on localhost:%d' % (listen_port), 'type': 'errback', # Error from libtorrent
+ 'value': lambda reader, data, data_all: CannotListenError(
+ 'localhost', listen_port,
+ 'Could not start deluge test client!\n%s' % data,
+ ),
+ },
+ {
+ 'expr': 'Traceback', 'type': 'errback',
+ 'value': lambda reader, data, data_all: DelugeError('Traceback found when starting daemon:\n%s' % data),
+ },
]
callbacks.append(default_core_cb)
diff --git a/deluge/tests/daemon_base.py b/deluge/tests/daemon_base.py
index 7fcaa8910..ed7deea0e 100644
--- a/deluge/tests/daemon_base.py
+++ b/deluge/tests/daemon_base.py
@@ -36,8 +36,10 @@ class DaemonBase(object):
return d
@defer.inlineCallbacks
- def start_core(self, arg, custom_script='', logfile='', print_stdout=True, print_stderr=True, timeout=5,
- port_range=10, extra_callbacks=None):
+ def start_core(
+ self, arg, custom_script='', logfile='', print_stdout=True, print_stderr=True, timeout=5,
+ port_range=10, extra_callbacks=None,
+ ):
if logfile == '':
logfile = 'daemon_%s.log' % self.id()
@@ -52,12 +54,14 @@ class DaemonBase(object):
for dummy in range(port_range):
try:
- d, self.core = common.start_core(listen_port=self.listen_port, logfile=logfile,
- timeout=timeout, timeout_msg='Timeout!',
- custom_script=custom_script,
- print_stdout=print_stdout,
- print_stderr=print_stderr,
- extra_callbacks=extra_callbacks)
+ d, self.core = common.start_core(
+ listen_port=self.listen_port, logfile=logfile,
+ timeout=timeout, timeout_msg='Timeout!',
+ custom_script=custom_script,
+ print_stdout=print_stdout,
+ print_stderr=print_stderr,
+ extra_callbacks=extra_callbacks,
+ )
yield d
except CannotListenError as ex:
exception_error = ex
diff --git a/deluge/tests/test_authmanager.py b/deluge/tests/test_authmanager.py
index e62ce9364..d714a5a82 100644
--- a/deluge/tests/test_authmanager.py
+++ b/deluge/tests/test_authmanager.py
@@ -26,5 +26,5 @@ class AuthManagerTestCase(BaseTestCase):
def test_authorize(self):
self.assertEqual(
self.auth.authorize(*get_localhost_auth()),
- AUTH_LEVEL_ADMIN
+ AUTH_LEVEL_ADMIN,
)
diff --git a/deluge/tests/test_client.py b/deluge/tests/test_client.py
index a5a85ff7c..9f622ec92 100644
--- a/deluge/tests/test_client.py
+++ b/deluge/tests/test_client.py
@@ -36,8 +36,10 @@ class NoVersionSendingDaemonSSLProxy(DaemonSSLProxy):
class NoVersionSendingClient(Client):
- def connect(self, host='127.0.0.1', port=58846, username='', password='',
- skip_authentication=False):
+ def connect(
+ self, host='127.0.0.1', port=58846, username='', password='',
+ skip_authentication=False,
+ ):
self._daemon_proxy = NoVersionSendingDaemonSSLProxy()
self._daemon_proxy.set_disconnect_callback(self.__on_disconnect)
@@ -116,7 +118,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def on_failure(failure):
self.assertEqual(
failure.trap(error.BadLoginError),
- error.BadLoginError
+ error.BadLoginError,
)
self.assertEqual(failure.value.message, 'Password does not match')
self.addCleanup(client.disconnect)
@@ -131,7 +133,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def on_failure(failure):
self.assertEqual(
failure.trap(error.BadLoginError),
- error.BadLoginError
+ error.BadLoginError,
)
self.assertEqual(failure.value.message, 'Username does not exist')
self.addCleanup(client.disconnect)
@@ -146,7 +148,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def on_failure(failure):
self.assertEqual(
failure.trap(error.AuthenticationRequired),
- error.AuthenticationRequired
+ error.AuthenticationRequired,
)
self.assertEqual(failure.value.username, username)
self.addCleanup(client.disconnect)
@@ -179,13 +181,13 @@ class ClientTestCase(BaseTestCase, DaemonBase):
username, password = get_localhost_auth()
no_version_sending_client = NoVersionSendingClient()
d = no_version_sending_client.connect(
- 'localhost', self.listen_port, username=username, password=password
+ 'localhost', self.listen_port, username=username, password=password,
)
def on_failure(failure):
self.assertEqual(
failure.trap(error.IncompatibleClient),
- error.IncompatibleClient
+ error.IncompatibleClient,
)
self.addCleanup(no_version_sending_client.disconnect)
diff --git a/deluge/tests/test_common.py b/deluge/tests/test_common.py
index 846783166..9a537df79 100644
--- a/deluge/tests/test_common.py
+++ b/deluge/tests/test_common.py
@@ -116,17 +116,19 @@ class CommonTestCase(unittest.TestCase):
def test_parse_human_size(self):
from deluge.common import parse_human_size
- sizes = [('1', 1),
- ('10 bytes', 10),
- ('2048 bytes', 2048),
- ('1MiB', 2**(10 * 2)),
- ('1 MiB', 2**(10 * 2)),
- ('1 GiB', 2**(10 * 3)),
- ('1 GiB', 2**(10 * 3)),
- ('1M', 10**6),
- ('1MB', 10**6),
- ('1 GB', 10**9),
- ('1 TB', 10**12)]
+ sizes = [
+ ('1', 1),
+ ('10 bytes', 10),
+ ('2048 bytes', 2048),
+ ('1MiB', 2**(10 * 2)),
+ ('1 MiB', 2**(10 * 2)),
+ ('1 GiB', 2**(10 * 3)),
+ ('1 GiB', 2**(10 * 3)),
+ ('1M', 10**6),
+ ('1MB', 10**6),
+ ('1 GB', 10**9),
+ ('1 TB', 10**12),
+ ]
for human_size, byte_size in sizes:
parsed = parse_human_size(human_size)
@@ -135,7 +137,8 @@ class CommonTestCase(unittest.TestCase):
def test_archive_files(self):
arc_filelist = [
get_test_data_file('test.torrent'),
- get_test_data_file('deluge.png')]
+ get_test_data_file('deluge.png'),
+ ]
arc_filepath = archive_files('test-arc', arc_filelist)
with tarfile.open(arc_filepath, 'r') as tar:
diff --git a/deluge/tests/test_component.py b/deluge/tests/test_component.py
index de44fc10d..06639b0aa 100644
--- a/deluge/tests/test_component.py
+++ b/deluge/tests/test_component.py
@@ -137,7 +137,8 @@ class ComponentTestClass(BaseTestCase):
self.assertRaises(
component.ComponentAlreadyRegistered,
ComponentTester,
- 'test_register_exception_c1')
+ 'test_register_exception_c1',
+ )
def test_stop_component(self):
def on_stop(result, c):
@@ -230,11 +231,15 @@ class ComponentTestClass(BaseTestCase):
result = yield component.start()
self.assertEqual(
[(result[0][0], result[0][1].value)],
- [(defer.FAILURE,
+ [(
+ defer.FAILURE,
component.ComponentException(
'Trying to start component "%s" but it is '
'not in a stopped state. Current state: %s' %
- ('test_pause_c1', 'Paused'), ''))])
+ ('test_pause_c1', 'Paused'), '',
+ ),
+ )],
+ )
def test_shutdown(self):
def on_shutdown(result, c1):
diff --git a/deluge/tests/test_core.py b/deluge/tests/test_core.py
index abf437a80..1d71c645a 100644
--- a/deluge/tests/test_core.py
+++ b/deluge/tests/test_core.py
@@ -75,8 +75,10 @@ class TopLevelResource(Resource):
self.putChild('cookie', CookieResource())
self.putChild('partial', PartialDownload())
self.putChild('redirect', RedirectResource())
- self.putChild('ubuntu-9.04-desktop-i386.iso.torrent',
- File(common.get_test_data_file('ubuntu-9.04-desktop-i386.iso.torrent')))
+ self.putChild(
+ 'ubuntu-9.04-desktop-i386.iso.torrent',
+ File(common.get_test_data_file('ubuntu-9.04-desktop-i386.iso.torrent')),
+ )
class CoreTestCase(BaseTestCase):
@@ -152,7 +154,7 @@ class CoreTestCase(BaseTestCase):
from deluge.bencode import bdecode, bencode
with open(filename, 'rb') as _file:
info_hash = sha(bencode(bdecode(_file.read())[b'info'])).hexdigest()
- self.assertEquals(torrent_id, info_hash)
+ self.assertEqual(torrent_id, info_hash)
def test_add_torrent_file_invalid_filedump(self):
options = {}
diff --git a/deluge/tests/test_error.py b/deluge/tests/test_error.py
index 238337f35..24512c3ce 100644
--- a/deluge/tests/test_error.py
+++ b/deluge/tests/test_error.py
@@ -31,8 +31,10 @@ class ErrorTestCase(unittest.TestCase):
def test_incompatible_client(self):
version = '1.3.6'
e = deluge.error.IncompatibleClient(version)
- self.assertEqual(str(e), 'Your deluge client is not compatible with the daemon. \
-Please upgrade your client to %s' % version)
+ self.assertEqual(
+ str(e), 'Your deluge client is not compatible with the daemon. \
+Please upgrade your client to %s' % version,
+ )
def test_not_authorized_error(self):
current_level = 5
diff --git a/deluge/tests/test_files_tab.py b/deluge/tests/test_files_tab.py
index 044aa8f1e..1942171cd 100644
--- a/deluge/tests/test_files_tab.py
+++ b/deluge/tests/test_files_tab.py
@@ -85,8 +85,10 @@ class FilesTabTestCase(BaseTestCase):
return _verify_treestore(treestore.get_iter_root(), tree)
def test_files_tab(self):
- self.filestab.files_list[self.t_id] = ({'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
- {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14})
+ self.filestab.files_list[self.t_id] = (
+ {'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
+ {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14},
+ )
self.filestab.update_files()
self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '2/test_100.txt')
@@ -96,8 +98,10 @@ class FilesTabTestCase(BaseTestCase):
self.assertTrue(ret)
def test_files_tab2(self):
- self.filestab.files_list[self.t_id] = ({'index': 0, 'path': '1/1/test_10.txt', 'offset': 0, 'size': 13},
- {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14})
+ self.filestab.files_list[self.t_id] = (
+ {'index': 0, 'path': '1/1/test_10.txt', 'offset': 0, 'size': 13},
+ {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14},
+ )
self.filestab.update_files()
self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/1/test_100.txt')
@@ -107,8 +111,10 @@ class FilesTabTestCase(BaseTestCase):
self.assertTrue(ret)
def test_files_tab3(self):
- self.filestab.files_list[self.t_id] = ({'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
- {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14})
+ self.filestab.files_list[self.t_id] = (
+ {'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
+ {'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14},
+ )
self.filestab.update_files()
self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/test_100.txt')
@@ -118,20 +124,30 @@ class FilesTabTestCase(BaseTestCase):
self.assertTrue(ret)
def test_files_tab4(self):
- self.filestab.files_list[self.t_id] = ({'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
- {'index': 1, 'path': '1/test_100.txt', 'offset': 13, 'size': 14})
+ self.filestab.files_list[self.t_id] = (
+ {'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
+ {'index': 1, 'path': '1/test_100.txt', 'offset': 13, 'size': 14},
+ )
self.filestab.update_files()
self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/2/test_100.txt')
- ret = self.verify_treestore(self.filestab.treestore, [['1/', [['2/', [['test_100.txt']]],
- ['test_10.txt']]]])
+ ret = self.verify_treestore(
+ self.filestab.treestore, [[
+ '1/', [
+ ['2/', [['test_100.txt']]],
+ ['test_10.txt'],
+ ],
+ ]],
+ )
if not ret:
self.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
def test_files_tab5(self):
- self.filestab.files_list[self.t_id] = ({'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
- {'index': 1, 'path': '2/test_100.txt', 'offset': 13, 'size': 14})
+ self.filestab.files_list[self.t_id] = (
+ {'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
+ {'index': 1, 'path': '2/test_100.txt', 'offset': 13, 'size': 14},
+ )
self.filestab.update_files()
self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/test_100.txt')
diff --git a/deluge/tests/test_httpdownloader.py b/deluge/tests/test_httpdownloader.py
index 6c410ecd2..f06ea5716 100644
--- a/deluge/tests/test_httpdownloader.py
+++ b/deluge/tests/test_httpdownloader.py
@@ -43,8 +43,10 @@ class RenameResource(Resource):
def render(self, request):
filename = request.args.get('filename', ['renamed_file'])[0]
request.setHeader(b'Content-Type', b'text/plain')
- request.setHeader(b'Content-Disposition', b'attachment; filename=' +
- filename)
+ request.setHeader(
+ b'Content-Disposition', b'attachment; filename=' +
+ filename,
+ )
return b'This file should be called ' + filename
diff --git a/deluge/tests/test_json_api.py b/deluge/tests/test_json_api.py
index d1664f190..68d7b6001 100644
--- a/deluge/tests/test_json_api.py
+++ b/deluge/tests/test_json_api.py
@@ -38,7 +38,7 @@ class JSONBase(BaseTestCase, DaemonBase):
def connect_client(self, *args, **kwargs):
return client.connect(
'localhost', self.listen_port, username=kwargs.get('user', ''),
- password=kwargs.get('password', '')
+ password=kwargs.get('password', ''),
)
def disconnect_client(self, *args):
@@ -219,18 +219,24 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
daemon.rpcserver.register_object(test)
"""
from twisted.internet.defer import Deferred
- extra_callback = {'deferred': Deferred(), 'types': ['stderr'],
- 'timeout': 10,
- 'triggers': [{'expr': 'in test_raise_error',
- 'value': lambda reader, data, data_all: 'Test'}]}
+ extra_callback = {
+ 'deferred': Deferred(), 'types': ['stderr'],
+ 'timeout': 10,
+ 'triggers': [{
+ 'expr': 'in test_raise_error',
+ 'value': lambda reader, data, data_all: 'Test',
+ }],
+ }
def on_test_raise(*args):
self.assertTrue('Unhandled error in Deferred:' in self.core.stderr_out)
self.assertTrue('in test_raise_error' in self.core.stderr_out)
extra_callback['deferred'].addCallback(on_test_raise)
- d.addCallback(self.start_core, custom_script=custom_script, print_stdout=False, print_stderr=False,
- timeout=5, extra_callbacks=[extra_callback])
+ d.addCallback(
+ self.start_core, custom_script=custom_script, print_stdout=False, print_stderr=False,
+ timeout=5, extra_callbacks=[extra_callback],
+ )
d.addCallbacks(self.connect_client, self.terminate_core)
return d
@@ -257,7 +263,8 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
self.assertEqual(
response['error']['message'],
'Failure: [Failure instance: Traceback (failure with no frames):'
- " <class 'deluge.error.DelugeError'>: DelugeERROR\n]")
+ " <class 'deluge.error.DelugeError'>: DelugeERROR\n]",
+ )
self.assertEqual(response['error']['code'], 4)
request.write = write
diff --git a/deluge/tests/test_torrent.py b/deluge/tests/test_torrent.py
index ceb1d35e0..a4148d3d5 100644
--- a/deluge/tests/test_torrent.py
+++ b/deluge/tests/test_torrent.py
@@ -31,8 +31,10 @@ class TorrentTestCase(BaseTestCase):
def setup_config(self):
config_dir = common.set_tmp_config_dir()
- core_config = deluge.config.Config('core.conf', defaults=deluge.core.preferencesmanager.DEFAULT_PREFS,
- config_dir=config_dir)
+ core_config = deluge.config.Config(
+ 'core.conf', defaults=deluge.core.preferencesmanager.DEFAULT_PREFS,
+ config_dir=config_dir,
+ )
core_config.save()
def set_up(self):
@@ -77,8 +79,10 @@ class TorrentTestCase(BaseTestCase):
return atp
def test_set_prioritize_first_last_pieces(self):
- piece_indexes = [0, 1, 50, 51, 52, 110, 111, 112, 113, 200, 201, 202, 212,
- 213, 214, 215, 216, 217, 457, 458, 459, 460, 461, 462]
+ piece_indexes = [
+ 0, 1, 50, 51, 52, 110, 111, 112, 113, 200, 201, 202, 212,
+ 213, 214, 215, 216, 217, 457, 458, 459, 460, 461, 462,
+ ]
self.run_test_set_prioritize_first_last_pieces('dir_with_6_files.torrent', piece_indexes)
def run_test_set_prioritize_first_last_pieces(self, torrent_file, prioritized_piece_indexes):
@@ -169,7 +173,7 @@ class TorrentTestCase(BaseTestCase):
'num_seeds': 16777215, 'sequential_download': 0, 'announce_to_trackers': 1,
'peers': '\n\x00\x02\x0f=\xc6SC\x17]\xd8}\x7f\x00\x00\x01=\xc6', 'finished_time': 13399,
'last_upload': 13399, 'trackers': [[]], 'super_seeding': 0,
- 'file sizes': [[512000, 1411826586]], 'last_download': 13399
+ 'file sizes': [[512000, 1411826586]], 'last_download': 13399,
}
torrent_state = TorrentState(
torrent_id='2dc5d0e71a66fe69649a640d39cb00a259704973',
@@ -185,7 +189,8 @@ class TorrentTestCase(BaseTestCase):
filedump = _file.read()
resume_data = utf8_encode_structure(resume_data)
torrent_id = self.core.torrentmanager.add(
- state=torrent_state, filedump=filedump, resume_data=lt.bencode(resume_data))
+ state=torrent_state, filedump=filedump, resume_data=lt.bencode(resume_data),
+ )
torrent = self.core.torrentmanager.torrents[torrent_id]
def assert_resume_data():
diff --git a/deluge/tests/test_torrentview.py b/deluge/tests/test_torrentview.py
index 8024546a7..9cf9ce282 100644
--- a/deluge/tests/test_torrentview.py
+++ b/deluge/tests/test_torrentview.py
@@ -42,26 +42,30 @@ setup_translations()
@pytest.mark.gtkui
class TorrentviewTestCase(BaseTestCase):
- default_column_index = ['filter', 'torrent_id', 'dirty', '#',
- 'Name',
- 'Size', 'Downloaded', 'Uploaded', 'Remaining',
- 'Progress',
- 'Seeds', 'Peers', 'Seeds:Peers',
- 'Down Speed', 'Up Speed', 'Down Limit', 'Up Limit',
- 'ETA', 'Ratio', 'Avail',
- 'Added', 'Completed', 'Complete Seen',
- 'Tracker', 'Download Folder', 'Owner', 'Shared']
- default_liststore_columns = [bool, str, bool, int,
- str, str, # Name
- TYPE_UINT64, TYPE_UINT64, TYPE_UINT64, TYPE_UINT64,
- float, str, # Progress
- int, int, int, int, float, # Seeds, Peers
- int, int, float, float,
- int, float, float, # ETA, Ratio, Avail
- int, int, int,
- str, str, # Tracker
- str, str,
- bool] # shared
+ default_column_index = [
+ 'filter', 'torrent_id', 'dirty', '#',
+ 'Name',
+ 'Size', 'Downloaded', 'Uploaded', 'Remaining',
+ 'Progress',
+ 'Seeds', 'Peers', 'Seeds:Peers',
+ 'Down Speed', 'Up Speed', 'Down Limit', 'Up Limit',
+ 'ETA', 'Ratio', 'Avail',
+ 'Added', 'Completed', 'Complete Seen',
+ 'Tracker', 'Download Folder', 'Owner', 'Shared',
+ ]
+ default_liststore_columns = [
+ bool, str, bool, int,
+ str, str, # Name
+ TYPE_UINT64, TYPE_UINT64, TYPE_UINT64, TYPE_UINT64,
+ float, str, # Progress
+ int, int, int, int, float, # Seeds, Peers
+ int, int, float, float,
+ int, float, float, # ETA, Ratio, Avail
+ int, int, int,
+ str, str, # Tracker
+ str, str,
+ bool,
+ ] # shared
def set_up(self):
if libs_available is False:
@@ -89,10 +93,14 @@ class TorrentviewTestCase(BaseTestCase):
# Add a text column
test_col = 'Test column'
self.torrentview.add_text_column(test_col, status_field=['label'])
- self.assertEqual(len(self.torrentview.liststore_columns),
- len(TorrentviewTestCase.default_liststore_columns) + 1)
- self.assertEqual(len(self.torrentview.column_index),
- len(TorrentviewTestCase.default_column_index) + 1)
+ self.assertEqual(
+ len(self.torrentview.liststore_columns),
+ len(TorrentviewTestCase.default_liststore_columns) + 1,
+ )
+ self.assertEqual(
+ len(self.torrentview.column_index),
+ len(TorrentviewTestCase.default_column_index) + 1,
+ )
self.assertEqual(self.torrentview.column_index[-1], test_col)
self.assertEqual(self.torrentview.columns[test_col].column_indices, [32])
@@ -106,10 +114,14 @@ class TorrentviewTestCase(BaseTestCase):
test_col2 = 'Test column2'
self.torrentview.add_text_column(test_col2, status_field=['label2'])
- self.assertEqual(len(self.torrentview.liststore_columns),
- len(TorrentviewTestCase.default_liststore_columns) + 2)
- self.assertEqual(len(self.torrentview.column_index),
- len(TorrentviewTestCase.default_column_index) + 2)
+ self.assertEqual(
+ len(self.torrentview.liststore_columns),
+ len(TorrentviewTestCase.default_liststore_columns) + 2,
+ )
+ self.assertEqual(
+ len(self.torrentview.column_index),
+ len(TorrentviewTestCase.default_column_index) + 2,
+ )
# test_col
self.assertEqual(self.torrentview.column_index[-2], test_col)
self.assertEqual(self.torrentview.columns[test_col].column_indices, [32])
@@ -140,10 +152,14 @@ class TorrentviewTestCase(BaseTestCase):
# Remove test_col
self.torrentview.remove_column(test_col)
- self.assertEqual(len(self.torrentview.liststore_columns),
- len(TorrentviewTestCase.default_liststore_columns) + 1)
- self.assertEqual(len(self.torrentview.column_index),
- len(TorrentviewTestCase.default_column_index) + 1)
+ self.assertEqual(
+ len(self.torrentview.liststore_columns),
+ len(TorrentviewTestCase.default_liststore_columns) + 1,
+ )
+ self.assertEqual(
+ len(self.torrentview.column_index),
+ len(TorrentviewTestCase.default_column_index) + 1,
+ )
self.assertEqual(self.torrentview.column_index[-1], test_col2)
self.assertEqual(self.torrentview.columns[test_col2].column_indices, [32])
@@ -159,10 +175,14 @@ class TorrentviewTestCase(BaseTestCase):
# Add a column with multiple column types
test_col3 = 'Test column3'
self.torrentview.add_progress_column(test_col3, status_field=['progress', 'label3'], col_types=[float, str])
- self.assertEqual(len(self.torrentview.liststore_columns),
- len(TorrentviewTestCase.default_liststore_columns) + 2)
- self.assertEqual(len(self.torrentview.column_index),
- len(TorrentviewTestCase.default_column_index) + 1)
+ self.assertEqual(
+ len(self.torrentview.liststore_columns),
+ len(TorrentviewTestCase.default_liststore_columns) + 2,
+ )
+ self.assertEqual(
+ len(self.torrentview.column_index),
+ len(TorrentviewTestCase.default_column_index) + 1,
+ )
self.assertEqual(self.torrentview.column_index[-1], test_col3)
self.assertEqual(self.torrentview.columns[test_col3].column_indices, [32, 33])
diff --git a/deluge/tests/test_transfer.py b/deluge/tests/test_transfer.py
index 0ac13b303..8940394a1 100644
--- a/deluge/tests/test_transfer.py
+++ b/deluge/tests/test_transfer.py
@@ -118,10 +118,12 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
"""
self.transfer = TransferTestClass()
self.msg1 = (0, 1, {'key_int': 1242429423}, {'key_str': b'some string'}, {'key_bool': True})
- self.msg2 = (2, 3, {'key_float': 12424.29423},
- {'key_unicode': 'some string'},
- {'key_dict_with_tuple': {'key_tuple': (1, 2, 3)}},
- {'keylist': [4, '5', 6.7]})
+ self.msg2 = (
+ 2, 3, {'key_float': 12424.29423},
+ {'key_unicode': 'some string'},
+ {'key_dict_with_tuple': {'key_tuple': (1, 2, 3)}},
+ {'keylist': [4, '5', 6.7]},
+ )
self.msg1_expected_compressed_base64 = 'RAAAADF4nDvKwJjenp1aGZ+ZV+Lgxfv9PYRXXFLU'\
'XZyfm6oAZGTmpad3gAST8vNznAEAJhSQ'
diff --git a/deluge/tests/test_ui_common.py b/deluge/tests/test_ui_common.py
index 69f6411d0..32ad3037f 100644
--- a/deluge/tests/test_ui_common.py
+++ b/deluge/tests/test_ui_common.py
@@ -33,11 +33,23 @@ class UICommonTestCase(unittest.TestCase):
ti = TorrentInfo(filename)
files = ti.files_tree['unicode_filenames']
- self.assertTrue((b'\xe3\x83\x86\xe3\x82\xaf\xe3\x82\xb9\xe3\x83\xbb\xe3\x83'
- b'\x86\xe3\x82\xaf\xe3\x82\xb5\xe3\x83\xb3.mkv').decode('utf8') in files)
- self.assertTrue((b'\xd0\x9c\xd0\xb8\xd1\x85\xd0\xb0\xd0\xb8\xd0\xbb \xd0\x93'
- b'\xd0\xbe\xd1\x80\xd0\xb1\xd0\xb0\xd1\x87\xd1\x91\xd0\xb2.mkv').decode('utf8') in files)
+ self.assertTrue(
+ (
+ b'\xe3\x83\x86\xe3\x82\xaf\xe3\x82\xb9\xe3\x83\xbb\xe3\x83'
+ b'\x86\xe3\x82\xaf\xe3\x82\xb5\xe3\x83\xb3.mkv'
+ ).decode('utf8') in files,
+ )
+ self.assertTrue(
+ (
+ b'\xd0\x9c\xd0\xb8\xd1\x85\xd0\xb0\xd0\xb8\xd0\xbb \xd0\x93'
+ b'\xd0\xbe\xd1\x80\xd0\xb1\xd0\xb0\xd1\x87\xd1\x91\xd0\xb2.mkv'
+ ).decode('utf8') in files,
+ )
self.assertTrue(b"Alisher ibn G'iyosiddin Navoiy.mkv".decode('utf8') in files)
self.assertTrue(b'Ascii title.mkv'.decode('utf8') in files)
- self.assertTrue((b'\xe0\xa6\xb8\xe0\xa7\x81\xe0\xa6\x95\xe0\xa7\x81\xe0\xa6\xae\xe0\xa6\xbe'
- b'\xe0\xa6\xb0 \xe0\xa6\xb0\xe0\xa6\xbe\xe0\xa7\x9f.mkv').decode('utf8') in files)
+ self.assertTrue(
+ (
+ b'\xe0\xa6\xb8\xe0\xa7\x81\xe0\xa6\x95\xe0\xa7\x81\xe0\xa6\xae\xe0\xa6\xbe'
+ b'\xe0\xa6\xb0 \xe0\xa6\xb0\xe0\xa6\xbe\xe0\xa7\x9f.mkv'
+ ).decode('utf8') in files,
+ )
diff --git a/deluge/tests/test_ui_entry.py b/deluge/tests/test_ui_entry.py
index e3d69ddea..130dbe192 100644
--- a/deluge/tests/test_ui_entry.py
+++ b/deluge/tests/test_ui_entry.py
@@ -60,7 +60,7 @@ class StringFileDescriptor(object):
class UIBaseTestCase(object):
def __init__(self):
- self.var = dict()
+ self.var = {}
def set_up(self):
common.set_tmp_config_dir()
@@ -339,8 +339,10 @@ class ConsoleUIWithDaemonBaseTestCase(UIWithDaemonBaseTestCase):
@defer.inlineCallbacks
def test_console_command_status(self):
username, password = get_localhost_auth()
- self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['--port'] + ['58900'] + ['--username'] +
- [username] + ['--password'] + [password] + ['status'])
+ self.patch(
+ sys, 'argv', self.var['sys_arg_cmd'] + ['--port'] + ['58900'] + ['--username'] +
+ [username] + ['--password'] + [password] + ['status'],
+ )
fd = StringFileDescriptor(sys.stdout)
self.patch(sys, 'stdout', fd)
diff --git a/deluge/tests/test_web_api.py b/deluge/tests/test_web_api.py
index 7baabc056..9b68b225c 100644
--- a/deluge/tests/test_web_api.py
+++ b/deluge/tests/test_web_api.py
@@ -72,8 +72,8 @@ class WebAPITestCase(WebServerTestBase):
'233f23632af0a74748bc5dd1d8717564748877baa16420e6898e17e8aa365e6e': {
'login': 'skrot',
'expires': 1460030877.0,
- 'level': 10
- }
+ 'level': 10,
+ },
}
self.deluge_web.web_api.set_config(config)
web_config = component.get('DelugeWeb').config.config
@@ -147,7 +147,10 @@ class WebAPITestCase(WebServerTestBase):
ret['contents'], {
'azcvsupdater_2.6.2.jar': {
'priority': 4, 'index': 0, 'offset': 0, 'progress': 0.0, 'path':
- 'azcvsupdater_2.6.2.jar', 'type': 'file', 'size': 307949}})
+ 'azcvsupdater_2.6.2.jar', 'type': 'file', 'size': 307949,
+ },
+ },
+ )
@defer.inlineCallbacks
def test_download_torrent_from_url(self):
@@ -170,7 +173,10 @@ class WebAPITestCase(WebServerTestBase):
d = yield agent.request(
b'POST',
b'http://127.0.0.1:%s/json' % self.webserver_listen_port,
- Headers({b'User-Agent': [b'Twisted Web Client Example'],
- b'Content-Type': [b'application/json']}),
- FileBodyProducer(BytesIO(bad_body)))
+ Headers({
+ b'User-Agent': [b'Twisted Web Client Example'],
+ b'Content-Type': [b'application/json'],
+ }),
+ FileBodyProducer(BytesIO(bad_body)),
+ )
yield d
diff --git a/deluge/tests/test_webserver.py b/deluge/tests/test_webserver.py
index ef2c0a773..a74be89a7 100644
--- a/deluge/tests/test_webserver.py
+++ b/deluge/tests/test_webserver.py
@@ -42,12 +42,16 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
# UnicodeDecodeError: 'utf8' codec can't decode byte 0xe5 in position 0: invalid continuation byte
filename = get_test_data_file('filehash_field.torrent')
input_file = '{"params": ["%s"], "method": "web.get_torrent_info", "id": 22}' % filename
- headers = {'User-Agent': ['Twisted Web Client Example'],
- 'Content-Type': ['application/json']}
+ headers = {
+ 'User-Agent': ['Twisted Web Client Example'],
+ 'Content-Type': ['application/json'],
+ }
url = 'http://127.0.0.1:%s/json' % self.webserver_listen_port
- d = yield agent.request(b'POST', url.encode('utf-8'), Headers(utf8_encode_structure(headers)),
- FileBodyProducer(BytesIO(input_file.encode('utf-8'))))
+ d = yield agent.request(
+ b'POST', url.encode('utf-8'), Headers(utf8_encode_structure(headers)),
+ FileBodyProducer(BytesIO(input_file.encode('utf-8'))),
+ )
try:
body = yield twisted.web.client.readBody(d)
except AttributeError:
diff --git a/deluge/tests/twisted/plugins/delugereporter.py b/deluge/tests/twisted/plugins/delugereporter.py
index a1b1d04f9..e0f4fc7d1 100644
--- a/deluge/tests/twisted/plugins/delugereporter.py
+++ b/deluge/tests/twisted/plugins/delugereporter.py
@@ -28,12 +28,14 @@ class _Reporter(object):
self.klass = klass
-deluge = _Reporter('Deluge reporter that suppresses Stacktrace from TODO tests',
- 'twisted.plugins.delugereporter',
- description='Deluge Reporter',
- longOpt='deluge-reporter',
- shortOpt=None,
- klass='DelugeReporter')
+deluge = _Reporter(
+ 'Deluge reporter that suppresses Stacktrace from TODO tests',
+ 'twisted.plugins.delugereporter',
+ description='Deluge Reporter',
+ longOpt='deluge-reporter',
+ shortOpt=None,
+ klass='DelugeReporter',
+)
class DelugeReporter(TreeReporter):
diff --git a/deluge/ui/Win32IconImagePlugin.py b/deluge/ui/Win32IconImagePlugin.py
index b1a0cf6e1..caa653590 100644
--- a/deluge/ui/Win32IconImagePlugin.py
+++ b/deluge/ui/Win32IconImagePlugin.py
@@ -100,7 +100,7 @@ class Win32IcoFile(object):
def sizes(self):
"""Get a list of all available icon sizes and color depths."""
- return set((h['width'], h['height']) for h in self.entry)
+ return {(h['width'], h['height']) for h in self.entry}
def get_image(self, size, bpp=False):
"""Get an image from the icon
@@ -171,7 +171,7 @@ class Win32IcoFile(object):
im.size, # (w, h)
alpha_bytes, # source chars
'raw', # raw decoder
- ('L', 0, -1) # 8bpp inverted, unpadded, reversed
+ ('L', 0, -1), # 8bpp inverted, unpadded, reversed
)
# apply mask image as alpha channel
@@ -198,7 +198,7 @@ class Win32IcoFile(object):
im.size, # (w, h)
mask_data, # source chars
'raw', # raw decoder
- ('1;I', w // 8, -1) # 1bpp inverted, padded, reversed
+ ('1;I', w // 8, -1), # 1bpp inverted, padded, reversed
)
# now we have two images, im is XOR image and mask is AND image
@@ -215,7 +215,8 @@ class Win32IcoFile(object):
def __repr__(self):
s = 'Microsoft Icon: %d images (max %dx%d %dbpp)' % (
len(self.entry), self.entry[0]['width'], self.entry[0]['height'],
- self.entry[0]['bpp'])
+ self.entry[0]['bpp'],
+ )
return s
# end Win32IcoFile
diff --git a/deluge/ui/baseargparser.py b/deluge/ui/baseargparser.py
index 3f116c9eb..6bedc8093 100644
--- a/deluge/ui/baseargparser.py
+++ b/deluge/ui/baseargparser.py
@@ -170,26 +170,48 @@ class BaseArgParser(argparse.ArgumentParser):
self.process_arg_group = False
self.group = self.add_argument_group(_('Common Options'))
if common_help:
- self.group.add_argument('-h', '--help', action=HelpAction,
- help=_('Print this help message'))
- self.group.add_argument('-V', '--version', action='version', version='%(prog)s ' + get_version(),
- help=_('Print version information'))
- self.group.add_argument('-v', action='version', version='%(prog)s ' + get_version(),
- help=argparse.SUPPRESS) # Deprecated arg
- self.group.add_argument('-c', '--config', metavar='<config>',
- help=_('Set the config directory path'))
- self.group.add_argument('-l', '--logfile', metavar='<logfile>',
- help=_('Output to specified logfile instead of stdout'))
- self.group.add_argument('-L', '--loglevel', choices=[l for k in deluge.log.levels for l in (k, k.upper())],
- help=_('Set the log level (none, error, warning, info, debug)'), metavar='<level>')
- self.group.add_argument('--logrotate', nargs='?', const='2M', metavar='<max-size>',
- help=_('Enable logfile rotation, with optional maximum logfile size, '
- 'default: %(const)s (Logfile rotation count is 5)'))
- self.group.add_argument('-q', '--quiet', action='store_true',
- help=_('Quieten logging output (Same as `--loglevel none`)'))
- self.group.add_argument('--profile', metavar='<profile-file>', nargs='?', default=False,
- help=_('Profile %(prog)s with cProfile. Outputs to stdout '
- 'unless a filename is specified'))
+ self.group.add_argument(
+ '-h', '--help', action=HelpAction,
+ help=_('Print this help message'),
+ )
+ self.group.add_argument(
+ '-V', '--version', action='version', version='%(prog)s ' + get_version(),
+ help=_('Print version information'),
+ )
+ self.group.add_argument(
+ '-v', action='version', version='%(prog)s ' + get_version(),
+ help=argparse.SUPPRESS,
+ ) # Deprecated arg
+ self.group.add_argument(
+ '-c', '--config', metavar='<config>',
+ help=_('Set the config directory path'),
+ )
+ self.group.add_argument(
+ '-l', '--logfile', metavar='<logfile>',
+ help=_('Output to specified logfile instead of stdout'),
+ )
+ self.group.add_argument(
+ '-L', '--loglevel', choices=[l for k in deluge.log.levels for l in (k, k.upper())],
+ help=_('Set the log level (none, error, warning, info, debug)'), metavar='<level>',
+ )
+ self.group.add_argument(
+ '--logrotate', nargs='?', const='2M', metavar='<max-size>',
+ help=_(
+ 'Enable logfile rotation, with optional maximum logfile size, '
+ 'default: %(const)s (Logfile rotation count is 5)',
+ ),
+ )
+ self.group.add_argument(
+ '-q', '--quiet', action='store_true',
+ help=_('Quieten logging output (Same as `--loglevel none`)'),
+ )
+ self.group.add_argument(
+ '--profile', metavar='<profile-file>', nargs='?', default=False,
+ help=_(
+ 'Profile %(prog)s with cProfile. Outputs to stdout '
+ 'unless a filename is specified',
+ ),
+ )
def parse_args(self, args=None):
"""Parse UI arguments and handle common and process group options.
@@ -251,8 +273,10 @@ class BaseArgParser(argparse.ArgumentParser):
logrotate = common.parse_human_size(options.logrotate)
# Setup the logger
- deluge.log.setup_logger(level=options.loglevel, filename=options.logfile, filemode=logfile_mode,
- logrotate=logrotate, output_stream=self.log_stream)
+ deluge.log.setup_logger(
+ level=options.loglevel, filename=options.logfile, filemode=logfile_mode,
+ logrotate=logrotate, output_stream=self.log_stream,
+ )
if options.config:
if not set_config_dir(options.config):
@@ -300,14 +324,24 @@ class BaseArgParser(argparse.ArgumentParser):
self.process_arg_group = True
self.group = self.add_argument_group(_('Process Control Options'))
- self.group.add_argument('-P', '--pidfile', metavar='<pidfile>', action='store',
- help=_('Pidfile to store the process id'))
+ self.group.add_argument(
+ '-P', '--pidfile', metavar='<pidfile>', action='store',
+ help=_('Pidfile to store the process id'),
+ )
if not common.windows_check():
- self.group.add_argument('-d', '--do-not-daemonize', dest='donotdaemonize', action='store_true',
- help=_('Do not daemonize (fork) this process'))
- self.group.add_argument('-f', '--fork', dest='donotdaemonize', action='store_false',
- help=argparse.SUPPRESS) # Deprecated arg
- self.group.add_argument('-U', '--user', metavar='<user>', action='store',
- help=_('Change to this user on startup (Requires root)'))
- self.group.add_argument('-g', '--group', metavar='<group>', action='store',
- help=_('Change to this group on startup (Requires root)'))
+ self.group.add_argument(
+ '-d', '--do-not-daemonize', dest='donotdaemonize', action='store_true',
+ help=_('Do not daemonize (fork) this process'),
+ )
+ self.group.add_argument(
+ '-f', '--fork', dest='donotdaemonize', action='store_false',
+ help=argparse.SUPPRESS,
+ ) # Deprecated arg
+ self.group.add_argument(
+ '-U', '--user', metavar='<user>', action='store',
+ help=_('Change to this user on startup (Requires root)'),
+ )
+ self.group.add_argument(
+ '-g', '--group', metavar='<group>', action='store',
+ help=_('Change to this group on startup (Requires root)'),
+ )
diff --git a/deluge/ui/client.py b/deluge/ui/client.py
index 172a6d68b..ac9b9f99a 100644
--- a/deluge/ui/client.py
+++ b/deluge/ui/client.py
@@ -98,8 +98,10 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
log.debug('Received invalid message: type is not tuple')
return
if len(request) < 3:
- log.debug('Received invalid message: number of items in '
- 'response is %s', len(request))
+ log.debug(
+ 'Received invalid message: number of items in '
+ 'response is %s', len(request),
+ )
return
message_type = request[0]
@@ -163,8 +165,10 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
log.debug(msg)
except Exception:
import traceback
- log.error('Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s',
- request[2], traceback.format_exc())
+ log.error(
+ 'Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s',
+ request[2], traceback.format_exc(),
+ )
d.errback(exception)
del self.__rpc_requests[request_id]
@@ -195,17 +199,23 @@ class DelugeRPCClientFactory(ClientFactory):
self.event_handlers = event_handlers
def startedConnecting(self, connector): # NOQA: N802
- log.debug('Connecting to daemon at "%s:%s"...',
- connector.host, connector.port)
+ log.debug(
+ 'Connecting to daemon at "%s:%s"...',
+ connector.host, connector.port,
+ )
def clientConnectionFailed(self, connector, reason): # NOQA: N802
- log.debug('Connection to daemon at "%s:%s" failed: %s',
- connector.host, connector.port, reason.value)
+ log.debug(
+ 'Connection to daemon at "%s:%s" failed: %s',
+ connector.host, connector.port, reason.value,
+ )
self.daemon.connect_deferred.errback(reason)
def clientConnectionLost(self, connector, reason): # NOQA: N802
- log.debug('Connection lost to daemon at "%s:%s" reason: %s',
- connector.host, connector.port, reason.value)
+ log.debug(
+ 'Connection lost to daemon at "%s:%s" reason: %s',
+ connector.host, connector.port, reason.value,
+ )
self.daemon.host = None
self.daemon.port = None
self.daemon.username = None
@@ -262,9 +272,11 @@ class DaemonSSLProxy(DaemonProxy):
log.debug('sslproxy.connect()')
self.host = host
self.port = port
- self.__connector = reactor.connectSSL(self.host, self.port,
- self.__factory,
- ssl.ClientContextFactory())
+ self.__connector = reactor.connectSSL(
+ self.host, self.port,
+ self.__factory,
+ ssl.ClientContextFactory(),
+ )
self.connect_deferred = defer.Deferred()
self.daemon_info_deferred = defer.Deferred()
@@ -384,8 +396,10 @@ class DaemonSSLProxy(DaemonProxy):
log.debug('%s.authenticate: %s', self.__class__.__name__, username)
login_deferred = defer.Deferred()
d = self.call('daemon.login', username, password, client_version=get_version())
- d.addCallbacks(self.__on_login, self.__on_login_fail, callbackArgs=[username, login_deferred],
- errbackArgs=[login_deferred])
+ d.addCallbacks(
+ self.__on_login, self.__on_login_fail, callbackArgs=[username, login_deferred],
+ errbackArgs=[login_deferred],
+ )
return login_deferred
def __on_login(self, result, username, login_deferred):
@@ -396,7 +410,8 @@ class DaemonSSLProxy(DaemonProxy):
if self.__factory.event_handlers:
self.call('daemon.set_event_interest', list(self.__factory.event_handlers))
self.call('core.get_auth_levels_mappings').addCallback(
- self.__on_auth_levels_mappings)
+ self.__on_auth_levels_mappings,
+ )
login_deferred.callback(result)
@@ -434,9 +449,11 @@ class DaemonStandaloneProxy(DaemonProxy):
self.host = 'localhost'
self.port = 58846
# Running in standalone mode, it's safe to import auth level
- from deluge.core.authmanager import (AUTH_LEVEL_ADMIN,
- AUTH_LEVELS_MAPPING,
- AUTH_LEVELS_MAPPING_REVERSE)
+ from deluge.core.authmanager import (
+ AUTH_LEVEL_ADMIN,
+ AUTH_LEVELS_MAPPING,
+ AUTH_LEVELS_MAPPING_REVERSE,
+ )
self.username = 'localclient'
self.authentication_level = AUTH_LEVEL_ADMIN
self.auth_levels_mapping = AUTH_LEVELS_MAPPING
@@ -528,8 +545,10 @@ class Client(object):
self.disconnect_callback = None
self.__started_standalone = False
- def connect(self, host='127.0.0.1', port=58846, username='', password='',
- skip_authentication=False):
+ def connect(
+ self, host='127.0.0.1', port=58846, username='', password='',
+ skip_authentication=False,
+ ):
"""
Connects to a daemon process.
@@ -635,8 +654,11 @@ class Client(object):
from errno import ENOENT
if ex.errno == ENOENT:
log.error(
- _('Deluge cannot find the `deluged` executable, check that '
- 'the deluged package is installed, or added to your PATH.'))
+ _(
+ 'Deluge cannot find the `deluged` executable, check that '
+ 'the deluged package is installed, or added to your PATH.',
+ ),
+ )
else:
log.exception(ex)
except Exception as ex:
diff --git a/deluge/ui/common.py b/deluge/ui/common.py
index 1767a3a97..71bbd0468 100644
--- a/deluge/ui/common.py
+++ b/deluge/ui/common.py
@@ -134,14 +134,14 @@ TORRENT_DATA_FIELD = {
'pieces':
{'name': _('Pieces'), 'status': ['num_pieces', 'piece_length']},
'seed_rank':
- {'name': _('Seed Rank'), 'status': ['seed_rank']}
+ {'name': _('Seed Rank'), 'status': ['seed_rank']},
}
TRACKER_STATUS_TRANSLATION = [
_('Error'),
_('Warning'),
_('Announce OK'),
- _('Announce Sent')
+ _('Announce Sent'),
]
PREFS_CATOG_TRANS = {
@@ -154,7 +154,7 @@ PREFS_CATOG_TRANS = {
'cache': _('Cache'),
'other': _('Other'),
'daemon': _('Daemon'),
- 'plugins': _('Plugins')
+ 'plugins': _('Plugins'),
}
FILE_PRIORITY = {
@@ -178,7 +178,7 @@ del _
DISK_CACHE_KEYS = [
'disk.num_blocks_read', 'disk.num_blocks_written', 'disk.num_read_ops', 'disk.num_write_ops',
'disk.num_blocks_cache_hits', 'read_hit_ratio', 'write_hit_ratio', 'disk.disk_blocks_in_use',
- 'disk.read_cache_blocks'
+ 'disk.read_cache_blocks',
]
@@ -279,13 +279,13 @@ class TorrentInfo(object):
'type': 'file',
'index': 0,
'length': self.__m_metadata['info']['length'],
- 'download': True
- }
- }
+ 'download': True,
+ },
+ },
}
else:
self.__m_files_tree = {
- self.__m_name: (0, self.__m_metadata['info']['length'], True)
+ self.__m_name: (0, self.__m_metadata['info']['length'], True),
}
self.__m_files = []
@@ -298,13 +298,13 @@ class TorrentInfo(object):
self.__m_files.append({
'path': f['path'],
'size': f['length'],
- 'download': True
+ 'download': True,
})
else:
self.__m_files.append({
'path': self.__m_name,
'size': self.__m_metadata['info']['length'],
- 'download': True
+ 'download': True,
})
def as_dict(self, *keys):
@@ -315,7 +315,7 @@ class TorrentInfo(object):
:param keys: a number of key strings
:type keys: string
"""
- return dict([(key, getattr(self, key)) for key in keys])
+ return {key: getattr(self, key) for key in keys}
@property
def name(self):
@@ -400,7 +400,7 @@ class FileTree2(object):
if child is None:
parent['contents'][directory] = {
'type': 'dir',
- 'contents': {}
+ 'contents': {},
}
parent = parent['contents'][directory]
return parent, path
@@ -411,12 +411,12 @@ class FileTree2(object):
parent, path = get_parent(path)
parent['contents'][path] = {
'type': 'dir',
- 'contents': {}
+ 'contents': {},
}
else:
parent, path = get_parent(path)
parent['contents'][path] = {
- 'type': 'file'
+ 'type': 'file',
}
def get_tree(self):
@@ -443,13 +443,13 @@ class FileTree2(object):
full_path = os.path.join(parent_path, path).replace('\\', '/')
if directory['contents'][path]['type'] == 'dir':
directory['contents'][path] = callback(
- full_path, directory['contents'][path]
- ) or directory['contents'][path]
+ full_path, directory['contents'][path],
+ ) or directory['contents'][path]
walk(directory['contents'][path], full_path)
else:
directory['contents'][path] = callback(
- full_path, directory['contents'][path]
- ) or directory['contents'][path]
+ full_path, directory['contents'][path],
+ ) or directory['contents'][path]
walk(self.tree, '')
def __str__(self):
diff --git a/deluge/ui/console/cmdline/commands/__init__.py b/deluge/ui/console/cmdline/commands/__init__.py
index 01bb8385e..628fae597 100644
--- a/deluge/ui/console/cmdline/commands/__init__.py
+++ b/deluge/ui/console/cmdline/commands/__init__.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from deluge.ui.console.cmdline.command import BaseCommand
diff --git a/deluge/ui/console/cmdline/commands/add.py b/deluge/ui/console/cmdline/commands/add.py
index e6282d9a2..47f9d5689 100644
--- a/deluge/ui/console/cmdline/commands/add.py
+++ b/deluge/ui/console/cmdline/commands/add.py
@@ -35,8 +35,10 @@ class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-p', '--path', dest='path', help=_('download folder for torrent'))
- parser.add_argument('torrents', metavar='<torrent>', nargs='+',
- help=_('One or more torrent files, URLs or magnet URIs'))
+ parser.add_argument(
+ 'torrents', metavar='<torrent>', nargs='+',
+ help=_('One or more torrent files, URLs or magnet URIs'),
+ )
def handle(self, options):
self.console = component.get('ConsoleUI')
@@ -62,11 +64,13 @@ class Command(BaseCommand):
if deluge.common.is_url(torrent):
self.console.write('{!info!}Attempting to add torrent from url: %s' % torrent)
deferreds.append(client.core.add_torrent_url(torrent, t_options).addCallback(on_success).addErrback(
- on_fail))
+ on_fail,
+ ))
elif deluge.common.is_magnet(torrent):
self.console.write('{!info!}Attempting to add torrent from magnet uri: %s' % torrent)
deferreds.append(client.core.add_torrent_magnet(torrent, t_options).addCallback(on_success).addErrback(
- on_fail))
+ on_fail,
+ ))
else:
# Just a file
if urlparse(torrent).scheme == 'file':
@@ -85,7 +89,7 @@ class Command(BaseCommand):
deferreds.append(
client.core.add_torrent_file_async(
filename, filedump, t_options,
- ).addCallback(on_success).addErrback(on_fail)
+ ).addCallback(on_success).addErrback(on_fail),
)
return defer.DeferredList(deferreds)
diff --git a/deluge/ui/console/cmdline/commands/info.py b/deluge/ui/console/cmdline/commands/info.py
index b2cc69618..44b1e4f27 100644
--- a/deluge/ui/console/cmdline/commands/info.py
+++ b/deluge/ui/console/cmdline/commands/info.py
@@ -59,7 +59,7 @@ STATUS_KEYS = [
'total_uploaded',
'total_payload_download',
'total_payload_upload',
- 'time_added'
+ 'time_added',
]
# Add filter specific state to torrent states
@@ -82,21 +82,33 @@ class Command(BaseCommand):
"""
def add_arguments(self, parser):
- parser.add_argument('-v', '--verbose', action='store_true', default=False, dest='verbose',
- help=_('Show more information per torrent.'))
- parser.add_argument('-d', '--detailed', action='store_true', default=False, dest='detailed',
- help=_('Show more detailed information including files and peers.'))
- parser.add_argument('-s', '--state', action='store', dest='state',
- help=_('Show torrents with state STATE: %s.' % (', '.join(STATES))))
+ parser.add_argument(
+ '-v', '--verbose', action='store_true', default=False, dest='verbose',
+ help=_('Show more information per torrent.'),
+ )
+ parser.add_argument(
+ '-d', '--detailed', action='store_true', default=False, dest='detailed',
+ help=_('Show more detailed information including files and peers.'),
+ )
+ parser.add_argument(
+ '-s', '--state', action='store', dest='state',
+ help=_('Show torrents with state STATE: %s.' % (', '.join(STATES))),
+ )
parser.add_argument('--sort', action='store', type=str, default='', dest='sort', help=self.sort_help)
- parser.add_argument('--sort-reverse', action='store', type=str, default='', dest='sort_rev',
- help=_('Same as --sort but items are in reverse order.'))
- parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='*',
- help=_('One or more torrent ids. If none is given, list all'))
+ parser.add_argument(
+ '--sort-reverse', action='store', type=str, default='', dest='sort_rev',
+ help=_('Same as --sort but items are in reverse order.'),
+ )
+ parser.add_argument(
+ 'torrent_ids', metavar='<torrent-id>', nargs='*',
+ help=_('One or more torrent ids. If none is given, list all'),
+ )
def add_subparser(self, subparsers):
- parser = subparsers.add_parser(self.name, prog=self.name, help=self.__doc__,
- description=self.__doc__, epilog=self.epilog)
+ parser = subparsers.add_parser(
+ self.name, prog=self.name, help=self.__doc__,
+ description=self.__doc__, epilog=self.epilog,
+ )
self.add_arguments(parser)
def handle(self, options):
@@ -251,7 +263,8 @@ class Command(BaseCommand):
colors.state_color['Seeding'],
fspeed(peer['up_speed']),
colors.state_color['Downloading'],
- fspeed(peer['down_speed']))
+ fspeed(peer['down_speed']),
+ )
s += '\n'
self.console.write(s[:-1])
@@ -280,10 +293,12 @@ class Command(BaseCommand):
if status['state'] != 'Seeding':
s += sep
s += '{!info!}Down Speed: {!input!}%s' % fspeed(
- status['download_payload_rate'], shortform=True)
+ status['download_payload_rate'], shortform=True,
+ )
s += sep
s += '{!info!}Up Speed: {!input!}%s' % fspeed(
- status['upload_payload_rate'], shortform=True)
+ status['upload_payload_rate'], shortform=True,
+ )
self.console.write(s)
if status['state'] in ('Seeding', 'Downloading', 'Queued'):
@@ -294,7 +309,8 @@ class Command(BaseCommand):
s += '{!info!}Availability: {!input!}%.2f' % status['distributed_copies']
s += sep
s += '{!info!}Seed Rank: {!input!}%s' % f_seedrank_dash(
- status['seed_rank'], status['seeding_time'])
+ status['seed_rank'], status['seeding_time'],
+ )
self.console.write(s)
total_done = fsize(status['total_done'], shortform=True)
@@ -321,7 +337,8 @@ class Command(BaseCommand):
s = '{!info!}Last Transfer: {!input!}%s' % format_time(status['time_since_transfer'])
s += sep
s += '{!info!}Complete Seen: {!input!}%s' % format_date_never(
- status['last_seen_complete'])
+ status['last_seen_complete'],
+ )
self.console.write(s)
s = '{!info!}Tracker: {!input!}%s' % status['tracker_host']
@@ -366,14 +383,18 @@ class Command(BaseCommand):
dl_info += '%s' % ftotal_sized(status['all_time_download'], status['total_payload_download'])
if status['download_payload_rate'] > 0:
- dl_info += ' @ %s%s' % (down_color, fspeed(
- status['download_payload_rate'], shortform=True))
+ dl_info += ' @ %s%s' % (
+ down_color,
+ fspeed(status['download_payload_rate'], shortform=True),
+ )
ul_info = ' {!info!}UL: {!input!}'
ul_info += '%s' % ftotal_sized(status['total_uploaded'], status['total_payload_upload'])
if status['upload_payload_rate'] > 0:
- ul_info += ' @ %s%s' % (up_color, fspeed(
- status['upload_payload_rate'], shortform=True))
+ ul_info += ' @ %s%s' % (
+ up_color,
+ fspeed(status['upload_payload_rate'], shortform=True),
+ )
eta = ' {!info!}ETA: {!magenta!}%s' % format_time(status['eta'])
diff --git a/deluge/ui/console/cmdline/commands/manage.py b/deluge/ui/console/cmdline/commands/manage.py
index 73be5b938..8f8349679 100644
--- a/deluge/ui/console/cmdline/commands/manage.py
+++ b/deluge/ui/console/cmdline/commands/manage.py
@@ -33,7 +33,7 @@ torrent_options = {
'stop_ratio': float,
'remove_at_ratio': bool,
'move_completed': bool,
- 'move_completed_path': str
+ 'move_completed_path': str,
}
@@ -43,8 +43,10 @@ class Command(BaseCommand):
usage = _('Usage: manage <torrent-id> [--set <key> <value>] [<key> [<key>...] ]')
def add_arguments(self, parser):
- parser.add_argument('torrent', metavar='<torrent>',
- help=_('an expression matched against torrent ids and torrent names'))
+ parser.add_argument(
+ 'torrent', metavar='<torrent>',
+ help=_('an expression matched against torrent ids and torrent names'),
+ )
set_group = parser.add_argument_group('setting a value')
set_group.add_argument('-s', '--set', action='store', metavar='<key>', help=_('set value for this key'))
set_group.add_argument('values', metavar='<value>', nargs='+', help=_('Value to set'))
diff --git a/deluge/ui/console/cmdline/commands/pause.py b/deluge/ui/console/cmdline/commands/pause.py
index cda220404..fa5ba7d13 100644
--- a/deluge/ui/console/cmdline/commands/pause.py
+++ b/deluge/ui/console/cmdline/commands/pause.py
@@ -21,8 +21,10 @@ class Command(BaseCommand):
usage = 'pause [ * | <torrent-id> [<torrent-id> ...] ]'
def add_arguments(self, parser):
- parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
- help=_('One or more torrent ids. Use "*" to pause all torrents'))
+ parser.add_argument(
+ 'torrent_ids', metavar='<torrent-id>', nargs='+',
+ help=_('One or more torrent ids. Use "*" to pause all torrents'),
+ )
def handle(self, options):
self.console = component.get('ConsoleUI')
diff --git a/deluge/ui/console/cmdline/commands/plugin.py b/deluge/ui/console/cmdline/commands/plugin.py
index 72f313b45..dd910d9da 100644
--- a/deluge/ui/console/cmdline/commands/plugin.py
+++ b/deluge/ui/console/cmdline/commands/plugin.py
@@ -20,14 +20,20 @@ class Command(BaseCommand):
"""Manage plugins"""
def add_arguments(self, parser):
- parser.add_argument('-l', '--list', action='store_true', default=False, dest='list',
- help=_('Lists available plugins'))
- parser.add_argument('-s', '--show', action='store_true', default=False, dest='show',
- help=_('Shows enabled plugins'))
+ parser.add_argument(
+ '-l', '--list', action='store_true', default=False, dest='list',
+ help=_('Lists available plugins'),
+ )
+ parser.add_argument(
+ '-s', '--show', action='store_true', default=False, dest='show',
+ help=_('Shows enabled plugins'),
+ )
parser.add_argument('-e', '--enable', dest='enable', nargs='+', help=_('Enables a plugin'))
parser.add_argument('-d', '--disable', dest='disable', nargs='+', help=_('Disables a plugin'))
- parser.add_argument('-r', '--reload', action='store_true', default=False, dest='reload',
- help=_('Reload list of available plugins'))
+ parser.add_argument(
+ '-r', '--reload', action='store_true', default=False, dest='reload',
+ help=_('Reload list of available plugins'),
+ )
parser.add_argument('-i', '--install', help=_('Install a plugin from an .egg file'))
def handle(self, options):
diff --git a/deluge/ui/console/cmdline/commands/resume.py b/deluge/ui/console/cmdline/commands/resume.py
index cf130edb2..8a2632264 100644
--- a/deluge/ui/console/cmdline/commands/resume.py
+++ b/deluge/ui/console/cmdline/commands/resume.py
@@ -21,8 +21,10 @@ class Command(BaseCommand):
usage = _('Usage: resume [ * | <torrent-id> [<torrent-id> ...] ]')
def add_arguments(self, parser):
- parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
- help=_('One or more torrent ids. Use "*" to resume all torrents'))
+ parser.add_argument(
+ 'torrent_ids', metavar='<torrent-id>', nargs='+',
+ help=_('One or more torrent ids. Use "*" to resume all torrents'),
+ )
def handle(self, options):
self.console = component.get('ConsoleUI')
diff --git a/deluge/ui/console/cmdline/commands/rm.py b/deluge/ui/console/cmdline/commands/rm.py
index 3e97178f4..a2d431c4d 100644
--- a/deluge/ui/console/cmdline/commands/rm.py
+++ b/deluge/ui/console/cmdline/commands/rm.py
@@ -25,10 +25,14 @@ class Command(BaseCommand):
aliases = ['del']
def add_arguments(self, parser):
- parser.add_argument('--remove_data', action='store_true', default=False,
- help=_('Also removes the torrent data'))
- parser.add_argument('-c', '--confirm', action='store_true', default=False,
- help=_('List the matching torrents without removing.'))
+ parser.add_argument(
+ '--remove_data', action='store_true', default=False,
+ help=_('Also removes the torrent data'),
+ )
+ parser.add_argument(
+ '-c', '--confirm', action='store_true', default=False,
+ help=_('List the matching torrents without removing.'),
+ )
parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids'))
def handle(self, options):
@@ -36,9 +40,11 @@ class Command(BaseCommand):
torrent_ids = self.console.match_torrents(options.torrent_ids)
if not options.confirm:
- self.console.write('{!info!}%d %s %s{!info!}' % (len(torrent_ids),
- _n('torrent', 'torrents', len(torrent_ids)),
- _n('match', 'matches', len(torrent_ids))))
+ self.console.write('{!info!}%d %s %s{!info!}' % (
+ len(torrent_ids),
+ _n('torrent', 'torrents', len(torrent_ids)),
+ _n('match', 'matches', len(torrent_ids)),
+ ))
for t_id in torrent_ids:
name = self.console.get_torrent_name(t_id)
self.console.write('* %-50s (%s)' % (name, t_id))
diff --git a/deluge/ui/console/cmdline/commands/status.py b/deluge/ui/console/cmdline/commands/status.py
index e1d5e37fa..5f6c3fe94 100644
--- a/deluge/ui/console/cmdline/commands/status.py
+++ b/deluge/ui/console/cmdline/commands/status.py
@@ -26,11 +26,17 @@ class Command(BaseCommand):
"""Shows various status information from the daemon"""
def add_arguments(self, parser):
- parser.add_argument('-r', '--raw', action='store_true', default=False, dest='raw',
- help=_('Raw values for upload/download rates (without KiB/s suffix)'
- '(useful for scripts that want to do their own parsing)'))
- parser.add_argument('-n', '--no-torrents', action='store_false', default=True, dest='show_torrents',
- help=_('Do not show torrent status (Improves command speed)'))
+ parser.add_argument(
+ '-r', '--raw', action='store_true', default=False, dest='raw',
+ help=_(
+ 'Raw values for upload/download rates (without KiB/s suffix)'
+ '(useful for scripts that want to do their own parsing)',
+ ),
+ )
+ parser.add_argument(
+ '-n', '--no-torrents', action='store_false', default=True, dest='show_torrents',
+ help=_('Do not show torrent status (Improves command speed)'),
+ )
def handle(self, options):
self.console = component.get('ConsoleUI')
diff --git a/deluge/ui/console/cmdline/commands/update_tracker.py b/deluge/ui/console/cmdline/commands/update_tracker.py
index 22121151b..f0848bced 100644
--- a/deluge/ui/console/cmdline/commands/update_tracker.py
+++ b/deluge/ui/console/cmdline/commands/update_tracker.py
@@ -22,8 +22,10 @@ class Command(BaseCommand):
aliases = ['reannounce']
def add_arguments(self, parser):
- parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
- help='One or more torrent ids. "*" updates all torrents')
+ parser.add_argument(
+ 'torrent_ids', metavar='<torrent-id>', nargs='+',
+ help='One or more torrent ids. "*" updates all torrents',
+ )
def handle(self, options):
self.console = component.get('ConsoleUI')
diff --git a/deluge/ui/console/console.py b/deluge/ui/console/console.py
index c95d675d0..893caf548 100644
--- a/deluge/ui/console/console.py
+++ b/deluge/ui/console/console.py
@@ -30,8 +30,12 @@ log = logging.getLogger(__name__)
def load_commands(command_dir):
def get_command(name):
- command = getattr(__import__('deluge.ui.console.cmdline.commands.%s' % name,
- {}, {}, ['Command']), 'Command')()
+ command = getattr(
+ __import__(
+ 'deluge.ui.console.cmdline.commands.%s' % name,
+ {}, {}, ['Command'],
+ ), 'Command',
+ )()
command._name = name
return command
@@ -67,29 +71,45 @@ class Console(UI):
def __init__(self, *args, **kwargs):
super(Console, self).__init__('console', *args, log_stream=LogStream(), **kwargs)
- group = self.parser.add_argument_group(_('Console Options'),
- _('These daemon connect options will be '
- 'used for commands, or if console ui autoconnect is enabled.'))
- group.add_argument('-d', '--daemon', metavar='<ip_addr>', dest='daemon_addr',
- help=_('Deluge daemon IP address to connect to (default 127.0.0.1)'), default='127.0.0.1')
- group.add_argument('-p', '--port', metavar='<port>', dest='daemon_port', type=int,
- help=_('Deluge daemon port to connect to (default 58846)'), default='58846')
- group.add_argument('-U', '--username', metavar='<user>', dest='daemon_user',
- help=_('Deluge daemon username to use when connecting'))
- group.add_argument('-P', '--password', metavar='<pass>', dest='daemon_pass',
- help=_('Deluge daemon password to use when connecting'))
+ group = self.parser.add_argument_group(
+ _('Console Options'),
+ _(
+ 'These daemon connect options will be '
+ 'used for commands, or if console ui autoconnect is enabled.',
+ ),
+ )
+ group.add_argument(
+ '-d', '--daemon', metavar='<ip_addr>', dest='daemon_addr',
+ help=_('Deluge daemon IP address to connect to (default 127.0.0.1)'), default='127.0.0.1',
+ )
+ group.add_argument(
+ '-p', '--port', metavar='<port>', dest='daemon_port', type=int,
+ help=_('Deluge daemon port to connect to (default 58846)'), default='58846',
+ )
+ group.add_argument(
+ '-U', '--username', metavar='<user>', dest='daemon_user',
+ help=_('Deluge daemon username to use when connecting'),
+ )
+ group.add_argument(
+ '-P', '--password', metavar='<pass>', dest='daemon_pass',
+ help=_('Deluge daemon password to use when connecting'),
+ )
# To properly print help message for the console commands ( e.g. deluge-console info -h),
# we add a subparser for each command which will trigger the help/usage when given
from deluge.ui.console.parser import ConsoleCommandParser # import here because (see top)
- self.console_parser = ConsoleCommandParser(parents=[self.parser], add_help=False, prog=self.parser.prog,
- description='Starts the Deluge console interface',
- formatter_class=lambda prog:
- DelugeTextHelpFormatter(prog, max_help_position=33, width=90))
+ self.console_parser = ConsoleCommandParser(
+ parents=[self.parser], add_help=False, prog=self.parser.prog,
+ description='Starts the Deluge console interface',
+ formatter_class=lambda prog:
+ DelugeTextHelpFormatter(prog, max_help_position=33, width=90),
+ )
self.parser.subparser = self.console_parser
self.console_parser.base_parser = self.parser
- subparsers = self.console_parser.add_subparsers(title=_('Console Commands'), help=_('Description'),
- description=_('The following console commands are available:'),
- metavar=_('Command'), dest='command')
+ subparsers = self.console_parser.add_subparsers(
+ title=_('Console Commands'), help=_('Description'),
+ description=_('The following console commands are available:'),
+ metavar=_('Command'), dest='command',
+ )
from deluge.ui.console import UI_PATH # Must import here
self.console_cmds = load_commands(os.path.join(UI_PATH, 'cmdline', 'commands'))
for cmd in sorted(self.console_cmds):
@@ -116,5 +136,7 @@ class Console(UI):
log.exception(ex)
raise
- return deluge.common.run_profiled(run, self.options, output_file=self.options.profile,
- do_profile=self.options.profile)
+ return deluge.common.run_profiled(
+ run, self.options, output_file=self.options.profile,
+ do_profile=self.options.profile,
+ )
diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py
index 01e2ac5e9..c3d6a131a 100644
--- a/deluge/ui/console/main.py
+++ b/deluge/ui/console/main.py
@@ -49,7 +49,7 @@ DEFAULT_CONSOLE_PREFS = {
'sidebar_width': 25,
'separate_complete': True,
'move_selection': True,
- 'columns': {}
+ 'columns': {},
},
'addtorrents': {
'show_misc_files': False, # TODO: Showing/hiding this
@@ -63,7 +63,7 @@ DEFAULT_CONSOLE_PREFS = {
'third_tab_lists_all': False,
'torrents_per_tab_press': 15,
'save_command_history': True,
- }
+ },
}
@@ -207,8 +207,10 @@ Please use commands from the command line, e.g.:\n
if not self.interactive and options.parsed_cmds[0].command == 'connect':
d = commander.exec_command(options.parsed_cmds.pop(0))
else:
- log.info('connect: host=%s, port=%s, username=%s, password=%s',
- options.daemon_addr, options.daemon_port, options.daemon_user, options.daemon_pass)
+ log.info(
+ 'connect: host=%s, port=%s, username=%s, password=%s',
+ options.daemon_addr, options.daemon_port, options.daemon_user, options.daemon_pass,
+ )
d = client.connect(options.daemon_addr, options.daemon_port, options.daemon_user, options.daemon_pass)
d.addCallback(on_connect)
d.addErrback(on_connect_fail)
@@ -279,8 +281,10 @@ Please use commands from the command line, e.g.:\n
# which can cause issues as the popup's screen will not be destroyed.
# This can lead to the popup border being visible for short periods
# while the current modes' screen is repainted.
- log.error('Mode "%s" still has popups available after being paused.'
- ' Ensure all popups are removed on pause!', mode.popup.title)
+ log.error(
+ 'Mode "%s" still has popups available after being paused.'
+ ' Ensure all popups are removed on pause!', mode.popup.title,
+ )
d.addCallback(on_mode_paused, self.active_mode)
reactor.removeReader(self.active_mode)
@@ -418,8 +422,10 @@ Please use commands from the command line, e.g.:\n
def tab_complete_path(self, line, path_type='file', ext='', sort='name', dirs_first=True):
if self.interactive and isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine):
- return self.active_mode.tab_complete_path(line, path_type=path_type, ext=ext,
- sort=sort, dirs_first=dirs_first)
+ return self.active_mode.tab_complete_path(
+ line, path_type=path_type, ext=ext,
+ sort=sort, dirs_first=dirs_first,
+ )
def on_client_disconnect(self):
component.stop()
@@ -474,10 +480,12 @@ Please use commands from the command line, e.g.:\n
config['language'] = DEFAULT_CONSOLE_PREFS['language']
# Migrate column settings
- columns = ['queue', 'size', 'state', 'progress', 'seeds', 'peers', 'downspeed', 'upspeed',
- 'eta', 'ratio', 'avail', 'added', 'tracker', 'savepath', 'downloaded', 'uploaded',
- 'remaining', 'owner', 'downloading_time', 'seeding_time', 'completed', 'seeds_peers_ratio',
- 'complete_seen', 'down_limit', 'up_limit', 'shared', 'name']
+ columns = [
+ 'queue', 'size', 'state', 'progress', 'seeds', 'peers', 'downspeed', 'upspeed',
+ 'eta', 'ratio', 'avail', 'added', 'tracker', 'savepath', 'downloaded', 'uploaded',
+ 'remaining', 'owner', 'downloading_time', 'seeding_time', 'completed', 'seeds_peers_ratio',
+ 'complete_seen', 'down_limit', 'up_limit', 'shared', 'name',
+ ]
column_name_mapping = {
'downspeed': 'download_speed',
'upspeed': 'upload_speed',
@@ -487,7 +495,7 @@ Please use commands from the command line, e.g.:\n
'complete_seen': 'last_seen_complete',
'down_limit': 'max_download_speed',
'up_limit': 'max_upload_speed',
- 'downloading_time': 'active_time'
+ 'downloading_time': 'active_time',
}
from deluge.ui.console.modes.torrentlist.torrentview import default_columns
diff --git a/deluge/ui/console/modes/add_util.py b/deluge/ui/console/modes/add_util.py
index 3f5027cee..4fd4702a7 100644
--- a/deluge/ui/console/modes/add_util.py
+++ b/deluge/ui/console/modes/add_util.py
@@ -81,5 +81,5 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
filedump = base64.encodestring(_file.read())
client.core.add_torrent_file_async(
- filename, filedump, t_options
+ filename, filedump, t_options,
).addCallback(success_cb, f, ress).addErrback(fail_cb, f, ress)
diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py
index 62b7d6a74..fde6d728b 100644
--- a/deluge/ui/console/modes/basemode.py
+++ b/deluge/ui/console/modes/basemode.py
@@ -156,8 +156,10 @@ class BaseMode(CursesStdIO, component.Component):
return add_string(row, string, screen, self.encoding, **kwargs)
- def draw_statusbars(self, top_row=0, bottom_row=-1, topbar=None, bottombar=None,
- bottombar_help=True, scr=None):
+ def draw_statusbars(
+ self, top_row=0, bottom_row=-1, topbar=None, bottombar=None,
+ bottombar_help=True, scr=None,
+ ):
self.add_string(top_row, topbar if topbar else self.statusbars.topbar, scr=scr)
bottombar = bottombar if bottombar else self.statusbars.bottombar
if bottombar_help:
@@ -289,10 +291,12 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=' ', tri
screen.addstr(row, col, s, color)
except curses.error as ex:
import traceback
- log.warn('FAILED on call screen.addstr(%s, %s, "%s", %s) - max_y: %s, max_x: %s, '
- 'curses.LINES: %s, curses.COLS: %s, Error: %s, trace:\n%s',
- row, col, s, color, max_y, max_x, curses.LINES, curses.COLS, ex,
- ''.join(traceback.format_stack(limit=5)))
+ log.warn(
+ 'FAILED on call screen.addstr(%s, %s, "%s", %s) - max_y: %s, max_x: %s, '
+ 'curses.LINES: %s, curses.COLS: %s, Error: %s, trace:\n%s',
+ row, col, s, color, max_y, max_x, curses.LINES, curses.COLS, ex,
+ ''.join(traceback.format_stack(limit=5)),
+ )
col += len(s)
@@ -335,5 +339,7 @@ def move_cursor(screen, row, col):
screen.move(row, col)
except curses.error as ex:
import traceback
- log.warn('Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: %s\nStack: %s',
- row, col, curses.LINES, curses.COLS, ex, ''.join(traceback.format_stack()))
+ log.warn(
+ 'Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: %s\nStack: %s',
+ row, col, curses.LINES, curses.COLS, ex, ''.join(traceback.format_stack()),
+ )
diff --git a/deluge/ui/console/modes/cmdline.py b/deluge/ui/console/modes/cmdline.py
index f2fe6e8a4..683f6be17 100644
--- a/deluge/ui/console/modes/cmdline.py
+++ b/deluge/ui/console/modes/cmdline.py
@@ -130,7 +130,7 @@ class CmdLine(BaseMode, Commander):
config_dir = deluge.configmanager.get_config_dir()
self.history_file = [
os.path.join(config_dir, 'cmd_line.hist1'),
- os.path.join(config_dir, 'cmd_line.hist2')
+ os.path.join(config_dir, 'cmd_line.hist2'),
]
self._hf_lines = [0, 0]
if self.console_config['cmdline']['save_command_history']:
@@ -645,7 +645,8 @@ class CmdLine(BaseMode, Commander):
match = possible_matches[i]
self.write(match.replace(r'\ ', ' '))
self.write('{!error!}And %i more (%i/%i). Press <tab> to view more' % (
- left - max_list, hits - 1, pages))
+ left - max_list, hits - 1, pages,
+ ))
else:
self.tab_count = 0
for match in possible_matches[listed:]:
@@ -786,15 +787,18 @@ class CmdLine(BaseMode, Commander):
if not empty and torrent_id.startswith(line):
# Highlight the matching part
text = '{!info!}%s{!input!}%s - "%s"' % (
- torrent_id[:line_len], torrent_id[line_len:], torrent_name)
+ torrent_id[:line_len], torrent_id[line_len:], torrent_name,
+ )
possible_matches.append(text)
if torrent_name.startswith(line):
text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
- escaped_name[:line_len], escaped_name[line_len:], torrent_id)
+ escaped_name[:line_len], escaped_name[line_len:], torrent_id,
+ )
possible_matches.append(text)
elif torrent_name.lower().startswith(line.lower()):
text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
- escaped_name[:line_len], escaped_name[line_len:], torrent_id)
+ escaped_name[:line_len], escaped_name[line_len:], torrent_id,
+ )
possible_matches2.append(text)
return possible_matches + possible_matches2
diff --git a/deluge/ui/console/modes/connectionmanager.py b/deluge/ui/console/modes/connectionmanager.py
index 4157c938f..000360390 100644
--- a/deluge/ui/console/modes/connectionmanager.py
+++ b/deluge/ui/console/modes/connectionmanager.py
@@ -41,10 +41,12 @@ class ConnectionManager(BaseMode, PopupsHandler):
selected_index = self.popup.current_selection() if self.popup else None
popup = SelectablePopup(
- self, _('Select Host'), self._host_selected, border_off_west=1, active_wrap=True)
+ self, _('Select Host'), self._host_selected, border_off_west=1, active_wrap=True,
+ )
popup.add_header(
"{!white,black,bold!}'Q'=%s, 'a'=%s, 'D'=%s" %
- (_('Quit'), _('Add Host'), _('Delete Host')), space_below=True)
+ (_('Quit'), _('Add Host'), _('Delete Host')), space_below=True,
+ )
self.push_popup(popup, clear=True)
for host_entry in self.hostlist.get_hosts_info():
@@ -91,8 +93,10 @@ class ConnectionManager(BaseMode, PopupsHandler):
if not result or kwargs.get('close', False):
self.pop_popup()
else:
- self.add_host(result['hostname']['value'], result['port']['value'],
- result['username']['value'], result['password']['value'])
+ self.add_host(
+ result['hostname']['value'], result['port']['value'],
+ result['username']['value'], result['password']['value'],
+ )
def add_popup(self):
self.inlist = False
@@ -101,7 +105,8 @@ class ConnectionManager(BaseMode, PopupsHandler):
_('Add Host (Up & Down arrows to navigate, Esc to cancel)'),
border_off_north=1,
border_off_east=1,
- close_cb=self._do_add)
+ close_cb=self._do_add,
+ )
popup.add_text_input('hostname', _('Hostname:'))
popup.add_text_input('port', _('Port:'))
popup.add_text_input('username', _('Username:'))
diff --git a/deluge/ui/console/modes/preferences/preference_panes.py b/deluge/ui/console/modes/preferences/preference_panes.py
index b1c7894f5..731ac067b 100644
--- a/deluge/ui/console/modes/preferences/preference_panes.py
+++ b/deluge/ui/console/modes/preferences/preference_panes.py
@@ -158,29 +158,45 @@ class InterfacePane(BasePreferencePane):
def create_pane(self, core_conf, console_config):
self.add_header(_('General options'))
- self.add_checked_input('ring_bell', _('Ring system bell when a download finishes'),
- console_config['ring_bell'])
+ self.add_checked_input(
+ 'ring_bell', _('Ring system bell when a download finishes'),
+ console_config['ring_bell'],
+ )
self.add_header('Console UI', space_above=True)
- self.add_checked_input('separate_complete',
- _('List complete torrents after incomplete regardless of sorting order'),
- console_config['torrentview']['separate_complete'])
- self.add_checked_input('move_selection', _('Move selection when moving torrents in the queue'),
- console_config['torrentview']['move_selection'])
+ self.add_checked_input(
+ 'separate_complete',
+ _('List complete torrents after incomplete regardless of sorting order'),
+ console_config['torrentview']['separate_complete'],
+ )
+ self.add_checked_input(
+ 'move_selection', _('Move selection when moving torrents in the queue'),
+ console_config['torrentview']['move_selection'],
+ )
from deluge.ui.translations_util import get_languages
langs = get_languages()
langs.insert(0, ('', 'System Default'))
- self.add_combo_input('language', _('Language'),
- langs, default=console_config['language'])
+ self.add_combo_input(
+ 'language', _('Language'),
+ langs, default=console_config['language'],
+ )
self.add_header(_('Command Line Mode'), space_above=True)
- self.add_checked_input('ignore_duplicate_lines', _('Do not store duplicate input in history'),
- console_config['cmdline']['ignore_duplicate_lines'])
- self.add_checked_input('save_command_history', _('Store and load command line history in command line mode'),
- console_config['cmdline']['save_command_history'])
+ self.add_checked_input(
+ 'ignore_duplicate_lines', _('Do not store duplicate input in history'),
+ console_config['cmdline']['ignore_duplicate_lines'],
+ )
+ self.add_checked_input(
+ 'save_command_history', _('Store and load command line history in command line mode'),
+ console_config['cmdline']['save_command_history'],
+ )
self.add_header('')
- self.add_checked_input('third_tab_lists_all', _('Third tab lists all remaining torrents in command line mode'),
- console_config['cmdline']['third_tab_lists_all'])
- self.add_int_spin_input('torrents_per_tab_press', _('Torrents per tab press'),
- console_config['cmdline']['torrents_per_tab_press'], min_val=5, max_val=10000)
+ self.add_checked_input(
+ 'third_tab_lists_all', _('Third tab lists all remaining torrents in command line mode'),
+ console_config['cmdline']['third_tab_lists_all'],
+ )
+ self.add_int_spin_input(
+ 'torrents_per_tab_press', _('Torrents per tab press'),
+ console_config['cmdline']['torrents_per_tab_press'], min_val=5, max_val=10000,
+ )
class DownloadsPane(BasePreferencePane):
@@ -191,27 +207,45 @@ class DownloadsPane(BasePreferencePane):
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
self.add_header(_('Folders'))
- self.add_text_input('download_location', '%s:' % _('Download To'), core_conf['download_location'],
- complete=True, activate_input=True, col='+1')
- cmptxt = TextInput(self.preferences, 'move_completed_path', None, self.move, self.pane_width,
- core_conf['move_completed_path'], False)
- self.add_checkedplus_input('move_completed', '%s:' % _('Move completed to'),
- cmptxt, core_conf['move_completed'])
- copytxt = TextInput(self.preferences, 'torrentfiles_location', None, self.move, self.pane_width,
- core_conf['torrentfiles_location'], False)
- self.add_checkedplus_input('copy_torrent_file', '%s:' % _('Copy of .torrent files to'), copytxt,
- core_conf['copy_torrent_file'])
- self.add_checked_input('del_copy_torrent_file', _('Delete copy of torrent file on remove'),
- core_conf['del_copy_torrent_file'])
+ self.add_text_input(
+ 'download_location', '%s:' % _('Download To'), core_conf['download_location'],
+ complete=True, activate_input=True, col='+1',
+ )
+ cmptxt = TextInput(
+ self.preferences, 'move_completed_path', None, self.move, self.pane_width,
+ core_conf['move_completed_path'], False,
+ )
+ self.add_checkedplus_input(
+ 'move_completed', '%s:' % _('Move completed to'),
+ cmptxt, core_conf['move_completed'],
+ )
+ copytxt = TextInput(
+ self.preferences, 'torrentfiles_location', None, self.move, self.pane_width,
+ core_conf['torrentfiles_location'], False,
+ )
+ self.add_checkedplus_input(
+ 'copy_torrent_file', '%s:' % _('Copy of .torrent files to'), copytxt,
+ core_conf['copy_torrent_file'],
+ )
+ self.add_checked_input(
+ 'del_copy_torrent_file', _('Delete copy of torrent file on remove'),
+ core_conf['del_copy_torrent_file'],
+ )
self.add_header(_('Options'), space_above=True)
- self.add_checked_input('prioritize_first_last_pieces', ('Prioritize first and last pieces of torrent'),
- core_conf['prioritize_first_last_pieces'])
- self.add_checked_input('sequential_download', _('Sequential download'),
- core_conf['sequential_download'])
+ self.add_checked_input(
+ 'prioritize_first_last_pieces', ('Prioritize first and last pieces of torrent'),
+ core_conf['prioritize_first_last_pieces'],
+ )
+ self.add_checked_input(
+ 'sequential_download', _('Sequential download'),
+ core_conf['sequential_download'],
+ )
self.add_checked_input('add_paused', _('Add Paused'), core_conf['add_paused'])
- self.add_checked_input('pre_allocate_storage', _('Pre-Allocate disk space'),
- core_conf['pre_allocate_storage'])
+ self.add_checked_input(
+ 'pre_allocate_storage', _('Pre-Allocate disk space'),
+ core_conf['pre_allocate_storage'],
+ )
class NetworkPane(BasePreferencePane):
@@ -222,26 +256,38 @@ class NetworkPane(BasePreferencePane):
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
self.add_header(_('Incomming Ports'))
- inrand = self.add_checked_input('random_port', 'Use Random Ports Active Port: %d'
- % self.preferences.active_port,
- core_conf['random_port'])
+ inrand = self.add_checked_input(
+ 'random_port', 'Use Random Ports Active Port: %d'
+ % self.preferences.active_port,
+ core_conf['random_port'],
+ )
listen_ports = core_conf['listen_ports']
- self.infrom = self.add_int_spin_input('listen_ports_from', ' %s:' % _('From'),
- value=listen_ports[0], min_val=0, max_val=65535)
+ self.infrom = self.add_int_spin_input(
+ 'listen_ports_from', ' %s:' % _('From'),
+ value=listen_ports[0], min_val=0, max_val=65535,
+ )
self.infrom.set_depend(inrand, inverse=True)
- self.into = self.add_int_spin_input('listen_ports_to', ' %s:' % _('To'),
- value=listen_ports[1], min_val=0, max_val=65535)
+ self.into = self.add_int_spin_input(
+ 'listen_ports_to', ' %s:' % _('To'),
+ value=listen_ports[1], min_val=0, max_val=65535,
+ )
self.into.set_depend(inrand, inverse=True)
self.add_header(_('Outgoing Ports'), space_above=True)
- outrand = self.add_checked_input('random_outgoing_ports', _('Use Random Ports'),
- core_conf['random_outgoing_ports'])
+ outrand = self.add_checked_input(
+ 'random_outgoing_ports', _('Use Random Ports'),
+ core_conf['random_outgoing_ports'],
+ )
out_ports = core_conf['outgoing_ports']
- self.outfrom = self.add_int_spin_input('out_ports_from', ' %s:' % _('From'),
- value=out_ports[0], min_val=0, max_val=65535)
+ self.outfrom = self.add_int_spin_input(
+ 'out_ports_from', ' %s:' % _('From'),
+ value=out_ports[0], min_val=0, max_val=65535,
+ )
self.outfrom.set_depend(outrand, inverse=True)
- self.outto = self.add_int_spin_input('out_ports_to', ' %s:' % _('To'),
- value=out_ports[1], min_val=0, max_val=65535)
+ self.outto = self.add_int_spin_input(
+ 'out_ports_to', ' %s:' % _('To'),
+ value=out_ports[1], min_val=0, max_val=65535,
+ )
self.outto.set_depend(outrand, inverse=True)
self.add_header(_('Incoming Interface'), space_above=True)
@@ -269,12 +315,18 @@ class NetworkPane(BasePreferencePane):
self.add_checked_input('dht', 'DHT', core_conf['dht'])
self.add_header(_('Encryption'), space_above=True)
- self.add_select_input('enc_in_policy', '%s:' % _('Inbound'), [_('Forced'), _('Enabled'), _('Disabled')],
- [0, 1, 2], core_conf['enc_in_policy'], active_default=True, col='+1')
- self.add_select_input('enc_out_policy', '%s:' % _('Outbound'), [_('Forced'), _('Enabled'), _('Disabled')],
- [0, 1, 2], core_conf['enc_out_policy'], active_default=True)
- self.add_select_input('enc_level', '%s:' % _('Level'), [_('Handshake'), _('Full Stream'), _('Either')],
- [0, 1, 2], core_conf['enc_level'], active_default=True)
+ self.add_select_input(
+ 'enc_in_policy', '%s:' % _('Inbound'), [_('Forced'), _('Enabled'), _('Disabled')],
+ [0, 1, 2], core_conf['enc_in_policy'], active_default=True, col='+1',
+ )
+ self.add_select_input(
+ 'enc_out_policy', '%s:' % _('Outbound'), [_('Forced'), _('Enabled'), _('Disabled')],
+ [0, 1, 2], core_conf['enc_out_policy'], active_default=True,
+ )
+ self.add_select_input(
+ 'enc_level', '%s:' % _('Level'), [_('Handshake'), _('Full Stream'), _('Either')],
+ [0, 1, 2], core_conf['enc_level'], active_default=True,
+ )
class BandwidthPane(BasePreferencePane):
@@ -285,31 +337,55 @@ class BandwidthPane(BasePreferencePane):
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
self.add_header(_('Global Bandwidth Usage'))
- self.add_int_spin_input('max_connections_global', '%s:' % _('Maximum Connections'),
- core_conf['max_connections_global'], min_val=-1, max_val=9000)
- self.add_int_spin_input('max_upload_slots_global', '%s:' % _('Maximum Upload Slots'),
- core_conf['max_upload_slots_global'], min_val=-1, max_val=9000)
- self.add_float_spin_input('max_download_speed', '%s:' % _('Maximum Download Speed (KiB/s)'),
- core_conf['max_download_speed'], min_val=-1.0, max_val=60000.0)
- self.add_float_spin_input('max_upload_speed', '%s:' % _('Maximum Upload Speed (KiB/s)'),
- core_conf['max_upload_speed'], min_val=-1.0, max_val=60000.0)
- self.add_int_spin_input('max_half_open_connections', '%s:' % _('Maximum Half-Open Connections'),
- core_conf['max_half_open_connections'], min_val=-1, max_val=9999)
- self.add_int_spin_input('max_connections_per_second', '%s:' % _('Maximum Connection Attempts per Second'),
- core_conf['max_connections_per_second'], min_val=-1, max_val=9999)
- self.add_checked_input('ignore_limits_on_local_network', _('Ignore limits on local network'),
- core_conf['ignore_limits_on_local_network'])
- self.add_checked_input('rate_limit_ip_overhead', _('Rate Limit IP Overhead'),
- core_conf['rate_limit_ip_overhead'])
+ self.add_int_spin_input(
+ 'max_connections_global', '%s:' % _('Maximum Connections'),
+ core_conf['max_connections_global'], min_val=-1, max_val=9000,
+ )
+ self.add_int_spin_input(
+ 'max_upload_slots_global', '%s:' % _('Maximum Upload Slots'),
+ core_conf['max_upload_slots_global'], min_val=-1, max_val=9000,
+ )
+ self.add_float_spin_input(
+ 'max_download_speed', '%s:' % _('Maximum Download Speed (KiB/s)'),
+ core_conf['max_download_speed'], min_val=-1.0, max_val=60000.0,
+ )
+ self.add_float_spin_input(
+ 'max_upload_speed', '%s:' % _('Maximum Upload Speed (KiB/s)'),
+ core_conf['max_upload_speed'], min_val=-1.0, max_val=60000.0,
+ )
+ self.add_int_spin_input(
+ 'max_half_open_connections', '%s:' % _('Maximum Half-Open Connections'),
+ core_conf['max_half_open_connections'], min_val=-1, max_val=9999,
+ )
+ self.add_int_spin_input(
+ 'max_connections_per_second', '%s:' % _('Maximum Connection Attempts per Second'),
+ core_conf['max_connections_per_second'], min_val=-1, max_val=9999,
+ )
+ self.add_checked_input(
+ 'ignore_limits_on_local_network', _('Ignore limits on local network'),
+ core_conf['ignore_limits_on_local_network'],
+ )
+ self.add_checked_input(
+ 'rate_limit_ip_overhead', _('Rate Limit IP Overhead'),
+ core_conf['rate_limit_ip_overhead'],
+ )
self.add_header(_('Per Torrent Bandwidth Usage'), space_above=True)
- self.add_int_spin_input('max_connections_per_torrent', '%s:' % _('Maximum Connections'),
- core_conf['max_connections_per_torrent'], min_val=-1, max_val=9000)
- self.add_int_spin_input('max_upload_slots_per_torrent', '%s:' % _('Maximum Upload Slots'),
- core_conf['max_upload_slots_per_torrent'], min_val=-1, max_val=9000)
- self.add_float_spin_input('max_download_speed_per_torrent', '%s:' % _('Maximum Download Speed (KiB/s)'),
- core_conf['max_download_speed_per_torrent'], min_val=-1.0, max_val=60000.0)
- self.add_float_spin_input('max_upload_speed_per_torrent', '%s:' % _('Maximum Upload Speed (KiB/s)'),
- core_conf['max_upload_speed_per_torrent'], min_val=-1.0, max_val=60000.0)
+ self.add_int_spin_input(
+ 'max_connections_per_torrent', '%s:' % _('Maximum Connections'),
+ core_conf['max_connections_per_torrent'], min_val=-1, max_val=9000,
+ )
+ self.add_int_spin_input(
+ 'max_upload_slots_per_torrent', '%s:' % _('Maximum Upload Slots'),
+ core_conf['max_upload_slots_per_torrent'], min_val=-1, max_val=9000,
+ )
+ self.add_float_spin_input(
+ 'max_download_speed_per_torrent', '%s:' % _('Maximum Download Speed (KiB/s)'),
+ core_conf['max_download_speed_per_torrent'], min_val=-1.0, max_val=60000.0,
+ )
+ self.add_float_spin_input(
+ 'max_upload_speed_per_torrent', '%s:' % _('Maximum Upload Speed (KiB/s)'),
+ core_conf['max_upload_speed_per_torrent'], min_val=-1.0, max_val=60000.0,
+ )
class OtherPane(BasePreferencePane):
@@ -336,13 +412,17 @@ class DaemonPane(BasePreferencePane):
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
self.add_header('Port')
- self.add_int_spin_input('daemon_port', '%s:' % _('Daemon Port'), core_conf['daemon_port'],
- min_val=0, max_val=65535)
+ self.add_int_spin_input(
+ 'daemon_port', '%s:' % _('Daemon Port'), core_conf['daemon_port'],
+ min_val=0, max_val=65535,
+ )
self.add_header('Connections', space_above=True)
self.add_checked_input('allow_remote', _('Allow remote connections'), core_conf['allow_remote'])
self.add_header('Other', space_above=True)
- self.add_checked_input('new_release_check', _('Periodically check the website for new releases'),
- core_conf['new_release_check'])
+ self.add_checked_input(
+ 'new_release_check', _('Periodically check the website for new releases'),
+ core_conf['new_release_check'],
+ )
class QueuePane(BasePreferencePane):
@@ -355,29 +435,51 @@ class QueuePane(BasePreferencePane):
self.add_header(_('New Torrents'))
self.add_checked_input('queue_new_to_top', _('Queue to top'), core_conf['queue_new_to_top'])
self.add_header(_('Active Torrents'), True)
- self.add_int_spin_input('max_active_limit', '%s:' % _('Total'), core_conf['max_active_limit'],
- min_val=-1, max_val=9999)
- self.add_int_spin_input('max_active_downloading', '%s:' % _('Downloading'),
- core_conf['max_active_downloading'], min_val=-1, max_val=9999)
- self.add_int_spin_input('max_active_seeding', '%s:' % _('Seeding'),
- core_conf['max_active_seeding'], min_val=-1, max_val=9999)
- self.add_checked_input('dont_count_slow_torrents', 'Ignore slow torrents',
- core_conf['dont_count_slow_torrents'])
- self.add_checked_input('auto_manage_prefer_seeds', 'Prefer seeding torrents',
- core_conf['auto_manage_prefer_seeds'])
+ self.add_int_spin_input(
+ 'max_active_limit', '%s:' % _('Total'), core_conf['max_active_limit'],
+ min_val=-1, max_val=9999,
+ )
+ self.add_int_spin_input(
+ 'max_active_downloading', '%s:' % _('Downloading'),
+ core_conf['max_active_downloading'], min_val=-1, max_val=9999,
+ )
+ self.add_int_spin_input(
+ 'max_active_seeding', '%s:' % _('Seeding'),
+ core_conf['max_active_seeding'], min_val=-1, max_val=9999,
+ )
+ self.add_checked_input(
+ 'dont_count_slow_torrents', 'Ignore slow torrents',
+ core_conf['dont_count_slow_torrents'],
+ )
+ self.add_checked_input(
+ 'auto_manage_prefer_seeds', 'Prefer seeding torrents',
+ core_conf['auto_manage_prefer_seeds'],
+ )
self.add_header(_('Seeding Rotation'), space_above=True)
- self.add_float_spin_input('share_ratio_limit', '%s:' % _('Share Ratio'),
- core_conf['share_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0)
- self.add_float_spin_input('seed_time_ratio_limit', '%s:' % _('Time Ratio'),
- core_conf['seed_time_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0)
- self.add_int_spin_input('seed_time_limit', '%s:' % _('Time (m)'), core_conf['seed_time_limit'],
- min_val=1, max_val=10000)
- seedratio = FloatSpinInput(self.mode, 'stop_seed_ratio', '', self.move, core_conf['stop_seed_ratio'],
- precision=2, inc_amt=0.1, min_val=0.5, max_val=100.0)
- self.add_checkedplus_input('stop_seed_at_ratio', '%s:' % _('Share Ratio Reached'), seedratio,
- core_conf['stop_seed_at_ratio'])
- self.add_checked_input('remove_seed_at_ratio', _('Remove torrent (Unchecked pauses torrent)'),
- core_conf['remove_seed_at_ratio'])
+ self.add_float_spin_input(
+ 'share_ratio_limit', '%s:' % _('Share Ratio'),
+ core_conf['share_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0,
+ )
+ self.add_float_spin_input(
+ 'seed_time_ratio_limit', '%s:' % _('Time Ratio'),
+ core_conf['seed_time_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0,
+ )
+ self.add_int_spin_input(
+ 'seed_time_limit', '%s:' % _('Time (m)'), core_conf['seed_time_limit'],
+ min_val=1, max_val=10000,
+ )
+ seedratio = FloatSpinInput(
+ self.mode, 'stop_seed_ratio', '', self.move, core_conf['stop_seed_ratio'],
+ precision=2, inc_amt=0.1, min_val=0.5, max_val=100.0,
+ )
+ self.add_checkedplus_input(
+ 'stop_seed_at_ratio', '%s:' % _('Share Ratio Reached'), seedratio,
+ core_conf['stop_seed_at_ratio'],
+ )
+ self.add_checked_input(
+ 'remove_seed_at_ratio', _('Remove torrent (Unchecked pauses torrent)'),
+ core_conf['remove_seed_at_ratio'],
+ )
class ProxyPane(BasePreferencePane):
@@ -408,7 +510,7 @@ class ProxyPane(BasePreferencePane):
' 0: None 1: Socks4\n'
' 2: Socks5 3: Socks5 Auth\n'
' 4: HTTP 5: HTTP Auth\n'
- ' 6: I2P'
+ ' 6: I2P',
)
@@ -425,31 +527,49 @@ class CachePane(BasePreferencePane):
def build_pane(self, core_conf, status):
self.created = True
self.add_header(_('Settings'), space_below=True)
- self.add_int_spin_input('cache_size',
- '%s:' % _('Cache Size (16 KiB blocks)'), core_conf['cache_size'],
- min_val=0, max_val=99999)
- self.add_int_spin_input('cache_expiry',
- '%s:' % _('Cache Expiry (seconds)'), core_conf['cache_expiry'],
- min_val=1, max_val=32000)
+ self.add_int_spin_input(
+ 'cache_size',
+ '%s:' % _('Cache Size (16 KiB blocks)'), core_conf['cache_size'],
+ min_val=0, max_val=99999,
+ )
+ self.add_int_spin_input(
+ 'cache_expiry',
+ '%s:' % _('Cache Expiry (seconds)'), core_conf['cache_expiry'],
+ min_val=1, max_val=32000,
+ )
self.add_header(' %s' % _('Write'), space_above=True)
self.add_info_field('blocks_written', ' %s:' % _('Blocks Written'), status['disk.num_blocks_written'])
self.add_info_field('writes', ' %s:' % _('Writes'), status['disk.num_write_ops'])
- self.add_info_field('write_hit_ratio',
- ' %s:' % _('Write Cache Hit Ratio'), '%.2f' % status['write_hit_ratio'])
+ self.add_info_field(
+ 'write_hit_ratio',
+ ' %s:' % _('Write Cache Hit Ratio'), '%.2f' % status['write_hit_ratio'],
+ )
self.add_header(' %s' % _('Read'))
- self.add_info_field('blocks_read',
- ' %s:' % _('Blocks Read'), status['disk.num_blocks_read'])
- self.add_info_field('blocks_read_hit',
- ' %s:' % _('Blocks Read hit'), status['disk.num_blocks_cache_hits'])
- self.add_info_field('reads',
- ' %s:' % _('Reads'), status['disk.num_read_ops'])
- self.add_info_field('read_hit_ratio',
- ' %s:' % _('Read Cache Hit Ratio'), '%.2f' % status['read_hit_ratio'])
+ self.add_info_field(
+ 'blocks_read',
+ ' %s:' % _('Blocks Read'), status['disk.num_blocks_read'],
+ )
+ self.add_info_field(
+ 'blocks_read_hit',
+ ' %s:' % _('Blocks Read hit'), status['disk.num_blocks_cache_hits'],
+ )
+ self.add_info_field(
+ 'reads',
+ ' %s:' % _('Reads'), status['disk.num_read_ops'],
+ )
+ self.add_info_field(
+ 'read_hit_ratio',
+ ' %s:' % _('Read Cache Hit Ratio'), '%.2f' % status['read_hit_ratio'],
+ )
self.add_header(' %s' % _('Size'))
- self.add_info_field('cache_size_info',
- ' %s:' % _('Cache Size'), status['disk.disk_blocks_in_use'])
- self.add_info_field('read_cache_size',
- ' %s:' % _('Read Cache Size'), status['disk.read_cache_blocks'])
+ self.add_info_field(
+ 'cache_size_info',
+ ' %s:' % _('Cache Size'), status['disk.disk_blocks_in_use'],
+ )
+ self.add_info_field(
+ 'read_cache_size',
+ ' %s:' % _('Read Cache Size'), status['disk.read_cache_blocks'],
+ )
@overrides(BasePreferencePane)
def update(self, active):
diff --git a/deluge/ui/console/modes/preferences/preferences.py b/deluge/ui/console/modes/preferences/preferences.py
index c64e5b2d2..cad497b85 100644
--- a/deluge/ui/console/modes/preferences/preferences.py
+++ b/deluge/ui/console/modes/preferences/preferences.py
@@ -76,11 +76,15 @@ class PreferenceSidebar(Sidebar):
def __init__(self, torrentview, width):
height = curses.LINES - 2
Sidebar.__init__(self, torrentview, width, height, title=None, border_off_north=1)
- self.categories = [_('Interface'), _('Downloads'), _('Network'), _('Bandwidth'),
- _('Other'), _('Daemon'), _('Queue'), _('Proxy'), _('Cache')]
+ self.categories = [
+ _('Interface'), _('Downloads'), _('Network'), _('Bandwidth'),
+ _('Other'), _('Daemon'), _('Queue'), _('Proxy'), _('Cache'),
+ ]
for name in self.categories:
- self.add_text_field(name, name, selectable=True, font_unfocused_active='bold',
- color_unfocused_active='white,black')
+ self.add_text_field(
+ name, name, selectable=True, font_unfocused_active='bold',
+ color_unfocused_active='white,black',
+ )
def on_resize(self):
self.resize_window(curses.LINES - 2, self.width)
@@ -116,7 +120,7 @@ class Preferences(BaseMode, PopupsHandler):
DaemonPane(self),
QueuePane(self),
ProxyPane(self),
- CachePane(self)
+ CachePane(self),
]
self.action_input = SelectInput(self, None, None, [_('Cancel'), _('Apply'), _('OK')], [0, 1, 2], 0)
@@ -163,8 +167,10 @@ class Preferences(BaseMode, PopupsHandler):
def _draw_actions(self):
selected = self.active_zone == ZONE.ACTIONS
self.stdscr.hline(self.rows - 3, self.sidebar_width, '_', self.cols)
- self.action_input.render(self.stdscr, self.rows - 2, width=self.cols,
- active=selected, focus=True, col=self.cols - 22)
+ self.action_input.render(
+ self.stdscr, self.rows - 2, width=self.cols,
+ active=selected, focus=True, col=self.cols - 22,
+ )
@overrides(BaseMode)
def on_resize(self, rows, cols):
@@ -254,8 +260,10 @@ class Preferences(BaseMode, PopupsHandler):
didupdate = update_conf_value(k, new_console_config, self.console_config, didupdate)
for k in ['separate_complete', 'move_selection']:
didupdate = update_conf_value(k, new_console_config, self.console_config['torrentview'], didupdate)
- for k in ['ignore_duplicate_lines', 'save_command_history',
- 'third_tab_lists_all', 'torrents_per_tab_press']:
+ for k in [
+ 'ignore_duplicate_lines', 'save_command_history',
+ 'third_tab_lists_all', 'torrents_per_tab_press',
+ ]:
didupdate = update_conf_value(k, new_console_config, self.console_config['cmdline'], didupdate)
if didupdate:
diff --git a/deluge/ui/console/modes/torrentdetail.py b/deluge/ui/console/modes/torrentdetail.py
index 86f54f8a2..9316585ad 100644
--- a/deluge/ui/console/modes/torrentdetail.py
+++ b/deluge/ui/console/modes/torrentdetail.py
@@ -73,13 +73,15 @@ class TorrentDetail(BaseMode, PopupsHandler):
self.parent_mode = parent_mode
self.torrentid = None
self.torrent_state = None
- self._status_keys = ['files', 'name', 'state', 'download_payload_rate', 'upload_payload_rate',
- 'progress', 'eta', 'all_time_download', 'total_uploaded', 'ratio',
- 'num_seeds', 'total_seeds', 'num_peers', 'total_peers', 'active_time',
- 'seeding_time', 'time_added', 'distributed_copies', 'num_pieces',
- 'piece_length', 'download_location', 'file_progress', 'file_priorities', 'message',
- 'total_wanted', 'tracker_host', 'owner', 'seed_rank', 'last_seen_complete',
- 'completed_time', 'time_since_transfer']
+ self._status_keys = [
+ 'files', 'name', 'state', 'download_payload_rate', 'upload_payload_rate',
+ 'progress', 'eta', 'all_time_download', 'total_uploaded', 'ratio',
+ 'num_seeds', 'total_seeds', 'num_peers', 'total_peers', 'active_time',
+ 'seeding_time', 'time_added', 'distributed_copies', 'num_pieces',
+ 'piece_length', 'download_location', 'file_progress', 'file_priorities', 'message',
+ 'total_wanted', 'tracker_host', 'owner', 'seed_rank', 'last_seen_complete',
+ 'completed_time', 'time_since_transfer',
+ ]
self.file_list = None
self.current_file = None
self.current_file_idx = 0
@@ -121,8 +123,10 @@ class TorrentDetail(BaseMode, PopupsHandler):
self.set_torrent_id(torrentid)
if self.torrentid:
- component.get('SessionProxy').get_torrent_status(self.torrentid,
- self._status_keys).addCallback(self.set_state)
+ component.get('SessionProxy').get_torrent_status(
+ self.torrentid,
+ self._status_keys,
+ ).addCallback(self.set_state)
@overrides(BaseMode)
def pause(self):
@@ -141,16 +145,19 @@ class TorrentDetail(BaseMode, PopupsHandler):
def set_state(self, state):
if state.get('files'):
- self.full_names = dict([(x['index'], x['path']) for x in state['files']])
+ self.full_names = {x['index']: x['path'] for x in state['files']}
need_prio_update = False
if not self.file_list:
# don't keep getting the files once we've got them once
if state.get('files'):
self.files_sep = '{!green,black,bold,underline!}%s' % (
- ('Files (torrent has %d files)' % len(state['files'])).center(self.cols))
- self.file_list, self.file_dict = self.build_file_list(state['files'], state['file_progress'],
- state['file_priorities'])
+ ('Files (torrent has %d files)' % len(state['files'])).center(self.cols)
+ )
+ self.file_list, self.file_dict = self.build_file_list(
+ state['files'], state['file_progress'],
+ state['file_priorities'],
+ )
else:
self.files_sep = '{!green,black,bold,underline!}%s' % (('Files (File list unknown)').center(self.cols))
need_prio_update = True
@@ -193,8 +200,10 @@ class TorrentDetail(BaseMode, PopupsHandler):
child_list = []
if path == paths[-1]:
file_progress = format_progress(progress[torrent_file['index']] * 100)
- entry = [path, torrent_file['index'], torrent_file['size'], child_list,
- False, file_progress, priority[torrent_file['index']]]
+ entry = [
+ path, torrent_file['index'], torrent_file['size'], child_list,
+ False, file_progress, priority[torrent_file['index']],
+ ]
file_dict[torrent_file['index']] = entry
else:
entry = [path, dir_idx, -1, child_list, False, 0, -1]
@@ -249,7 +258,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
def __update_columns(self):
self.column_widths = [-1, 15, 15, 20]
- req = sum([col_width for col_width in self.column_widths if col_width >= 0])
+ 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
cw = self.cols // len(self.column_names)
for i in range(0, len(self.column_widths)):
@@ -262,8 +271,12 @@ class TorrentDetail(BaseMode, PopupsHandler):
if self.column_widths[i] < 0:
self.column_widths[i] = vw
- self.column_string = '{!green,black,bold!}%s' % (''.join(['%s%s' % (self.column_names[i], ' ' * (
- self.column_widths[i] - len(self.column_names[i]))) for i in range(0, len(self.column_names))]))
+ self.column_string = '{!green,black,bold!}%s' % (
+ ''.join(['%s%s' % (
+ self.column_names[i], ' ' * (
+ self.column_widths[i] - len(self.column_names[i])
+ ),
+ ) for i in range(0, len(self.column_names))]))
def _on_torrentremoved_event(self, torrent_id):
if torrent_id == self.torrentid:
@@ -273,7 +286,8 @@ class TorrentDetail(BaseMode, PopupsHandler):
if torrent_id == self.torrentid:
self.file_dict[index][0] = new_name.split('/')[-1]
component.get('SessionProxy').get_torrent_status(
- self.torrentid, self._status_keys).addCallback(self.set_state)
+ self.torrentid, self._status_keys,
+ ).addCallback(self.set_state)
def _on_torrentfolderrenamed_event(self, torrent_id, old_folder, new_folder):
if torrent_id == self.torrentid:
@@ -289,7 +303,8 @@ class TorrentDetail(BaseMode, PopupsHandler):
# self.__get_file_by_name(old_folder, self.file_list)[0] = new_folder.strip('/')
component.get('SessionProxy').get_torrent_status(
- self.torrentid, self._status_keys).addCallback(self.set_state)
+ self.torrentid, self._status_keys,
+ ).addCallback(self.set_state)
def draw_files(self, files, depth, off, idx):
@@ -318,7 +333,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
4: 'white', # Normal
5: 'green',
6: 'green',
- 7: 'green' # High
+ 7: 'green', # High
}
fg = priority_fg_color[fl[6]]
@@ -359,10 +374,14 @@ class TorrentDetail(BaseMode, PopupsHandler):
else: # file
xchar = '-'
- r = format_row(['%s%s %s' % (' ' * depth, xchar, fl[0]),
- fsize(fl[2]), fl[5],
- format_priority(fl[6])],
- self.column_widths)
+ r = format_row(
+ [
+ '%s%s %s' % (' ' * depth, xchar, fl[0]),
+ fsize(fl[2]), fl[5],
+ format_priority(fl[6]),
+ ],
+ self.column_widths,
+ )
self.add_string(off, '%s%s' % (color_string, r), trim=False)
off += 1
@@ -419,8 +438,10 @@ class TorrentDetail(BaseMode, PopupsHandler):
download_color = colors.state_color['Downloading']
def add_field(name, row, pre_color='{!info!}', post_color='{!input!}'):
- s = '%s%s: %s%s' % (pre_color, torrent_data_fields[name]['name'],
- post_color, get_column_value(name, status))
+ s = '%s%s: %s%s' % (
+ pre_color, torrent_data_fields[name]['name'],
+ post_color, get_column_value(name, status),
+ )
if row:
row = self.add_string(row, s)
return row
@@ -449,22 +470,28 @@ class TorrentDetail(BaseMode, PopupsHandler):
row = self.add_string(row, s)
# Seed/peer info
- s = '{!info!}%s:{!green!} %s {!input!}(%s)' % (torrent_data_fields['seeds']['name'],
- status['num_seeds'], status['total_seeds'])
+ s = '{!info!}%s:{!green!} %s {!input!}(%s)' % (
+ torrent_data_fields['seeds']['name'],
+ status['num_seeds'], status['total_seeds'],
+ )
row = self.add_string(row, s)
- s = '{!info!}%s:{!red!} %s {!input!}(%s)' % (torrent_data_fields['peers']['name'],
- status['num_peers'], status['total_peers'])
+ s = '{!info!}%s:{!red!} %s {!input!}(%s)' % (
+ torrent_data_fields['peers']['name'],
+ status['num_peers'], status['total_peers'],
+ )
row = self.add_string(row, s)
# Tracker
tracker_color = '{!green!}' if status['message'] == 'OK' else '{!red!}'
s = '{!info!}%s: {!magenta!}%s{!input!} says "%s%s{!input!}"' % (
- torrent_data_fields['tracker']['name'], status['tracker_host'], tracker_color, status['message'])
+ torrent_data_fields['tracker']['name'], status['tracker_host'], tracker_color, status['message'],
+ )
row = self.add_string(row, s)
# Pieces and availability
s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % (
- torrent_data_fields['pieces']['name'], status['num_pieces'], fsize(status['piece_length']))
+ torrent_data_fields['pieces']['name'], status['num_pieces'], fsize(status['piece_length']),
+ )
if status['distributed_copies']:
s += '{!info!}%s: {!input!}%s' % (torrent_data_fields['seed_rank']['name'], status['seed_rank'])
row = self.add_string(row, s)
@@ -588,14 +615,22 @@ class TorrentDetail(BaseMode, PopupsHandler):
if self.marked:
popup = SelectablePopup(self, 'Set File Priority', popup_func, border_off_north=1)
- popup.add_line('ignore_priority', '_Ignore',
- cb_arg=FILE_PRIORITY['Ignore'], foreground='red')
- popup.add_line('low_priority', '_Low Priority',
- cb_arg=FILE_PRIORITY['Low Priority'], foreground='yellow')
- popup.add_line('normal_priority', '_Normal Priority',
- cb_arg=FILE_PRIORITY['Normal Priority'])
- popup.add_line('high_priority', '_High Priority',
- cb_arg=FILE_PRIORITY['High Priority'], foreground='green')
+ popup.add_line(
+ 'ignore_priority', '_Ignore',
+ cb_arg=FILE_PRIORITY['Ignore'], foreground='red',
+ )
+ popup.add_line(
+ 'low_priority', '_Low Priority',
+ cb_arg=FILE_PRIORITY['Low Priority'], foreground='yellow',
+ )
+ popup.add_line(
+ 'normal_priority', '_Normal Priority',
+ cb_arg=FILE_PRIORITY['Normal Priority'],
+ )
+ popup.add_line(
+ 'high_priority', '_High Priority',
+ cb_arg=FILE_PRIORITY['High Priority'], foreground='green',
+ )
popup._selected = 1
self.push_popup(popup)
@@ -770,9 +805,11 @@ class TorrentDetail(BaseMode, PopupsHandler):
def _show_rename_popup(self):
# Perhaps in the future: Renaming multiple files
if self.marked:
- self.report_message('Error (Enter to close)',
- 'Sorry, you cannot rename multiple files, please clear '
- 'selection with {!info!}"c"{!normal!} key')
+ self.report_message(
+ 'Error (Enter to close)',
+ 'Sorry, you cannot rename multiple files, please clear '
+ 'selection with {!info!}"c"{!normal!} key',
+ )
else:
_file = self.__get_file_by_num(self.current_file_idx, self.file_list)
old_filename = _file[0]
diff --git a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
index 44d31f91e..3cc7ee253 100644
--- a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
+++ b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
@@ -61,15 +61,19 @@ def show_torrent_add_popup(torrentlist):
torrentlist.report_message('Error', '{!error!}Invalid URL or magnet link: %s' % url)
return
- log.debug('Adding Torrent(s): %s (dl path: %s) (paused: %d)',
- url, data['path']['value'], data['add_paused']['value'])
+ log.debug(
+ 'Adding Torrent(s): %s (dl path: %s) (paused: %d)',
+ url, data['path']['value'], data['add_paused']['value'],
+ )
def show_add_url_popup():
add_paused = 1 if 'add_paused' in torrentlist.coreconfig else 0
popup = InputPopup(torrentlist, 'Add Torrent (Esc to cancel)', close_cb=do_add_from_url)
popup.add_text_input('url', 'Enter torrent URL or Magnet link:')
- popup.add_text_input('path', 'Enter save path:', torrentlist.coreconfig.get('download_location', ''),
- complete=True)
+ popup.add_text_input(
+ 'path', 'Enter save path:', torrentlist.coreconfig.get('download_location', ''),
+ complete=True,
+ )
popup.add_select_input('add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], add_paused)
torrentlist.push_popup(popup)
diff --git a/deluge/ui/console/modes/torrentlist/filtersidebar.py b/deluge/ui/console/modes/torrentlist/filtersidebar.py
index 62272bfdd..49e26ed89 100644
--- a/deluge/ui/console/modes/torrentlist/filtersidebar.py
+++ b/deluge/ui/console/modes/torrentlist/filtersidebar.py
@@ -33,8 +33,10 @@ class FilterSidebar(Sidebar, Component):
self.config = config
height = curses.LINES - 2
width = self.config['torrentview']['sidebar_width']
- Sidebar.__init__(self, torrentlist, width, height, title=' Filter ', border_off_north=1,
- allow_resize=True)
+ Sidebar.__init__(
+ self, torrentlist, width, height, title=' Filter ', border_off_north=1,
+ allow_resize=True,
+ )
Component.__init__(self, 'FilterSidebar')
self.checked_index = 0
kwargs = {'checked_char': '*', 'unchecked_char': '-', 'checkbox_format': ' %s ', 'col': 0}
diff --git a/deluge/ui/console/modes/torrentlist/queue_mode.py b/deluge/ui/console/modes/torrentlist/queue_mode.py
index 42d138cc7..9a98e86c3 100644
--- a/deluge/ui/console/modes/torrentlist/queue_mode.py
+++ b/deluge/ui/console/modes/torrentlist/queue_mode.py
@@ -20,10 +20,12 @@ try:
except ImportError:
pass
-key_to_action = {curses.KEY_HOME: ACTION.QUEUE_TOP,
- curses.KEY_UP: ACTION.QUEUE_UP,
- curses.KEY_DOWN: ACTION.QUEUE_DOWN,
- curses.KEY_END: ACTION.QUEUE_BOTTOM}
+key_to_action = {
+ curses.KEY_HOME: ACTION.QUEUE_TOP,
+ curses.KEY_UP: ACTION.QUEUE_UP,
+ curses.KEY_DOWN: ACTION.QUEUE_DOWN,
+ curses.KEY_END: ACTION.QUEUE_BOTTOM,
+}
QUEUE_MODE_HELP_STR = """
Change queue position of selected torrents
diff --git a/deluge/ui/console/modes/torrentlist/search_mode.py b/deluge/ui/console/modes/torrentlist/search_mode.py
index 2196b78c7..f28bf75cb 100644
--- a/deluge/ui/console/modes/torrentlist/search_mode.py
+++ b/deluge/ui/console/modes/torrentlist/search_mode.py
@@ -43,7 +43,7 @@ SEARCH_FORMAT = {
SEARCH_FAILING: '{!black,white!}Search torrents: {!black,red!}%s{!black,white!}',
SEARCH_START_REACHED:
'{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (start reached)',
- SEARCH_END_REACHED: '{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (end reached)'
+ SEARCH_END_REACHED: '{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (end reached)',
}
diff --git a/deluge/ui/console/modes/torrentlist/torrentactions.py b/deluge/ui/console/modes/torrentlist/torrentactions.py
index 52baa56f7..53b12fc91 100644
--- a/deluge/ui/console/modes/torrentlist/torrentactions.py
+++ b/deluge/ui/console/modes/torrentlist/torrentactions.py
@@ -28,13 +28,17 @@ log = logging.getLogger(__name__)
torrent_options = [
'max_download_speed', 'max_upload_speed', 'max_connections', 'max_upload_slots',
'prioritize_first_last', 'sequential_download', 'is_auto_managed', 'stop_at_ratio',
- 'stop_ratio', 'remove_at_ratio', 'move_completed', 'move_completed_path']
+ 'stop_ratio', 'remove_at_ratio', 'move_completed', 'move_completed_path',
+]
def action_error(error, mode):
rerr = error.value
- mode.report_message('An Error Occurred', '%s got error %s: %s' % (
- rerr.method, rerr.exception_type, rerr.exception_msg))
+ mode.report_message(
+ 'An Error Occurred', '%s got error %s: %s' % (
+ rerr.method, rerr.exception_type, rerr.exception_msg,
+ ),
+ )
mode.refresh()
@@ -85,12 +89,16 @@ def action_remove(mode=None, torrent_ids=None, **kwargs):
rem_msg += '\n {!red!}And %i more' % (len(status) - show_max)
break
- popup = InputPopup(mode, '(Esc to cancel, Enter to remove)', close_cb=do_remove,
- border_off_west=1, border_off_north=1)
+ popup = InputPopup(
+ mode, '(Esc to cancel, Enter to remove)', close_cb=do_remove,
+ border_off_west=1, border_off_north=1,
+ )
popup.add_text(rem_msg)
popup.add_spaces(1)
- popup.add_select_input('remove_files', '{!info!}Torrent files:',
- ['Keep', 'Remove'], [False, True], False)
+ popup.add_select_input(
+ 'remove_files', '{!info!}Torrent files:',
+ ['Keep', 'Remove'], [False, True], False,
+ )
mode.push_popup(popup)
defer.DeferredList(callbacks).addCallback(remove_dialog)
@@ -125,9 +133,11 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
if kwargs.get('close', False):
mode.pop_popup()
return True
- option_popup = InputPopup(mode, ' Set Torrent Options ', close_cb=cb,
- border_off_west=1, border_off_north=1,
- base_popup=kwargs.get('base_popup', None))
+ option_popup = InputPopup(
+ mode, ' Set Torrent Options ', close_cb=cb,
+ border_off_west=1, border_off_north=1,
+ base_popup=kwargs.get('base_popup', None),
+ )
for field in torrent_options:
caption = '{!info!}' + TORRENT_DATA_FIELD[field]['name']
value = options[field]
@@ -182,8 +192,10 @@ def torrent_action(action, *args, **kwargs):
return True
if os.path.exists(res['path']['value']) and not os.path.isdir(res['path']['value']):
- mode.report_message('Cannot Move Download Folder',
- '{!error!}%s exists and is not a directory' % res['path']['value'])
+ mode.report_message(
+ 'Cannot Move Download Folder',
+ '{!error!}%s exists and is not a directory' % res['path']['value'],
+ )
else:
log.debug('Moving %s to: %s', torrent_ids, res['path']['value'])
client.core.move_storage(torrent_ids, res['path']['value']).addErrback(action_error, mode)
@@ -218,10 +230,12 @@ def torrent_actions_popup(mode, torrent_ids, details=False, action=None, close_c
torrent_action(action, mode=mode, torrent_ids=torrent_ids)
return
- popup = SelectablePopup(mode, 'Torrent Actions', torrent_action,
- cb_args={'mode': mode, 'torrent_ids': torrent_ids},
- close_cb=close_cb, border_off_north=1,
- border_off_west=1, border_off_east=1)
+ popup = SelectablePopup(
+ mode, 'Torrent Actions', torrent_action,
+ cb_args={'mode': mode, 'torrent_ids': torrent_ids},
+ close_cb=close_cb, border_off_north=1,
+ border_off_west=1, border_off_east=1,
+ )
popup.add_line(ACTION.PAUSE, '_Pause')
popup.add_line(ACTION.RESUME, '_Resume')
if details:
diff --git a/deluge/ui/console/modes/torrentlist/torrentlist.py b/deluge/ui/console/modes/torrentlist/torrentlist.py
index 52239a867..0af01a633 100644
--- a/deluge/ui/console/modes/torrentlist/torrentlist.py
+++ b/deluge/ui/console/modes/torrentlist/torrentlist.py
@@ -115,8 +115,10 @@ class TorrentList(BaseMode, PopupsHandler):
self.coreconfig = self.consoleui.coreconfig
self.config = self.consoleui.config
self.sidebar = FilterSidebar(self, self.config)
- self.torrentview_panel = mkwin(curses.COLOR_GREEN, curses.LINES - 1,
- curses.COLS - self.sidebar.width, 0, self.sidebar.width)
+ self.torrentview_panel = mkwin(
+ curses.COLOR_GREEN, curses.LINES - 1,
+ curses.COLS - self.sidebar.width, 0, self.sidebar.width,
+ )
self.torrentview = torrentview.TorrentView(self, self.config)
util.safe_curs_set(util.Curser.INVISIBLE)
diff --git a/deluge/ui/console/modes/torrentlist/torrentview.py b/deluge/ui/console/modes/torrentlist/torrentview.py
index 967aa26d4..50bb25d31 100644
--- a/deluge/ui/console/modes/torrentlist/torrentview.py
+++ b/deluge/ui/console/modes/torrentlist/torrentview.py
@@ -28,12 +28,14 @@ except ImportError:
log = logging.getLogger(__name__)
-state_fg_colors = {'Downloading': 'green',
- 'Seeding': 'cyan',
- 'Error': 'red',
- 'Queued': 'yellow',
- 'Checking': 'blue',
- 'Moving': 'green'}
+state_fg_colors = {
+ 'Downloading': 'green',
+ 'Seeding': 'cyan',
+ 'Error': 'red',
+ 'Queued': 'yellow',
+ 'Checking': 'blue',
+ 'Moving': 'green',
+}
def _queue_sort(v1, v2):
@@ -63,7 +65,7 @@ reverse_sort_fields = [
'progress',
'ratio',
'seeding_time',
- 'active_time'
+ 'active_time',
]
@@ -297,8 +299,12 @@ class TorrentView(InputKeyHandler):
def draw_row(index):
if index not in self.cached_rows:
ts = self.curstate[self.sorted_ids[index]]
- self.cached_rows[index] = (format_utils.format_row(
- [get_column_value(name, ts) for name in self.cols_to_show], self.column_widths), ts['state'])
+ self.cached_rows[index] = (
+ format_utils.format_row(
+ [get_column_value(name, ts) for name in self.cols_to_show],
+ self.column_widths,
+ ), ts['state'],
+ )
return self.cached_rows[index]
tidx = self.curoff
@@ -327,12 +333,16 @@ class TorrentView(InputKeyHandler):
else:
colorstr = '{!%(fg)s,%(bg)s!}' % colors
- self.torrentlist.add_string(currow + self.torrentlist_offset, '%s%s' % (colorstr, row[0]),
- trim=False, scr=self.torrentlist.torrentview_panel)
+ self.torrentlist.add_string(
+ currow + self.torrentlist_offset, '%s%s' % (colorstr, row[0]),
+ trim=False, scr=self.torrentlist.torrentview_panel,
+ )
def update(self, refresh=False):
- d = component.get('SessionProxy').get_torrents_status(self.filter_dict,
- self.status_fields)
+ d = component.get('SessionProxy').get_torrents_status(
+ self.filter_dict,
+ self.status_fields,
+ )
d.addCallback(self.update_state, refresh=refresh)
def on_config_changed(self):
@@ -345,9 +355,12 @@ class TorrentView(InputKeyHandler):
if changed:
self.config.save()
- self.cols_to_show = [col for col in sorted(self.config['torrentview']['columns'],
- key=lambda k: self.config['torrentview']['columns'][k]['order'])
- if self.config['torrentview']['columns'][col]['visible']]
+ self.cols_to_show = [
+ col for col in sorted(
+ self.config['torrentview']['columns'],
+ key=lambda k: self.config['torrentview']['columns'][k]['order'],
+ ) if self.config['torrentview']['columns'][col]['visible']
+ ]
self.status_fields = get_required_fields(self.cols_to_show)
# we always need these, even if we're not displaying them
@@ -365,7 +378,7 @@ class TorrentView(InputKeyHandler):
def update_columns(self):
self.column_widths = [self.config['torrentview']['columns'][col]['width'] for col in self.cols_to_show]
- requested_width = sum([width for width in self.column_widths if width >= 0])
+ requested_width = sum(width for width in self.column_widths if width >= 0)
cols = self.torrentlist.torrentview_columns()
if requested_width > cols: # can't satisfy requests, just spread out evenly
@@ -428,8 +441,10 @@ class TorrentView(InputKeyHandler):
def on_close(**kwargs):
if added:
self.marked.pop()
- torrent_actions_popup(self.torrentlist, self._selected_torrent_ids(),
- action=ACTION.REMOVE, close_cb=on_close)
+ torrent_actions_popup(
+ self.torrentlist, self._selected_torrent_ids(),
+ action=ACTION.REMOVE, close_cb=on_close,
+ )
elif c in [curses.KEY_ENTER, util.KEY_ENTER2] and self.numtorrents:
added = self.update_marked(self.cursel)
diff --git a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
index 9f2b292cf..96da7ffad 100644
--- a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
+++ b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
@@ -25,12 +25,14 @@ Control column visibilty with the following actions:
{!info!}'CTRL+down'{!normal!} - {|indent_pos:|} Move column right
"""
-column_pref_names = ['queue', 'name', 'size', 'downloaded', 'uploaded', 'remaining', 'state',
- 'progress', 'seeds', 'peers', 'seeds_peers_ratio',
- 'download_speed', 'upload_speed', 'max_download_speed', 'max_upload_speed',
- 'eta', 'ratio', 'avail', 'time_added', 'completed_time', 'last_seen_complete',
- 'tracker', 'download_location', 'active_time', 'seeding_time', 'finished_time',
- 'time_since_transfer', 'shared', 'owner']
+column_pref_names = [
+ 'queue', 'name', 'size', 'downloaded', 'uploaded', 'remaining', 'state',
+ 'progress', 'seeds', 'peers', 'seeds_peers_ratio',
+ 'download_speed', 'upload_speed', 'max_download_speed', 'max_upload_speed',
+ 'eta', 'ratio', 'avail', 'time_added', 'completed_time', 'last_seen_complete',
+ 'tracker', 'download_location', 'active_time', 'seeding_time', 'finished_time',
+ 'time_since_transfer', 'shared', 'owner',
+]
class ColumnAndWidth(CheckedPlusInput):
@@ -57,28 +59,36 @@ class TorrentViewColumns(InputPopup):
self.torrentview = torrentlist.torrentview
title = 'Visible columns (Esc to exit)'
- InputPopup.__init__(self, torrentlist, title, close_cb=self._do_set_column_visibility,
- immediate_action=True,
- height_req=len(column_pref_names) - 5,
- width_req=max([len(col) for col in column_pref_names + [title]]) + 14,
- border_off_west=1,
- allow_rearrange=True)
+ InputPopup.__init__(
+ self, torrentlist, title, close_cb=self._do_set_column_visibility,
+ immediate_action=True,
+ height_req=len(column_pref_names) - 5,
+ width_req=max(
+ len(col) for col in column_pref_names + [title]
+ ) + 14,
+ border_off_west=1,
+ allow_rearrange=True,
+ )
msg_fmt = '%-25s'
self.add_header((msg_fmt % _('Columns')) + ' ' + _('Width'), space_below=True)
for colpref_name in column_pref_names:
col = self.torrentview.config['torrentview']['columns'][colpref_name]
- width_spin = IntSpinInput(self, colpref_name + '_ width', '', self.move, col['width'],
- min_val=-1, max_val=99, fmt='%2d')
+ width_spin = IntSpinInput(
+ self, colpref_name + '_ width', '', self.move, col['width'],
+ min_val=-1, max_val=99, fmt='%2d',
+ )
def on_width_func(name, width):
self.torrentview.config['torrentview']['columns'][name]['width'] = width
- self._add_input(ColumnAndWidth(self, colpref_name, torrent_data_fields[colpref_name]['name'], width_spin,
- on_width_func,
- checked=col['visible'], checked_char='*', msg_fmt=msg_fmt,
- show_usage_hints=False, child_always_visible=True))
+ self._add_input(ColumnAndWidth(
+ self, colpref_name, torrent_data_fields[colpref_name]['name'], width_spin,
+ on_width_func,
+ checked=col['visible'], checked_char='*', msg_fmt=msg_fmt,
+ show_usage_hints=False, child_always_visible=True,
+ ))
def _do_set_column_visibility(self, data=None, state_changed=True, close=True, **kwargs):
if close:
diff --git a/deluge/ui/console/utils/colors.py b/deluge/ui/console/utils/colors.py
index 17119e71a..ac1a50c77 100644
--- a/deluge/ui/console/utils/colors.py
+++ b/deluge/ui/console/utils/colors.py
@@ -29,12 +29,12 @@ colors = [
'COLOR_MAGENTA',
'COLOR_RED',
'COLOR_WHITE',
- 'COLOR_YELLOW'
+ 'COLOR_YELLOW',
]
# {(fg, bg): pair_number, ...}
color_pairs = {
- ('white', 'black'): 0 # Special case, can't be changed
+ ('white', 'black'): 0, # Special case, can't be changed
}
# Some default color schemes
@@ -50,7 +50,7 @@ schemes = {
'marked': ('white', 'blue', 'bold'),
'selectedmarked': ('blue', 'white', 'bold'),
'header': ('green', 'black', 'bold'),
- 'filterstatus': ('green', 'blue', 'bold')
+ 'filterstatus': ('green', 'blue', 'bold'),
}
# Colors for various torrent states
@@ -61,7 +61,7 @@ state_color = {
'Checking': '{!green,black!}',
'Queued': '{!yellow,black!}',
'Error': '{!red,black,bold!}',
- 'Moving': '{!green,black,bold!}'
+ 'Moving': '{!green,black,bold!}',
}
type_color = {
@@ -70,7 +70,7 @@ type_color = {
float: '{!green,black,bold!}',
str: '{!cyan,black,bold!}',
list: '{!magenta,black,bold!}',
- dict: '{!white,black,bold!}'
+ dict: '{!white,black,bold!}',
}
@@ -297,7 +297,7 @@ class ConsoleColorFormatter(object):
'<value>': '{!cyan!}%s{!input!}',
'usage:': '{!info!}%s{!input!}',
'<download-folder>': '{!yellow!}%s{!input!}',
- '<torrent-file>': '{!green!}%s{!input!}'
+ '<torrent-file>': '{!green!}%s{!input!}',
}
diff --git a/deluge/ui/console/utils/format_utils.py b/deluge/ui/console/utils/format_utils.py
index 4d2773572..9d609c4fb 100644
--- a/deluge/ui/console/utils/format_utils.py
+++ b/deluge/ui/console/utils/format_utils.py
@@ -96,8 +96,10 @@ def f_seedrank_dash(seed_rank, seeding_time):
def ftotal_sized(first, second):
- return '%s (%s)' % (deluge.common.fsize(first, shortform=True),
- deluge.common.fsize(second, shortform=True))
+ return '%s (%s)' % (
+ deluge.common.fsize(first, shortform=True),
+ deluge.common.fsize(second, shortform=True),
+ )
def format_pieces(num, size):
@@ -297,7 +299,7 @@ def strwidth(string):
"""
Measure width of a string considering asian double width characters
"""
- return sum([1 + (east_asian_width(char) in ['W', 'F']) for char in string])
+ return sum(1 + (east_asian_width(char) in ['W', 'F']) for char in string)
def pad_string(string, length, character=' ', side='right'):
diff --git a/deluge/ui/console/widgets/fields.py b/deluge/ui/console/widgets/fields.py
index a89b5b483..7cf222151 100644
--- a/deluge/ui/console/widgets/fields.py
+++ b/deluge/ui/console/widgets/fields.py
@@ -189,12 +189,16 @@ class InfoField(NoInputField):
class CheckedInput(InputField):
- def __init__(self, parent, name, message, checked=False, checked_char='X', unchecked_char=' ',
- checkbox_format='[%s] ', **kwargs):
+ def __init__(
+ self, parent, name, message, checked=False, checked_char='X', unchecked_char=' ',
+ checkbox_format='[%s] ', **kwargs
+ ):
InputField.__init__(self, parent, name, message, **kwargs)
self.set_value(checked)
- self.fmt_keys.update({'msg': message, 'checkbox_format': checkbox_format,
- 'unchecked_char': unchecked_char, 'checked_char': checked_char})
+ self.fmt_keys.update({
+ 'msg': message, 'checkbox_format': checkbox_format,
+ 'unchecked_char': unchecked_char, 'checked_char': checked_char,
+ })
self.set_fmt_key('font_checked', 'font', kwargs)
self.set_fmt_key('font_unfocused_checked', 'font_checked', kwargs)
self.set_fmt_key('font_active_checked', 'font_active', kwargs)
@@ -253,8 +257,10 @@ class CheckedInput(InputField):
class CheckedPlusInput(CheckedInput):
- def __init__(self, parent, name, message, child, child_always_visible=False,
- show_usage_hints=True, msg_fmt='%s ', **kwargs):
+ def __init__(
+ self, parent, name, message, child, child_always_visible=False,
+ show_usage_hints=True, msg_fmt='%s ', **kwargs
+ ):
CheckedInput.__init__(self, parent, name, message, **kwargs)
self.child = child
self.child_active = False
@@ -279,13 +285,17 @@ class CheckedPlusInput(CheckedInput):
msglen = len(self.msg_fmt % colors.strip_colors(self.build_msg_string(focused, active)))
# show child
if self.checked or self.child_always_visible:
- crows = self.child.render(screen, row, width=width - msglen,
- active=self.child_active and active,
- col=col + msglen, cursor_offset=msglen)
+ crows = self.child.render(
+ screen, row, width=width - msglen,
+ active=self.child_active and active,
+ col=col + msglen, cursor_offset=msglen,
+ )
rows = max(rows, crows)
else:
- self.parent.add_string(row, '(enable to view/edit value)', scr=screen,
- col=col + msglen, pad=False)
+ self.parent.add_string(
+ row, '(enable to view/edit value)', scr=screen,
+ col=col + msglen, pad=False,
+ )
return rows
@overrides(CheckedInput)
@@ -311,8 +321,10 @@ class CheckedPlusInput(CheckedInput):
class IntSpinInput(InputField):
- def __init__(self, parent, name, message, move_func, value, min_val=None, max_val=None,
- inc_amt=1, incr_large=10, strict_validation=False, fmt='%d', **kwargs):
+ def __init__(
+ self, parent, name, message, move_func, value, min_val=None, max_val=None,
+ inc_amt=1, incr_large=10, strict_validation=False, fmt='%d', **kwargs
+ ):
InputField.__init__(self, parent, name, message, **kwargs)
self.convert_func = int
self.fmt = fmt
@@ -355,9 +367,13 @@ class IntSpinInput(InputField):
else:
value_format += '[ ' + fmt_str + ' ]'
- self.parent.add_string(row, value_format % dict({'msg': self.message, 'value': '%s' % self.valstr},
- **self.fmt_keys),
- scr=screen, col=col, pad=False)
+ self.parent.add_string(
+ row, value_format % dict(
+ {'msg': self.message, 'value': '%s' % self.valstr},
+ **self.fmt_keys
+ ),
+ scr=screen, col=col, pad=False,
+ )
if active:
if focused:
util.safe_curs_set(util.Curser.NORMAL)
@@ -389,27 +405,37 @@ class IntSpinInput(InputField):
elif c == curses.KEY_BACKSPACE or c == util.KEY_BACKSPACE2:
if self.valstr and self.cursor > 0:
new_val = self.valstr[:self.cursor - 1] + self.valstr[self.cursor:]
- self.set_value(new_val, validate=False, cursor=self.cursor - 1, cursor_on_fail=True,
- value_on_fail=self.valstr if self.strict_validation else None)
+ self.set_value(
+ new_val, validate=False, cursor=self.cursor - 1, cursor_on_fail=True,
+ value_on_fail=self.valstr if self.strict_validation else None,
+ )
elif c == curses.KEY_DC: # Del
if self.valstr and self.cursor <= len(self.valstr):
if self.cursor == 0:
new_val = self.valstr[1:]
else:
new_val = self.valstr[:self.cursor] + self.valstr[self.cursor + 1:]
- self.set_value(new_val, validate=False, cursor=False,
- value_on_fail=self.valstr if self.strict_validation else None, cursor_on_fail=True)
+ self.set_value(
+ new_val, validate=False, cursor=False,
+ value_on_fail=self.valstr if self.strict_validation else None, cursor_on_fail=True,
+ )
elif c == ord('-'): # minus
- self.set_value(self.value - 1, validate=True, cursor=True, cursor_on_fail=True,
- value_on_fail=self.value, on_invalid=self.value)
+ self.set_value(
+ self.value - 1, validate=True, cursor=True, cursor_on_fail=True,
+ value_on_fail=self.value, on_invalid=self.value,
+ )
elif c == ord('+'): # plus
- self.set_value(self.value + 1, validate=True, cursor=True, cursor_on_fail=True,
- value_on_fail=self.value, on_invalid=self.value)
+ self.set_value(
+ self.value + 1, validate=True, cursor=True, cursor_on_fail=True,
+ value_on_fail=self.value, on_invalid=self.value,
+ )
elif util.is_int_chr(c):
if self.strict_validation:
new_val = self.valstr[:self.cursor - 1] + chr(c) + self.valstr[self.cursor - 1:]
- self.set_value(new_val, validate=True, cursor=self.cursor + 1,
- value_on_fail=self.valstr, on_invalid=self.value)
+ self.set_value(
+ new_val, validate=True, cursor=self.cursor + 1,
+ value_on_fail=self.valstr, on_invalid=self.value,
+ )
else:
minus_place = self.valstr.find('-')
if self.cursor > minus_place:
@@ -440,8 +466,10 @@ class IntSpinInput(InputField):
self.last_valid_value = self.value = value
except ValueError:
if value_on_fail is not None:
- self.set_value(value_on_fail, cursor=cursor, cursor_on_fail=cursor_on_fail,
- validate=validate, on_invalid=on_invalid)
+ self.set_value(
+ value_on_fail, cursor=cursor, cursor_on_fail=cursor_on_fail,
+ validate=validate, on_invalid=on_invalid,
+ )
return
self.value = None
self.valstr = val
@@ -484,8 +512,10 @@ class FloatSpinInput(IntSpinInput):
class SelectInput(InputField):
- def __init__(self, parent, name, message, opts, vals, active_index, active_default=False,
- require_select_action=True, **kwargs):
+ def __init__(
+ self, parent, name, message, opts, vals, active_index, active_default=False,
+ require_select_action=True, **kwargs
+ ):
InputField.__init__(self, parent, name, message, **kwargs)
self.opts = opts
self.vals = vals
@@ -580,8 +610,10 @@ class SelectInput(InputField):
class TextInput(InputField):
- def __init__(self, parent, name, message, move_func, width, value, complete=False,
- activate_input=False, **kwargs):
+ def __init__(
+ self, parent, name, message, move_func, width, value, complete=False,
+ activate_input=False, **kwargs
+ ):
InputField.__init__(self, parent, name, message, **kwargs)
self.move_func = move_func
self._width = width
@@ -690,8 +722,10 @@ class TextInput(InputField):
"""
if self.activate_input:
if not self.input_active:
- if c in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_HOME,
- curses.KEY_END, curses.KEY_ENTER, util.KEY_ENTER2]:
+ if c in [
+ curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_HOME,
+ curses.KEY_END, curses.KEY_ENTER, util.KEY_ENTER2,
+ ]:
self.input_active = True
return util.ReadState.READ
else:
@@ -867,13 +901,17 @@ class ComboInput(InputField):
select_in_range(0, selected)
from deluge.ui.console.widgets.popup import SelectablePopup # Must import here
- select_popup = SelectablePopup(self.parent, ' %s ' % _('Select Language'), self._lang_selected,
- input_cb=search_handler if self.searchable else None,
- border_off_west=1, active_wrap=False, width_req=self.choices_width + 12)
+ select_popup = SelectablePopup(
+ self.parent, ' %s ' % _('Select Language'), self._lang_selected,
+ input_cb=search_handler if self.searchable else None,
+ border_off_west=1, active_wrap=False, width_req=self.choices_width + 12,
+ )
for choice in self.choices:
args = {'data': choice[0]}
- select_popup.add_line(choice[0], choice[1], selectable=True,
- selected=choice[0] == self.get_value(), **args)
+ select_popup.add_line(
+ choice[0], choice[1], selectable=True,
+ selected=choice[0] == self.get_value(), **args
+ )
self.parent.push_popup(select_popup)
return util.ReadState.CHANGED
return util.ReadState.IGNORED
diff --git a/deluge/ui/console/widgets/inputpane.py b/deluge/ui/console/widgets/inputpane.py
index cf53b48ea..810b72209 100644
--- a/deluge/ui/console/widgets/inputpane.py
+++ b/deluge/ui/console/widgets/inputpane.py
@@ -30,9 +30,11 @@ log = logging.getLogger(__name__)
class BaseInputPane(InputKeyHandler):
- def __init__(self, mode, allow_rearrange=False, immediate_action=False, set_first_input_active=True,
- border_off_west=0, border_off_north=0, border_off_east=0, border_off_south=0,
- active_wrap=False, **kwargs):
+ def __init__(
+ self, mode, allow_rearrange=False, immediate_action=False, set_first_input_active=True,
+ border_off_west=0, border_off_north=0, border_off_east=0, border_off_south=0,
+ active_wrap=False, **kwargs
+ ):
InputKeyHandler.__init__(self)
self.inputs = []
self.mode = mode
@@ -50,8 +52,10 @@ class BaseInputPane(InputKeyHandler):
self.last_lineoff_move = 0
if not hasattr(self, 'visible_content_pane_height'):
- log.error('The class "%s" does not have the attribute "%s" required by super class "%s"',
- self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__)
+ log.error(
+ 'The class "%s" does not have the attribute "%s" required by super class "%s"',
+ self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__,
+ )
raise AttributeError('visible_content_pane_height')
@property
@@ -83,8 +87,10 @@ class BaseInputPane(InputKeyHandler):
continue
if e.name == input_element.name:
import traceback
- log.warn('Input element with name "%s" already exists in input pane (%s):\n%s',
- input_element.name, e, ''.join(traceback.format_stack(limit=5)))
+ log.warn(
+ 'Input element with name "%s" already exists in input pane (%s):\n%s',
+ input_element.name, e, ''.join(traceback.format_stack(limit=5)),
+ )
return
self.inputs.append(input_element)
@@ -117,8 +123,10 @@ class BaseInputPane(InputKeyHandler):
:param value: initial value of the field
:param complete: should completion be run when tab is hit and this field is active
"""
- return self._add_input(TextInput(self, name, message, self.move, self.visible_content_pane_width, value,
- col=col, **kwargs))
+ return self._add_input(TextInput(
+ self, name, message, self.move, self.visible_content_pane_width, value,
+ col=col, **kwargs
+ ))
def add_select_input(self, name, message, opts, vals, default_index=0, **kwargs):
return self._add_input(SelectInput(self, name, message, opts, vals, default_index, **kwargs))
@@ -305,8 +313,10 @@ class BaseInputPane(InputKeyHandler):
field_width -= default_col # Increase to col must be reflected here
else:
col = default_col
- crow += ipt.render(self.screen, crow, width=field_width, active=i == self.active_input,
- focused=focused, col=col, cursor_offset=cursor_offset)
+ crow += ipt.render(
+ self.screen, crow, width=field_width, active=i == self.active_input,
+ focused=focused, col=col, cursor_offset=cursor_offset,
+ )
if self._cursor_row >= 0:
util.safe_curs_set(util.Curser.VERY_VISIBLE)
diff --git a/deluge/ui/console/widgets/popup.py b/deluge/ui/console/widgets/popup.py
index dc0fbd599..4553ab257 100644
--- a/deluge/ui/console/widgets/popup.py
+++ b/deluge/ui/console/widgets/popup.py
@@ -64,8 +64,10 @@ class PopupsHandler(object):
class Popup(BaseWindow, InputKeyHandler):
- def __init__(self, parent_mode, title, width_req=0, height_req=0, align=ALIGN.DEFAULT,
- close_cb=None, encoding=None, base_popup=None, **kwargs):
+ def __init__(
+ self, parent_mode, title, width_req=0, height_req=0, align=ALIGN.DEFAULT,
+ close_cb=None, encoding=None, base_popup=None, **kwargs
+ ):
"""
Init a new popup. The default constructor will handle sizing and borders and the like.
@@ -196,8 +198,10 @@ class SelectablePopup(BaseInputPane, Popup):
"""
A popup which will let the user select from some of the lines that are added.
"""
- def __init__(self, parent_mode, title, selection_cb, close_cb=None, input_cb=None,
- allow_rearrange=False, immediate_action=False, **kwargs):
+ def __init__(
+ self, parent_mode, title, selection_cb, close_cb=None, input_cb=None,
+ allow_rearrange=False, immediate_action=False, **kwargs
+ ):
"""
Args:
parent_mode (basemode subclass): The mode which the popup will be drawn over
@@ -235,8 +239,10 @@ class SelectablePopup(BaseInputPane, Popup):
"""Set a selected index"""
self.active_input = index
- def add_line(self, name, string, use_underline=True, cb_arg=None, foreground=None, selectable=True,
- selected=False, **kwargs):
+ def add_line(
+ self, name, string, use_underline=True, cb_arg=None, foreground=None, selectable=True,
+ selected=False, **kwargs
+ ):
hotkey = None
self.cb_arg[name] = cb_arg
if use_underline:
@@ -293,11 +299,15 @@ class MessagePopup(Popup, BaseInputPane):
"""
Popup that just displays a message
"""
- def __init__(self, parent_mode, title, message, align=ALIGN.DEFAULT,
- height_req=0.75, width_req=0.5, **kwargs):
+ def __init__(
+ self, parent_mode, title, message, align=ALIGN.DEFAULT,
+ height_req=0.75, width_req=0.5, **kwargs
+ ):
self.message = message
- Popup.__init__(self, parent_mode, title, align=align,
- height_req=height_req, width_req=width_req)
+ Popup.__init__(
+ self, parent_mode, title, align=align,
+ height_req=height_req, width_req=width_req,
+ )
BaseInputPane.__init__(self, self, immediate_action=True, **kwargs)
lns = format_utils.wrap_string(self.message, self.width - 3, 3, True)
diff --git a/deluge/ui/console/widgets/statusbars.py b/deluge/ui/console/widgets/statusbars.py
index 81944548d..e1d9c4ccf 100644
--- a/deluge/ui/console/widgets/statusbars.py
+++ b/deluge/ui/console/widgets/statusbars.py
@@ -114,4 +114,5 @@ class StatusBars(component.Component):
self.bottombar += ' ' + _('DHT') + ': {!white,blue!}%s{!status!}' % self.dht
self.bottombar += ' ' + _('IP {!white,blue!}%s{!status!}') % (
- self.external_ip if self.external_ip else _('n/a'))
+ self.external_ip if self.external_ip else _('n/a')
+ )
diff --git a/deluge/ui/console/widgets/window.py b/deluge/ui/console/widgets/window.py
index d868c66fe..175ad8043 100644
--- a/deluge/ui/console/widgets/window.py
+++ b/deluge/ui/console/widgets/window.py
@@ -122,8 +122,10 @@ class BaseWindow(object):
indicator_row = min(indicator_row, self.visible_content_pane_height)
indicator_col = self.width + 1
- add_string(indicator_row, '{!red,black,bold!}#', screen, self.encoding,
- col=indicator_col, pad=False, trim=False)
+ add_string(
+ indicator_row, '{!red,black,bold!}#', screen, self.encoding,
+ col=indicator_col, pad=False, trim=False,
+ )
def refresh(self):
height, width = self.visible_content_pane_size
@@ -150,5 +152,7 @@ class BaseWindow(object):
self.screen.noutrefresh(pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol)
except curses.error as ex:
import traceback
- log.warn('Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: %s\nStack: %s',
- pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, ''.join(traceback.format_stack()))
+ log.warn(
+ 'Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: %s\nStack: %s',
+ pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, ''.join(traceback.format_stack()),
+ )
diff --git a/deluge/ui/gtkui/__init__.py b/deluge/ui/gtkui/__init__.py
index 180419c6a..4a5f4e040 100644
--- a/deluge/ui/gtkui/__init__.py
+++ b/deluge/ui/gtkui/__init__.py
@@ -25,9 +25,16 @@ class Gtk(UI):
super(Gtk, self).__init__('gtk', *args, description='Starts the Deluge GTK+ interface', **kwargs)
group = self.parser.add_argument_group(_('GTK Options'))
- group.add_argument('torrents', metavar='<torrent>', nargs='*', default=None,
- help=_('Add one or more torrent files, torrent URLs or magnet URIs'
- ' to a currently running Deluge GTK instance'))
+ group.add_argument(
+ 'torrents',
+ metavar='<torrent>',
+ nargs='*',
+ default=None,
+ help=_(
+ 'Add one or more torrent files, torrent URLs or magnet URIs'
+ ' to a currently running Deluge GTK instance',
+ ),
+ )
def start(self):
super(Gtk, self).start()
@@ -42,8 +49,12 @@ class Gtk(UI):
log.exception(ex)
raise
- deluge.common.run_profiled(run, self.options, output_file=self.options.profile,
- do_profile=self.options.profile)
+ deluge.common.run_profiled(
+ run,
+ self.options,
+ output_file=self.options.profile,
+ do_profile=self.options.profile,
+ )
def start():
diff --git a/deluge/ui/gtkui/aboutdialog.py b/deluge/ui/gtkui/aboutdialog.py
index c8e44694d..355f8f9d3 100644
--- a/deluge/ui/gtkui/aboutdialog.py
+++ b/deluge/ui/gtkui/aboutdialog.py
@@ -33,17 +33,19 @@ class AboutDialog(object):
version = get_version()
self.about.set_copyright(
- _('Copyright %(year_start)s-%(year_end)s Deluge Team') % {'year_start': 2007, 'year_end': 2015})
+ _('Copyright %(year_start)s-%(year_end)s Deluge Team') % {'year_start': 2007, 'year_end': 2015},
+ )
self.about.set_comments(
_('A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.') +
- '\n\n' + _('Client:') + ' %s\n' % version)
+ '\n\n' + _('Client:') + ' %s\n' % version,
+ )
self.about.set_version(version)
self.about.set_authors([
_('Current Developers:'), 'Andrew Resch', 'Damien Churchill',
'John Garland', 'Calum Lind', '', 'libtorrent (libtorrent.org):',
'Arvid Norberg', '', _('Past Developers or Contributors:'),
'Zach Tibbitts', 'Alon Zakai', 'Marcos Mobley', 'Alex Dedul',
- 'Sadrul Habib Chowdhury', 'Ido Abramovich', 'Martijn Voncken'
+ 'Sadrul Habib Chowdhury', 'Ido Abramovich', 'Martijn Voncken',
])
self.about.set_artists(['Andrew Wedderburn', 'Andrew Resch'])
self.about.set_translator_credits('\n'.join([
@@ -222,7 +224,7 @@ class AboutDialog(object):
'Xiaodong Xu', 'xyb', 'Yaron', 'Yasen Pramatarov', 'YesPoX',
'Yuren Ju', 'Yves MATHIEU', 'zekopeko', 'zhuqin', 'Zissan',
'Γιάννης Κατσαμπίρης', 'Артём Попов', 'Миша', 'Шаймарданов Максим',
- '蔡查理'
+ '蔡查理',
]))
self.about.set_wrap_license(True)
self.about.set_license(_(
@@ -248,7 +250,7 @@ class AboutDialog(object):
'version of the file(s), but you are not obligated to do so. If '
'you do not wish to do so, delete this exception statement from '
'your version. If you delete this exception statement from all '
- 'source files in the program, then also delete it here.'
+ 'source files in the program, then also delete it here.',
))
self.about.set_website('http://deluge-torrent.org')
self.about.set_website_label('deluge-torrent.org')
@@ -259,10 +261,12 @@ class AboutDialog(object):
if client.connected():
if not client.is_standalone():
self.about.set_comments(
- self.about.get_comments() + _('Server:') + ' %coreversion%\n')
+ self.about.get_comments() + _('Server:') + ' %coreversion%\n',
+ )
self.about.set_comments(
- self.about.get_comments() + '\n' + _('libtorrent:') + ' %ltversion%\n')
+ self.about.get_comments() + '\n' + _('libtorrent:') + ' %ltversion%\n',
+ )
def on_lt_version(result):
c = self.about.get_comments()
diff --git a/deluge/ui/gtkui/addtorrentdialog.py b/deluge/ui/gtkui/addtorrentdialog.py
index 67c9cb644..3ee2868c3 100644
--- a/deluge/ui/gtkui/addtorrentdialog.py
+++ b/deluge/ui/gtkui/addtorrentdialog.py
@@ -39,15 +39,15 @@ class AddTorrentDialog(component.Component):
self.builder = gtk.Builder()
# The base dialog
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.ui'),
))
# The infohash dialog
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.infohash.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.infohash.ui'),
))
# The url dialog
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.url.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.url.ui'),
))
self.dialog = self.builder.get_object('dialog_add_torrent')
@@ -58,7 +58,8 @@ class AddTorrentDialog(component.Component):
# download?, path, filesize, sequence number, inconsistent?
self.files_treestore = gtk.TreeStore(
- bool, str, TYPE_UINT64, TYPE_INT64, bool, str)
+ bool, str, TYPE_UINT64, TYPE_INT64, bool, str,
+ )
self.files_treestore.set_sort_column_id(1, gtk.SORT_ASCENDING)
# Holds the files info
@@ -207,7 +208,7 @@ class AddTorrentDialog(component.Component):
ErrorDialog(
_('Duplicate Torrent(s)'),
_('You cannot add the same torrent twice. %d torrents were already added.' % already_added),
- self.dialog
+ self.dialog,
).run()
def add_from_magnets(self, uris):
@@ -272,7 +273,7 @@ class AddTorrentDialog(component.Component):
split_files = {}
for i, _file in enumerate(files):
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.listview_files.expand_row(b'0', False)
@@ -285,23 +286,28 @@ class AddTorrentDialog(component.Component):
file_name_chunk = file_name[:first_slash_index + 1]
if file_name_chunk not in files_storage:
files_storage[file_name_chunk] = {}
- self.prepare_file(_file, file_name[first_slash_index + 1:],
- file_num, download, files_storage[file_name_chunk])
+ self.prepare_file(
+ _file, file_name[first_slash_index + 1:],
+ file_num, download, files_storage[file_name_chunk],
+ )
def add_files(self, parent_iter, split_files):
ret = 0
for key, value in split_files.items():
if key.endswith(os.path.sep):
chunk_iter = self.files_treestore.append(
- parent_iter, [True, key, 0, -1, False, gtk.STOCK_DIRECTORY])
+ parent_iter, [True, key, 0, -1, False, gtk.STOCK_DIRECTORY],
+ )
chunk_size = self.add_files(chunk_iter, value)
self.files_treestore.set(chunk_iter, 2, chunk_size)
ret += chunk_size
else:
- self.files_treestore.append(parent_iter, [
- value[2], key, value[1]['size'],
- value[0], False, gtk.STOCK_FILE
- ])
+ self.files_treestore.append(
+ parent_iter, [
+ value[2], key, value[1]['size'],
+ value[0], False, gtk.STOCK_FILE,
+ ],
+ )
ret += value[1]['size']
if parent_iter and self.files_treestore.iter_has_child(parent_iter):
# Iterate through the children and see what we should label the
@@ -326,10 +332,14 @@ class AddTorrentDialog(component.Component):
return ret
def load_path_choosers_data(self):
- self.move_completed_path_chooser.set_text(self.core_config['move_completed_path'],
- cursor_end=False, default_text=True)
- self.download_location_path_chooser.set_text(self.core_config['download_location'],
- cursor_end=False, default_text=True)
+ self.move_completed_path_chooser.set_text(
+ self.core_config['move_completed_path'],
+ cursor_end=False, default_text=True,
+ )
+ self.download_location_path_chooser.set_text(
+ self.core_config['download_location'],
+ cursor_end=False, default_text=True,
+ )
self.builder.get_object('chk_move_completed').set_active(self.core_config['move_completed'])
def setup_move_completed_path_chooser(self):
@@ -355,23 +365,32 @@ class AddTorrentDialog(component.Component):
self.move_completed_path_chooser.set_text(options['move_completed_path'], cursor_end=True)
self.builder.get_object('spin_maxdown').set_value(
- options['max_download_speed'])
+ options['max_download_speed'],
+ )
self.builder.get_object('spin_maxup').set_value(
- options['max_upload_speed'])
+ options['max_upload_speed'],
+ )
self.builder.get_object('spin_maxconnections').set_value(
- options['max_connections'])
+ options['max_connections'],
+ )
self.builder.get_object('spin_maxupslots').set_value(
- options['max_upload_slots'])
+ options['max_upload_slots'],
+ )
self.builder.get_object('chk_paused').set_active(
- options['add_paused'])
+ options['add_paused'],
+ )
self.builder.get_object('chk_pre_alloc').set_active(
- options['pre_allocate_storage'])
+ options['pre_allocate_storage'],
+ )
self.builder.get_object('chk_prioritize').set_active(
- options['prioritize_first_last_pieces'])
+ options['prioritize_first_last_pieces'],
+ )
self.builder.get_object('chk_sequential_download').set_active(
- options['sequential_download'])
+ options['sequential_download'],
+ )
self.builder.get_object('chk_move_completed').set_active(
- options['move_completed'])
+ options['move_completed'],
+ )
def save_torrent_options(self, row=None):
# Keeps the torrent options dictionary up-to-date with what the user has
@@ -401,7 +420,8 @@ class AddTorrentDialog(component.Component):
options['add_paused'] = self.builder.get_object('chk_paused').get_active()
options['prioritize_first_last_pieces'] = self.builder.get_object('chk_prioritize').get_active()
options['sequential_download'] = self.builder.get_object(
- 'chk_sequential_download').get_active() or False
+ 'chk_sequential_download',
+ ).get_active() or False
options['move_completed'] = self.builder.get_object('chk_move_completed').get_active()
options['seed_mode'] = self.builder.get_object('chk_seed_mode').get_active()
@@ -409,7 +429,7 @@ class AddTorrentDialog(component.Component):
# Save the file priorities
files_priorities = self.build_priorities(
- self.files_treestore.get_iter_first(), {}
+ self.files_treestore.get_iter_first(), {},
)
if len(files_priorities) > 0:
@@ -434,23 +454,32 @@ class AddTorrentDialog(component.Component):
self.load_path_choosers_data()
self.builder.get_object('chk_pre_alloc').set_active(
- self.core_config['pre_allocate_storage'])
+ self.core_config['pre_allocate_storage'],
+ )
self.builder.get_object('spin_maxdown').set_value(
- self.core_config['max_download_speed_per_torrent'])
+ self.core_config['max_download_speed_per_torrent'],
+ )
self.builder.get_object('spin_maxup').set_value(
- self.core_config['max_upload_speed_per_torrent'])
+ self.core_config['max_upload_speed_per_torrent'],
+ )
self.builder.get_object('spin_maxconnections').set_value(
- self.core_config['max_connections_per_torrent'])
+ self.core_config['max_connections_per_torrent'],
+ )
self.builder.get_object('spin_maxupslots').set_value(
- self.core_config['max_upload_slots_per_torrent'])
+ self.core_config['max_upload_slots_per_torrent'],
+ )
self.builder.get_object('chk_paused').set_active(
- self.core_config['add_paused'])
+ self.core_config['add_paused'],
+ )
self.builder.get_object('chk_prioritize').set_active(
- self.core_config['prioritize_first_last_pieces'])
+ self.core_config['prioritize_first_last_pieces'],
+ )
self.builder.get_object('chk_sequential_download').set_active(
- self.core_config['sequential_download'])
+ self.core_config['sequential_download'],
+ )
self.builder.get_object('chk_move_completed').set_active(
- self.core_config['move_completed'])
+ self.core_config['move_completed'],
+ )
self.builder.get_object('chk_seed_mode').set_active(False)
def get_file_priorities(self, torrent_id):
@@ -514,8 +543,10 @@ class AddTorrentDialog(component.Component):
_('Choose a .torrent file'),
None,
gtk.FILE_CHOOSER_ACTION_OPEN,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
- gtk.RESPONSE_OK)
+ buttons=(
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
+ gtk.RESPONSE_OK,
+ ),
)
chooser.set_transient_for(self.dialog)
@@ -587,14 +618,15 @@ class AddTorrentDialog(component.Component):
ErrorDialog(
_('Invalid URL'),
'%s %s' % (url, _('is not a valid URL.')),
- self.dialog
+ self.dialog,
).run()
def add_from_url(self, url):
dialog = gtk.Dialog(
_('Downloading...'),
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
- parent=self.dialog)
+ parent=self.dialog,
+ )
dialog.set_transient_for(self.dialog)
pb = gtk.ProgressBar()
@@ -612,7 +644,8 @@ class AddTorrentDialog(component.Component):
pb.set_text('%.2f%% (%s / %s)' % (
percent * 100,
deluge.common.fsize(current_length),
- deluge.common.fsize(total_length)))
+ deluge.common.fsize(total_length),
+ ))
else:
pb.pulse()
pb.set_text('%s' % deluge.common.fsize(current_length))
@@ -626,7 +659,7 @@ class AddTorrentDialog(component.Component):
dialog.destroy()
ErrorDialog(
_('Download Failed'), '%s %s' % (_('Failed to download:'), url),
- details=result.getErrorMessage(), parent=self.dialog
+ details=result.getErrorMessage(), parent=self.dialog,
).run()
return result
@@ -717,9 +750,11 @@ class AddTorrentDialog(component.Component):
del options['file_priorities']
client.core.add_torrent_magnet(filename, options)
else:
- torrents_to_add.append((os.path.split(filename)[-1],
- base64.encodestring(self.infos[torrent_id]),
- options))
+ torrents_to_add.append((
+ os.path.split(filename)[-1],
+ base64.encodestring(self.infos[torrent_id]),
+ options,
+ ))
row = self.torrent_liststore.iter_next(row)
def on_torrents_added(errors):
@@ -832,7 +867,7 @@ class AddTorrentDialog(component.Component):
# Get the file path base once, since it will be the same for
# all siblings
file_path_base = self.get_file_path(
- self.files_treestore.iter_parent(row)
+ self.files_treestore.iter_parent(row),
)
# Iterate through all the siblings at this level
@@ -866,9 +901,11 @@ class AddTorrentDialog(component.Component):
for s in split_text[:-1]:
# We don't iterate over the last item because we'll just use
# the existing itr and change the text
- parent = self.files_treestore.append(parent, [
- True, s + os.path.sep, 0, -1, False, gtk.STOCK_DIRECTORY
- ])
+ parent = self.files_treestore.append(
+ parent, [
+ True, s + os.path.sep, 0, -1, False, gtk.STOCK_DIRECTORY,
+ ],
+ )
self.files_treestore[itr][1] = split_text[-1] + os.path.sep
diff --git a/deluge/ui/gtkui/common.py b/deluge/ui/gtkui/common.py
index 6bf8c4eae..70d6bcb82 100644
--- a/deluge/ui/gtkui/common.py
+++ b/deluge/ui/gtkui/common.py
@@ -72,8 +72,10 @@ def get_logo(size):
return get_pixbuf_at_size(filename, size)
-def build_menu_radio_list(value_list, callback, pref_value=None, suffix=None, show_notset=False,
- notset_label='∞', notset_lessthan=0, show_other=False):
+def build_menu_radio_list(
+ value_list, callback, pref_value=None, suffix=None, show_notset=False,
+ notset_label='∞', notset_lessthan=0, show_other=False,
+):
"""Build a menu with radio menu items from a list and connect them to the callback.
Params:
diff --git a/deluge/ui/gtkui/connectionmanager.py b/deluge/ui/gtkui/connectionmanager.py
index ba791ee15..5b860e699 100644
--- a/deluge/ui/gtkui/connectionmanager.py
+++ b/deluge/ui/gtkui/connectionmanager.py
@@ -48,7 +48,7 @@ HOSTLIST_PIXBUFS = [
HOSTLIST_STATUS = [
'Offline',
'Online',
- 'Connected'
+ 'Connected',
]
@@ -93,7 +93,8 @@ class ConnectionManager(component.Component):
"""Show the ConnectionManager dialog."""
self.builder = gtk.Builder()
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.ui')))
+ 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.ui'),
+ ))
self.connection_manager = self.builder.get_object('connection_manager')
self.connection_manager.set_transient_for(component.get('MainWindow').window)
@@ -101,7 +102,8 @@ class ConnectionManager(component.Component):
if not HOSTLIST_PIXBUFS:
for stock_id in (gtk.STOCK_NO, gtk.STOCK_YES, gtk.STOCK_CONNECT):
HOSTLIST_PIXBUFS.append(
- self.connection_manager.render_icon(stock_id, gtk.ICON_SIZE_MENU))
+ self.connection_manager.render_icon(stock_id, gtk.ICON_SIZE_MENU),
+ )
# Setup the hostlist liststore and treeview
self.treeview = self.builder.get_object('treeview_hostlist')
@@ -165,11 +167,14 @@ class ConnectionManager(component.Component):
def _load_widget_config(self):
"""Set the widgets to show the correct options from the config."""
self.builder.get_object('chk_autoconnect').set_active(
- self.gtkui_config['autoconnect'])
+ self.gtkui_config['autoconnect'],
+ )
self.builder.get_object('chk_autostart').set_active(
- self.gtkui_config['autostart_localhost'])
+ self.gtkui_config['autostart_localhost'],
+ )
self.builder.get_object('chk_donotshow').set_active(
- not self.gtkui_config['show_connection_manager_on_start'])
+ not self.gtkui_config['show_connection_manager_on_start'],
+ )
def _update_host_status(self):
"""Updates the host status"""
@@ -205,7 +210,8 @@ class ConnectionManager(component.Component):
self.builder.get_object('button_removehost').set_sensitive(False)
self.builder.get_object('button_startdaemon').set_sensitive(False)
self.builder.get_object('image_startdaemon').set_from_stock(
- gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU)
+ gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU,
+ )
self.builder.get_object('label_startdaemon').set_text_with_mnemonic('_Start Daemon')
model, row = self.treeview.get_selection().get_selected()
@@ -230,7 +236,8 @@ class ConnectionManager(component.Component):
if status == 'Connected' or status == 'Online':
self.builder.get_object('button_connect').set_sensitive(True)
self.builder.get_object('image_startdaemon').set_from_stock(
- gtk.STOCK_STOP, gtk.ICON_SIZE_MENU)
+ gtk.STOCK_STOP, gtk.ICON_SIZE_MENU,
+ )
self.builder.get_object('label_startdaemon').set_text_with_mnemonic(_('_Stop Daemon'))
self.builder.get_object('button_startdaemon').set_sensitive(False)
if status == 'Connected':
@@ -261,7 +268,8 @@ class ConnectionManager(component.Component):
else:
ErrorDialog(
_('Unable to start daemon!'),
- _('Check deluged package is installed and logs for further details')).run()
+ _('Check deluged package is installed and logs for further details'),
+ ).run()
return False
# Signal handlers
@@ -318,8 +326,10 @@ class ConnectionManager(component.Component):
msg = str(reason.value)
if not self.gtkui_config['autostart_localhost']:
- msg += '\n' + _('Auto-starting the daemon locally is not enabled. '
- 'See "Options" on the "Connection Manager".')
+ msg += '\n' + _(
+ 'Auto-starting the daemon locally is not enabled. '
+ 'See "Options" on the "Connection Manager".',
+ )
ErrorDialog(_('Failed To Connect'), msg).run()
def on_button_connect_clicked(self, widget=None):
@@ -363,7 +373,8 @@ class ConnectionManager(component.Component):
"""
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.addhost.ui')))
+ 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.addhost.ui'),
+ ))
dialog = self.builder.get_object('addhost_dialog')
dialog.set_transient_for(self.connection_manager)
hostname_entry = self.builder.get_object('entry_hostname')
@@ -418,7 +429,8 @@ class ConnectionManager(component.Component):
self.liststore[row][HOSTLIST_COL_HOST],
self.liststore[row][HOSTLIST_COL_PORT],
self.liststore[row][HOSTLIST_COL_USER],
- self.liststore[row][HOSTLIST_COL_PASS]]
+ self.liststore[row][HOSTLIST_COL_PASS],
+ ]
new_host_info = self._run_addhost_dialog(edit_host_info=host_info)
if new_host_info:
hostname, port, username, password = new_host_info
@@ -493,7 +505,8 @@ class ConnectionManager(component.Component):
self.gtkui_config['autoconnect'] = self.builder.get_object('chk_autoconnect').get_active()
self.gtkui_config['autostart_localhost'] = self.builder.get_object('chk_autostart').get_active()
self.gtkui_config['show_connection_manager_on_start'] = not self.builder.get_object(
- 'chk_donotshow').get_active()
+ 'chk_donotshow',
+ ).get_active()
def on_entry_host_paste_clipboard(self, widget):
text = get_clipboard_text()
diff --git a/deluge/ui/gtkui/createtorrentdialog.py b/deluge/ui/gtkui/createtorrentdialog.py
index 4a86a8051..29256fc59 100644
--- a/deluge/ui/gtkui/createtorrentdialog.py
+++ b/deluge/ui/gtkui/createtorrentdialog.py
@@ -37,19 +37,19 @@ class CreateTorrentDialog(object):
# The main dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.ui'),
))
# The remote path dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_path.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_path.ui'),
))
# The remote save dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_save.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_save.ui'),
))
# The progress dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.progress.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.progress.ui'),
))
self.config = ConfigManager('gtkui.conf')
@@ -85,9 +85,11 @@ class CreateTorrentDialog(object):
self.trackers_liststore = gtk.ListStore(int, str)
self.builder.get_object('tracker_treeview').append_column(
- gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0))
+ gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0),
+ )
self.builder.get_object('tracker_treeview').append_column(
- gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1))
+ gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1),
+ )
self.builder.get_object('tracker_treeview').set_model(self.trackers_liststore)
self.trackers_liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
@@ -125,11 +127,15 @@ class CreateTorrentDialog(object):
def on_button_file_clicked(self, widget):
log.debug('on_button_file_clicked')
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_('Choose a file'),
- self.dialog,
- gtk.FILE_CHOOSER_ACTION_OPEN,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN, gtk.RESPONSE_OK))
+ chooser = gtk.FileChooserDialog(
+ _('Choose a file'),
+ self.dialog,
+ gtk.FILE_CHOOSER_ACTION_OPEN,
+ buttons=(
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
+ gtk.STOCK_OPEN, gtk.RESPONSE_OK,
+ ),
+ )
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(False)
@@ -154,11 +160,15 @@ class CreateTorrentDialog(object):
def on_button_folder_clicked(self, widget):
log.debug('on_button_folder_clicked')
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_('Choose a folder'),
- self.dialog,
- gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN, gtk.RESPONSE_OK))
+ chooser = gtk.FileChooserDialog(
+ _('Choose a folder'),
+ self.dialog,
+ gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
+ buttons=(
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
+ gtk.STOCK_OPEN, gtk.RESPONSE_OK,
+ ),
+ )
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(False)
@@ -232,10 +242,14 @@ class CreateTorrentDialog(object):
dialog.hide()
else:
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_('Save .torrent file'), self.dialog,
- gtk.FILE_CHOOSER_ACTION_SAVE,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_SAVE, gtk.RESPONSE_OK))
+ chooser = gtk.FileChooserDialog(
+ _('Save .torrent file'), self.dialog,
+ gtk.FILE_CHOOSER_ACTION_SAVE,
+ buttons=(
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
+ gtk.STOCK_SAVE, gtk.RESPONSE_OK,
+ ),
+ )
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(False)
@@ -322,25 +336,28 @@ class CreateTorrentDialog(object):
private,
author,
trackers,
- add_to_session)
+ add_to_session,
+ )
else:
def hide_progress(result):
self.builder.get_object('progress_dialog').hide_all()
- deferToThread(self.create_torrent,
- path.decode('utf-8'),
- tracker,
- piece_length,
- self._on_create_torrent_progress,
- comment,
- result.decode('utf-8'),
- webseeds,
- private,
- author,
- trackers,
- add_to_session).addCallback(hide_progress)
+ deferToThread(
+ self.create_torrent,
+ path.decode('utf-8'),
+ tracker,
+ piece_length,
+ self._on_create_torrent_progress,
+ comment,
+ result.decode('utf-8'),
+ webseeds,
+ private,
+ author,
+ trackers,
+ add_to_session,
+ ).addCallback(hide_progress)
# Setup progress dialog
self.builder.get_object('progress_dialog').set_transient_for(component.get('MainWindow').window)
@@ -348,8 +365,10 @@ class CreateTorrentDialog(object):
self.dialog.destroy()
- def create_torrent(self, path, tracker, piece_length, progress, comment, target,
- webseeds, private, created_by, trackers, add_to_session):
+ def create_torrent(
+ self, path, tracker, piece_length, progress, comment, target,
+ webseeds, private, created_by, trackers, add_to_session,
+ ):
import deluge.metafile
deluge.metafile.make_meta_file(
path,
@@ -361,7 +380,8 @@ class CreateTorrentDialog(object):
webseeds=webseeds,
private=private,
created_by=created_by,
- trackers=trackers)
+ trackers=trackers,
+ )
if add_to_session:
with open(target, 'rb') as _file:
@@ -369,7 +389,7 @@ class CreateTorrentDialog(object):
client.core.add_torrent_file_async(
os.path.split(target)[-1],
filedump,
- {'download_location': os.path.split(path)[0]}
+ {'download_location': os.path.split(path)[0]},
)
def _on_create_torrent_progress(self, value, num_pieces):
@@ -407,7 +427,7 @@ class CreateTorrentDialog(object):
log.debug('on_button_add_clicked')
builder = gtk.Builder()
builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui'),
))
dialog = builder.get_object('add_tracker_dialog')
dialog.set_transient_for(self.dialog)
diff --git a/deluge/ui/gtkui/dialogs.py b/deluge/ui/gtkui/dialogs.py
index e020a3fcc..91b299bb3 100644
--- a/deluge/ui/gtkui/dialogs.py
+++ b/deluge/ui/gtkui/dialogs.py
@@ -36,7 +36,8 @@ class BaseDialog(gtk.Dialog):
title=header,
parent=parent if parent else component.get('MainWindow').window,
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
- buttons=buttons)
+ buttons=buttons,
+ )
self.set_icon(get_deluge_icon())
@@ -104,7 +105,8 @@ class YesNoDialog(BaseDialog):
text,
gtk.STOCK_DIALOG_QUESTION,
(gtk.STOCK_NO, gtk.RESPONSE_NO, gtk.STOCK_YES, gtk.RESPONSE_YES),
- parent)
+ parent,
+ )
class InformationDialog(BaseDialog):
@@ -124,7 +126,8 @@ class InformationDialog(BaseDialog):
text,
gtk.STOCK_DIALOG_INFO,
(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE),
- parent)
+ parent,
+ )
class ErrorDialog(BaseDialog):
@@ -149,7 +152,8 @@ class ErrorDialog(BaseDialog):
text,
gtk.STOCK_DIALOG_ERROR,
(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE),
- parent)
+ parent,
+ )
if traceback:
import traceback
@@ -193,7 +197,8 @@ class AuthenticationDialog(BaseDialog):
_('Authenticate'), err_msg,
gtk.STOCK_DIALOG_AUTHENTICATION,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK),
- parent)
+ parent,
+ )
table = gtk.Table(2, 2, False)
self.username_label = gtk.Label()
@@ -235,24 +240,32 @@ class AuthenticationDialog(BaseDialog):
class AccountDialog(BaseDialog):
- def __init__(self, username=None, password=None, authlevel=None,
- levels_mapping=None, parent=None):
+ def __init__(
+ self, username=None, password=None, authlevel=None,
+ levels_mapping=None, parent=None,
+ ):
if username:
super(AccountDialog, self).__init__(
_('Edit Account'),
_('Edit existing account'),
gtk.STOCK_DIALOG_INFO,
- (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_APPLY, gtk.RESPONSE_OK),
- parent)
+ (
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
+ gtk.STOCK_APPLY, gtk.RESPONSE_OK,
+ ),
+ parent,
+ )
else:
super(AccountDialog, self).__init__(
_('New Account'),
_('Create a new account'),
gtk.STOCK_DIALOG_INFO,
- (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_ADD, gtk.RESPONSE_OK),
- parent)
+ (
+ gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
+ gtk.STOCK_ADD, gtk.RESPONSE_OK,
+ ),
+ parent,
+ )
self.levels_mapping = levels_mapping
@@ -339,7 +352,8 @@ class OtherDialog(BaseDialog):
text,
icon,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_APPLY, gtk.RESPONSE_OK),
- parent)
+ parent,
+ )
hbox = gtk.HBox(spacing=5)
alignment_spacer = gtk.Alignment()
@@ -394,7 +408,8 @@ class PasswordDialog(BaseDialog):
_('Password Protected'), password_msg,
gtk.STOCK_DIALOG_AUTHENTICATION,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK),
- parent)
+ parent,
+ )
table = gtk.Table(1, 2, False)
self.password_label = gtk.Label()
diff --git a/deluge/ui/gtkui/edittrackersdialog.py b/deluge/ui/gtkui/edittrackersdialog.py
index 5a2842d0d..c3008cf44 100644
--- a/deluge/ui/gtkui/edittrackersdialog.py
+++ b/deluge/ui/gtkui/edittrackersdialog.py
@@ -84,15 +84,15 @@ class EditTrackersDialog(object):
# Main dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.ui'),
))
# add tracker dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui'),
))
# edit tracker dialog
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.edit.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.edit.ui'),
))
self.dialog = self.builder.get_object('edit_trackers_dialog')
@@ -116,9 +116,11 @@ class EditTrackersDialog(object):
# Create the columns
self.treeview.append_column(
- gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0))
+ gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0),
+ )
self.treeview.append_column(
- gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1))
+ gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1),
+ )
self.treeview.set_model(self.liststore)
self.liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
@@ -134,7 +136,7 @@ class EditTrackersDialog(object):
# Get the trackers for this torrent
session = component.get('SessionProxy')
session.get_torrent_status(
- self.torrent_id, ['trackers']
+ self.torrent_id, ['trackers'],
).addCallback(self._on_get_torrent_status)
client.force_call()
diff --git a/deluge/ui/gtkui/files_tab.py b/deluge/ui/gtkui/files_tab.py
index ab6bd439e..7cb31e437 100644
--- a/deluge/ui/gtkui/files_tab.py
+++ b/deluge/ui/gtkui/files_tab.py
@@ -32,7 +32,7 @@ CELL_PRIORITY_ICONS = {
'Ignore': gtk.STOCK_NO,
'Low': gtk.STOCK_GO_DOWN,
'Normal': gtk.STOCK_OK,
- 'High': gtk.STOCK_GO_UP
+ 'High': gtk.STOCK_GO_UP,
}
@@ -156,13 +156,13 @@ class FilesTab(Tab):
self.main_builder.get_object('menuitem_low'),
self.main_builder.get_object('menuitem_normal'),
self.main_builder.get_object('menuitem_high'),
- self.main_builder.get_object('menuitem_priority_sep')
+ self.main_builder.get_object('menuitem_priority_sep'),
]
self.localhost_widgets = [
self.main_builder.get_object('menuitem_open_file'),
self.main_builder.get_object('menuitem_show_file'),
- self.main_builder.get_object('menuitem3')
+ self.main_builder.get_object('menuitem3'),
]
self.listview.connect('row-activated', self._on_row_activated)
@@ -170,7 +170,8 @@ class FilesTab(Tab):
self.listview.connect('button-press-event', self._on_button_press_event)
self.listview.enable_model_drag_source(
- BUTTON1_MASK, [('text/plain', 0, 0)], ACTION_DEFAULT | ACTION_MOVE)
+ BUTTON1_MASK, [('text/plain', 0, 0)], ACTION_DEFAULT | ACTION_MOVE,
+ )
self.listview.enable_model_drag_dest([('text/plain', 0, 0)], ACTION_DEFAULT)
self.listview.connect('drag_data_get', self._on_drag_data_get_data)
@@ -204,13 +205,13 @@ class FilesTab(Tab):
state = {
'columns': {},
'sort_id': int(column_id) if column_id >= 0 else None,
- 'sort_order': int(sort_order) if sort_order >= 0 else None
+ 'sort_order': int(sort_order) if sort_order >= 0 else None,
}
for index, column in enumerate(self.listview.get_columns()):
state['columns'][column.get_title()] = {
'position': index,
- 'width': column.get_width()
+ 'width': column.get_width(),
}
save_pickled_state_file('files_tab.state', state)
@@ -269,7 +270,8 @@ class FilesTab(Tab):
status_keys += ['files']
component.get('SessionProxy').get_torrent_status(
- self.torrent_id, status_keys).addCallback(self._on_get_torrent_status, self.torrent_id)
+ self.torrent_id, status_keys,
+ ).addCallback(self._on_get_torrent_status, self.torrent_id)
def clear(self):
self.treestore.clear()
@@ -326,21 +328,27 @@ class FilesTab(Tab):
file_name_chunk = file_name[:first_slash_index + 1]
if file_name_chunk not in files_storage:
files_storage[file_name_chunk] = {}
- self.prepare_file(torrent_file, file_name[first_slash_index + 1:],
- file_num, files_storage[file_name_chunk])
+ self.prepare_file(
+ torrent_file, file_name[first_slash_index + 1:],
+ file_num, files_storage[file_name_chunk],
+ )
def add_files(self, parent_iter, split_files):
chunk_size_total = 0
for key, value in split_files.items():
if key.endswith('/'):
- chunk_iter = self.treestore.append(parent_iter,
- [key, 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY])
+ chunk_iter = self.treestore.append(
+ parent_iter,
+ [key, 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY],
+ )
chunk_size = self.add_files(chunk_iter, value)
self.treestore.set(chunk_iter, 1, chunk_size)
chunk_size_total += chunk_size
else:
- self.treestore.append(parent_iter,
- [key, value[1]['size'], '', 0, 0, value[0], gtk.STOCK_FILE])
+ self.treestore.append(
+ parent_iter,
+ [key, value[1]['size'], '', 0, 0, value[0], gtk.STOCK_FILE],
+ )
chunk_size_total += value[1]['size']
return chunk_size_total
@@ -488,12 +496,14 @@ class FilesTab(Tab):
def on_menuitem_open_file_activate(self, menuitem):
if client.is_localhost:
component.get('SessionProxy').get_torrent_status(
- self.torrent_id, ['download_location']).addCallback(self._on_open_file)
+ self.torrent_id, ['download_location'],
+ ).addCallback(self._on_open_file)
def on_menuitem_show_file_activate(self, menuitem):
if client.is_localhost:
component.get('SessionProxy').get_torrent_status(
- self.torrent_id, ['download_location']).addCallback(self._on_show_file)
+ self.torrent_id, ['download_location'],
+ ).addCallback(self._on_show_file)
def _set_file_priorities_on_user_change(self, selected, priority):
"""Sets the file priorities in the core. It will change the selected with the 'priority'"""
@@ -514,19 +524,23 @@ class FilesTab(Tab):
def on_menuitem_ignore_activate(self, menuitem):
self._set_file_priorities_on_user_change(
- self.get_selected_files(), FILE_PRIORITY['Ignore'])
+ self.get_selected_files(), FILE_PRIORITY['Ignore'],
+ )
def on_menuitem_low_activate(self, menuitem):
self._set_file_priorities_on_user_change(
- self.get_selected_files(), FILE_PRIORITY['Low'])
+ self.get_selected_files(), FILE_PRIORITY['Low'],
+ )
def on_menuitem_normal_activate(self, menuitem):
self._set_file_priorities_on_user_change(
- self.get_selected_files(), FILE_PRIORITY['Normal'])
+ self.get_selected_files(), FILE_PRIORITY['Normal'],
+ )
def on_menuitem_high_activate(self, menuitem):
self._set_file_priorities_on_user_change(
- self.get_selected_files(), FILE_PRIORITY['High'])
+ self.get_selected_files(), FILE_PRIORITY['High'],
+ )
def on_menuitem_expand_all_activate(self, menuitem):
self.listview.expand_all()
@@ -606,11 +620,14 @@ class FilesTab(Tab):
if not p_itr:
p_itr = self.get_iter_at_path('/'.join(parent_path[:i]) + '/')
p_itr = self.treestore.append(
- p_itr, [parent_path[i] + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY])
+ p_itr, [parent_path[i] + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY],
+ )
p_itr = self.get_iter_at_path('/'.join(parent_path) + '/')
old_name_itr = self.get_iter_at_path(old_name)
- self.treestore.append(p_itr,
- self.treestore.get(old_name_itr, *range(self.treestore.get_n_columns())))
+ self.treestore.append(
+ p_itr,
+ self.treestore.get(old_name_itr, *range(self.treestore.get_n_columns())),
+ )
self.treestore.remove(old_name_itr)
# Remove old parent path
@@ -621,10 +638,13 @@ class FilesTab(Tab):
parent_iter = None
for f in new_folders:
parent_iter = self.treestore.append(
- parent_iter, [f + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY])
+ parent_iter, [f + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY],
+ )
child = self.get_iter_at_path(old_name)
- self.treestore.append(parent_iter,
- self.treestore.get(child, *range(self.treestore.get_n_columns())))
+ self.treestore.append(
+ parent_iter,
+ self.treestore.get(child, *range(self.treestore.get_n_columns())),
+ )
self.treestore.remove(child)
else:
@@ -768,8 +788,10 @@ class FilesTab(Tab):
while itr:
pp = self.treestore[itr][0] + pp
itr = self.treestore.iter_parent(itr)
- client.core.rename_folder(self.torrent_id, pp + model[selected[0]][0],
- parent_path + model[selected[0]][0])
+ client.core.rename_folder(
+ self.torrent_id, pp + model[selected[0]][0],
+ parent_path + model[selected[0]][0],
+ )
else:
# [(index, filepath), ...]
to_rename = []
diff --git a/deluge/ui/gtkui/filtertreeview.py b/deluge/ui/gtkui/filtertreeview.py
index a6a87f0e6..6bec3966c 100644
--- a/deluge/ui/gtkui/filtertreeview.py
+++ b/deluge/ui/gtkui/filtertreeview.py
@@ -37,7 +37,7 @@ STATE_PIX = {
'Error': 'alert',
'Active': 'active',
'Allocating': 'checking',
- 'Moving': 'checking'
+ 'Moving': 'checking',
}
TRACKER_PIX = {
@@ -123,8 +123,12 @@ class FilterTreeView(component.Component):
for state in ['All', 'Active'] + TORRENT_STATE:
self.update_row('state', state, 0, _(state))
- self.cat_nodes['tracker_host'] = self.treestore.append(None, ['cat', 'tracker_host',
- _('Trackers'), 0, None, False])
+ self.cat_nodes['tracker_host'] = self.treestore.append(
+ None, [
+ 'cat', 'tracker_host',
+ _('Trackers'), 0, None, False,
+ ],
+ )
self.update_row('tracker_host', 'All', 0, _('All'))
self.update_row('tracker_host', 'Error', 0, _('Error'))
self.update_row('tracker_host', '', 0, _('None'))
@@ -279,8 +283,10 @@ class FilterTreeView(component.Component):
hide_cat.append('tracker_host')
if not self.config['sidebar_show_owners']:
hide_cat.append('owner')
- client.core.get_filter_tree(self.config['sidebar_show_zero'],
- hide_cat).addCallback(self.cb_update_filter_tree)
+ client.core.get_filter_tree(
+ self.config['sidebar_show_zero'],
+ hide_cat,
+ ).addCallback(self.cb_update_filter_tree)
except Exception as ex:
log.debug(ex)
diff --git a/deluge/ui/gtkui/gtkui.py b/deluge/ui/gtkui/gtkui.py
index 78cf0497d..0468baa86 100644
--- a/deluge/ui/gtkui/gtkui.py
+++ b/deluge/ui/gtkui/gtkui.py
@@ -299,20 +299,28 @@ class GtkUI(object):
try:
client.start_standalone()
except DaemonRunningError:
- err_msg = _('A Deluge daemon (deluged) is already running.\n'
- 'To use Standalone mode, stop local daemon and restart Deluge.')
+ err_msg = _(
+ 'A Deluge daemon (deluged) is already running.\n'
+ 'To use Standalone mode, stop local daemon and restart Deluge.',
+ )
except ImportError as ex:
if 'No module named libtorrent' in ex.message:
- err_msg = _('Only Thin Client mode is available because libtorrent is not installed.\n'
- 'To use Standalone mode, please install libtorrent package.')
+ err_msg = _(
+ 'Only Thin Client mode is available because libtorrent is not installed.\n'
+ 'To use Standalone mode, please install libtorrent package.',
+ )
else:
log.exception(ex)
- err_msg = _('Only Thin Client mode is available due to unknown Import Error.\n'
- 'To use Standalone mode, please see logs for error details.')
+ err_msg = _(
+ 'Only Thin Client mode is available due to unknown Import Error.\n'
+ 'To use Standalone mode, please see logs for error details.',
+ )
except Exception as ex:
log.exception(ex)
- err_msg = _('Only Thin Client mode is available due to unknown Import Error.\n'
- 'To use Standalone mode, please see logs for error details.')
+ err_msg = _(
+ 'Only Thin Client mode is available due to unknown Import Error.\n'
+ 'To use Standalone mode, please see logs for error details.',
+ )
else:
component.start()
return
diff --git a/deluge/ui/gtkui/listview.py b/deluge/ui/gtkui/listview.py
index 4aabd9cd9..6b892b156 100644
--- a/deluge/ui/gtkui/listview.py
+++ b/deluge/ui/gtkui/listview.py
@@ -178,7 +178,8 @@ class ListView(object):
"""
model_filter = self.liststore.filter_new()
model_filter.set_visible_column(
- self.columns['filter'].column_indices[0])
+ self.columns['filter'].column_indices[0],
+ )
self.model_filter = gtk.TreeModelSort(model_filter)
self.model_filter.connect('sort-column-changed', self.on_model_sort_changed)
self.model_filter.connect('row-inserted', self.on_model_row_inserted)
@@ -215,7 +216,8 @@ class ListView(object):
def on_model_row_inserted(self, model, path, _iter):
if self.unique_column_id:
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 stabilized(model, iter1, iter2, data):
@@ -224,8 +226,10 @@ class ListView(object):
unique1 = model[iter1][self.unique_column_id]
unique2 = model[iter2][self.unique_column_id]
if unique1 in self.last_sort_order and unique2 in self.last_sort_order:
- result = cmp(self.last_sort_order[unique1],
- self.last_sort_order[unique2])
+ result = cmp(
+ self.last_sort_order[unique1],
+ self.last_sort_order[unique2],
+ )
# If all else fails, fall back to sorting by unique column
if result == 0:
result = cmp(unique1, unique2)
@@ -242,7 +246,8 @@ class ListView(object):
self.model_filter.set_sort_func(
column.sort_id,
self.stabilize_sort_func(sort_func),
- column.sort_id)
+ column.sort_id,
+ )
def create_column_state(self, column, position=None):
if not position:
@@ -257,8 +262,10 @@ class ListView(object):
if self.get_column_name(sort_id) == column.get_title():
sort = sort_id
- return ListViewColumnState(column.get_title(), position, column.get_width(),
- column.get_visible(), sort, int(column.get_sort_order()))
+ return ListViewColumnState(
+ column.get_title(), position, column.get_width(),
+ column.get_visible(), sort, int(column.get_sort_order()),
+ )
def save_state(self, filename):
"""Saves the listview state (column positions and visibility) to
@@ -311,7 +318,8 @@ class ListView(object):
for f in self.columns[column].status_field:
if field == f:
return self.columns[column].column_indices[
- self.columns[column].status_field.index(f)]
+ self.columns[column].status_field.index(f)
+ ]
def on_menuitem_toggled(self, widget):
"""Callback for the generated column menuitems."""
@@ -392,8 +400,10 @@ class ListView(object):
if column.column_type == 'text':
if add:
tree_column.pack_start(column.renderer, True)
- tree_column.set_col_attributes(column.renderer, add=add,
- text=column.column_indices[column.text_index])
+ tree_column.set_col_attributes(
+ column.renderer, add=add,
+ text=column.column_indices[column.text_index],
+ )
elif column.column_type == 'bool':
if add:
tree_column.pack_start(column.renderer, True)
@@ -409,22 +419,29 @@ class ListView(object):
if add:
tree_column.pack_start(column.renderer, True)
if column.data_func is None:
- tree_column.set_col_attributes(column.renderer, add=add,
- text=column.column_indices[column.text_index],
- value=column.column_indices[column.value_index])
+ tree_column.set_col_attributes(
+ column.renderer, add=add,
+ text=column.column_indices[column.text_index],
+ value=column.column_indices[column.value_index],
+ )
else:
- tree_column.set_cell_data_func(column.renderer, column.data_func,
- tuple(column.column_indices))
+ tree_column.set_cell_data_func(
+ column.renderer, column.data_func,
+ tuple(column.column_indices),
+ )
elif column.column_type == 'texticon':
if add:
tree_column.pack_start(column.renderer[column.pixbuf_index], False)
tree_column.pack_start(column.renderer[column.text_index], True)
- tree_column.set_col_attributes(column.renderer[column.text_index], add=add,
- text=column.column_indices[column.text_index])
+ tree_column.set_col_attributes(
+ column.renderer[column.text_index], add=add,
+ text=column.column_indices[column.text_index],
+ )
if column.data_func is not None:
tree_column.set_cell_data_func(
column.renderer[column.pixbuf_index], column.data_func,
- column.column_indices[column.pixbuf_index])
+ column.column_indices[column.pixbuf_index],
+ )
return True
def remove_column(self, header):
@@ -464,10 +481,12 @@ class ListView(object):
self.create_checklist_menu()
return
- def add_column(self, header, render, col_types, hidden, position,
- status_field, sortid, text=0, value=0, pixbuf=0, function=None,
- column_type=None, sort_func=None, tooltip=None, default=True,
- unique=False, default_sort=False):
+ def add_column(
+ self, header, render, col_types, hidden, position,
+ status_field, sortid, text=0, value=0, pixbuf=0, function=None,
+ column_type=None, sort_func=None, tooltip=None, default=True,
+ unique=False, default_sort=False,
+ ):
"""Adds a column to the ListView"""
# Add the column types to liststore_columns
column_indices = []
@@ -524,8 +543,10 @@ class ListView(object):
column.set_min_width(20)
column.set_reorderable(True)
column.set_visible(not hidden)
- column.connect('button-press-event',
- self.on_treeview_header_right_clicked)
+ column.connect(
+ 'button-press-event',
+ self.on_treeview_header_right_clicked,
+ )
if tooltip:
column.get_widget().set_tooltip_markup(tooltip)
@@ -563,72 +584,92 @@ class ListView(object):
return True
- def add_text_column(self, header, col_type=str, hidden=False, position=None,
- status_field=None, sortid=0, column_type='text',
- sort_func=None, tooltip=None, default=True, unique=False,
- default_sort=False):
+ def add_text_column(
+ self, header, col_type=str, hidden=False, position=None,
+ status_field=None, sortid=0, column_type='text',
+ sort_func=None, tooltip=None, default=True, unique=False,
+ default_sort=False,
+ ):
"""Add a text column to the listview. Only the header name is required.
"""
render = gtk.CellRendererText()
- self.add_column(header, render, col_type, hidden, position,
- status_field, sortid, column_type=column_type,
- sort_func=sort_func, tooltip=tooltip, default=default,
- unique=unique, default_sort=default_sort)
+ self.add_column(
+ header, render, col_type, hidden, position,
+ status_field, sortid, column_type=column_type,
+ sort_func=sort_func, tooltip=tooltip, default=default,
+ unique=unique, default_sort=default_sort,
+ )
return True
- def add_bool_column(self, header, col_type=bool, hidden=False,
- position=None, status_field=None, sortid=0,
- column_type='bool', tooltip=None, default=True):
+ def add_bool_column(
+ self, header, col_type=bool, hidden=False,
+ position=None, status_field=None, sortid=0,
+ column_type='bool', tooltip=None, default=True,
+ ):
"""Add a bool column to the listview"""
render = gtk.CellRendererToggle()
- self.add_column(header, render, col_type, hidden, position,
- status_field, sortid, column_type=column_type,
- tooltip=tooltip, default=default)
-
- def add_func_column(self, header, function, col_types, sortid=0,
- hidden=False, position=None, status_field=None,
- column_type='func', sort_func=None, tooltip=None, default=True):
+ self.add_column(
+ header, render, col_type, hidden, position,
+ status_field, sortid, column_type=column_type,
+ tooltip=tooltip, default=default,
+ )
+
+ def add_func_column(
+ self, header, function, col_types, sortid=0,
+ hidden=False, position=None, status_field=None,
+ column_type='func', sort_func=None, tooltip=None, default=True,
+ ):
"""Add a function column to the listview. Need a header name, the
function and the column types."""
render = gtk.CellRendererText()
- self.add_column(header, render, col_types, hidden, position,
- status_field, sortid, column_type=column_type,
- function=function, sort_func=sort_func, tooltip=tooltip, default=default)
+ self.add_column(
+ header, render, col_types, hidden, position,
+ status_field, sortid, column_type=column_type,
+ function=function, sort_func=sort_func, tooltip=tooltip, default=default,
+ )
return True
- def add_progress_column(self, header, col_types=None, sortid=0,
- hidden=False, position=None, status_field=None,
- function=None, column_type='progress',
- tooltip=None, sort_func=None, default=True):
+ def add_progress_column(
+ self, header, col_types=None, sortid=0,
+ hidden=False, position=None, status_field=None,
+ function=None, column_type='progress',
+ tooltip=None, sort_func=None, default=True,
+ ):
"""Add a progress column to the listview."""
if col_types is None:
col_types = [float, str]
render = gtk.CellRendererProgress()
- self.add_column(header, render, col_types, hidden, position,
- status_field, sortid, function=function,
- column_type=column_type, value=0, text=1,
- tooltip=tooltip, sort_func=sort_func, default=default)
+ self.add_column(
+ header, render, col_types, hidden, position,
+ status_field, sortid, function=function,
+ column_type=column_type, value=0, text=1,
+ tooltip=tooltip, sort_func=sort_func, default=default,
+ )
return True
- def add_texticon_column(self, header, col_types=None, sortid=1,
- hidden=False, position=None, status_field=None,
- column_type='texticon', function=None, sort_func=None,
- tooltip=None, default=True, default_sort=False):
+ def add_texticon_column(
+ self, header, col_types=None, sortid=1,
+ hidden=False, position=None, status_field=None,
+ column_type='texticon', function=None, sort_func=None,
+ tooltip=None, default=True, default_sort=False,
+ ):
"""Adds a texticon column to the listview."""
if col_types is None:
col_types = [str, str]
render1 = gtk.CellRendererPixbuf()
render2 = gtk.CellRendererText()
- self.add_column(header, (render1, render2), col_types, hidden, position,
- status_field, sortid, column_type=column_type,
- function=function, pixbuf=0, text=1, tooltip=tooltip,
- sort_func=sort_func, default=default, default_sort=default_sort)
+ self.add_column(
+ header, (render1, render2), col_types, hidden, position,
+ status_field, sortid, column_type=column_type,
+ function=function, pixbuf=0, text=1, tooltip=tooltip,
+ sort_func=sort_func, default=default, default_sort=default_sort,
+ )
return True
diff --git a/deluge/ui/gtkui/mainwindow.py b/deluge/ui/gtkui/mainwindow.py
index 8d744b743..c68d0a15e 100644
--- a/deluge/ui/gtkui/mainwindow.py
+++ b/deluge/ui/gtkui/mainwindow.py
@@ -43,7 +43,7 @@ class _GtkBuilderSignalsHolder(object):
if hasattr(self, name):
raise RuntimeError(
'A handler for signal %r has already been registered: %s' %
- (name, getattr(self, name))
+ (name, getattr(self, name)),
)
setattr(self, name, handler)
else:
@@ -72,15 +72,20 @@ class MainWindow(component.Component):
self.main_builder.prev_connect_signals = copy.deepcopy(self.main_builder.connect_signals)
def patched_connect_signals(*a, **k):
- raise RuntimeError('In order to connect signals to this GtkBuilder instance please use '
- '"component.get(\'MainWindow\').connect_signals()"')
+ raise RuntimeError(
+ 'In order to connect signals to this GtkBuilder instance please use '
+ '"component.get(\'MainWindow\').connect_signals()"',
+ )
self.main_builder.connect_signals = patched_connect_signals
# Get Gtk Builder files Main Window, New release dialog, and Tabs.
- for filename in ('main_window.ui', 'main_window.new_release.ui', 'main_window.tabs.ui',
- 'main_window.tabs.menu_file.ui', 'main_window.tabs.menu_peer.ui'):
+ for filename in (
+ 'main_window.ui', 'main_window.new_release.ui', 'main_window.tabs.ui',
+ 'main_window.tabs.menu_file.ui', 'main_window.tabs.menu_peer.ui',
+ ):
self.main_builder.add_from_file(
- resource_filename('deluge.ui.gtkui', os.path.join('glade', filename)))
+ resource_filename('deluge.ui.gtkui', os.path.join('glade', filename)),
+ )
self.window = self.main_builder.get_object('main_window')
self.window.set_icon(deluge.ui.gtkui.common.get_deluge_icon())
@@ -168,7 +173,7 @@ class MainWindow(component.Component):
"""Returns a reference to the main window GTK builder object."""
return self.main_builder
- def quit(self, shutdown=False, restart=False):
+ def quit(self, shutdown=False, restart=False): # noqa: A003 python builtin
"""Quits the GtkUI application.
Args:
@@ -270,8 +275,8 @@ class MainWindow(component.Component):
self.window.set_title(_('D: %s U: %s - Deluge' % (download_rate, upload_rate)))
if self.config['show_rate_in_title']:
client.core.get_session_status(
- ['payload_download_rate', 'payload_upload_rate']
- ).addCallback(_on_get_session_status)
+ ['payload_download_rate', 'payload_upload_rate'],
+ ).addCallback(_on_get_session_status)
def _on_set_show_rate_in_title(self, key, value):
if value:
diff --git a/deluge/ui/gtkui/menubar.py b/deluge/ui/gtkui/menubar.py
index 1bf0cbfe7..a08ce972c 100644
--- a/deluge/ui/gtkui/menubar.py
+++ b/deluge/ui/gtkui/menubar.py
@@ -38,15 +38,15 @@ class MenuBar(component.Component):
self.builder = gtk.Builder()
# Get the torrent menu from the gtk builder file
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.ui'),
))
# Get the torrent options menu from the gtk builder file
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.options.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.options.ui'),
))
# Get the torrent queue menu from the gtk builder file
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.queue.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.queue.ui'),
))
# Attach queue torrent menu
@@ -59,8 +59,10 @@ class MenuBar(component.Component):
self.builder.get_object('download-limit-image').set_from_file(deluge.common.get_pixmap('downloading16.png'))
self.builder.get_object('upload-limit-image').set_from_file(deluge.common.get_pixmap('seeding16.png'))
- for menuitem in ('menuitem_down_speed', 'menuitem_up_speed',
- 'menuitem_max_connections', 'menuitem_upload_slots'):
+ for menuitem in (
+ 'menuitem_down_speed', 'menuitem_up_speed',
+ 'menuitem_max_connections', 'menuitem_upload_slots',
+ ):
submenu = gtk.Menu()
item = gtk.MenuItem(_('Set Unlimited'))
item.set_name(menuitem)
@@ -115,7 +117,7 @@ class MenuBar(component.Component):
self.builder.connect_signals(self)
self.change_sensitivity = [
- 'menuitem_addtorrent'
+ 'menuitem_addtorrent',
]
def start(self):
@@ -125,7 +127,7 @@ class MenuBar(component.Component):
# Only show open_folder menuitem and separator if connected to a localhost daemon.
localhost_items = [
'menuitem_open_folder',
- 'separator4'
+ 'separator4',
]
if client.is_localhost():
for widget in localhost_items:
@@ -146,7 +148,8 @@ class MenuBar(component.Component):
if client.get_auth_level() == deluge.common.AUTH_LEVEL_ADMIN:
# Get known accounts to allow changing ownership
client.core.get_known_accounts().addCallback(
- self._on_known_accounts).addErrback(self._on_known_accounts_fail)
+ self._on_known_accounts,
+ ).addErrback(self._on_known_accounts_fail)
client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
client.register_event_handler('TorrentResumedEvent', self.on_torrentresumed_event)
@@ -232,24 +235,28 @@ class MenuBar(component.Component):
def on_menuitem_pause_activate(self, data=None):
log.debug('on_menuitem_pause_activate')
client.core.pause_torrent(
- component.get('TorrentView').get_selected_torrents())
+ component.get('TorrentView').get_selected_torrents(),
+ )
def on_menuitem_resume_activate(self, data=None):
log.debug('on_menuitem_resume_activate')
client.core.resume_torrent(
- component.get('TorrentView').get_selected_torrents())
+ component.get('TorrentView').get_selected_torrents(),
+ )
def on_menuitem_updatetracker_activate(self, data=None):
log.debug('on_menuitem_updatetracker_activate')
client.core.force_reannounce(
- component.get('TorrentView').get_selected_torrents())
+ component.get('TorrentView').get_selected_torrents(),
+ )
def on_menuitem_edittrackers_activate(self, data=None):
log.debug('on_menuitem_edittrackers_activate')
from deluge.ui.gtkui.edittrackersdialog import EditTrackersDialog
dialog = EditTrackersDialog(
component.get('TorrentView').get_selected_torrent(),
- self.mainwindow.window)
+ self.mainwindow.window,
+ )
dialog.run()
def on_menuitem_remove_activate(self, data=None):
@@ -262,7 +269,8 @@ class MenuBar(component.Component):
def on_menuitem_recheck_activate(self, data=None):
log.debug('on_menuitem_recheck_activate')
client.core.force_recheck(
- component.get('TorrentView').get_selected_torrents())
+ component.get('TorrentView').get_selected_torrents(),
+ )
def on_menuitem_open_folder_activate(self, data=None):
log.debug('on_menuitem_open_folder')
@@ -273,19 +281,21 @@ class MenuBar(component.Component):
deluge.common.show_file(path, timestamp=timestamp)
for torrent_id in component.get('TorrentView').get_selected_torrents():
component.get('SessionProxy').get_torrent_status(
- torrent_id, ['download_location', 'files']).addCallback(_on_torrent_status)
+ torrent_id, ['download_location', 'files'],
+ ).addCallback(_on_torrent_status)
def on_menuitem_move_activate(self, data=None):
log.debug('on_menuitem_move_activate')
component.get('SessionProxy').get_torrent_status(
component.get('TorrentView').get_selected_torrent(),
- ['download_location']).addCallback(self.show_move_storage_dialog)
+ ['download_location'],
+ ).addCallback(self.show_move_storage_dialog)
def show_move_storage_dialog(self, status):
log.debug('show_move_storage_dialog')
builder = gtk.Builder()
builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'move_storage_dialog.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'move_storage_dialog.ui'),
))
# Keep it referenced:
# https://bugzilla.gnome.org/show_bug.cgi?id=546802
@@ -308,11 +318,13 @@ class MenuBar(component.Component):
on_core_result(None)
if response_id == gtk.RESPONSE_OK:
- log.debug('Moving torrents to %s',
- self.move_storage_path_chooser.get_text())
+ log.debug(
+ 'Moving torrents to %s',
+ self.move_storage_path_chooser.get_text(),
+ )
path = self.move_storage_path_chooser.get_text()
client.core.move_storage(
- component.get('TorrentView').get_selected_torrents(), path
+ component.get('TorrentView').get_selected_torrents(), path,
).addCallback(on_core_result)
self.move_storage_dialog.connect('response', on_dialog_response_event)
@@ -371,7 +383,7 @@ class MenuBar(component.Component):
'menuitem_down_speed': 'max_download_speed',
'menuitem_up_speed': 'max_upload_speed',
'menuitem_max_connections': 'max_connections',
- 'menuitem_upload_slots': 'max_upload_slots'
+ 'menuitem_upload_slots': 'max_upload_slots',
}
if widget.get_name() in funcs:
torrent_ids = component.get('TorrentView').get_selected_torrents()
@@ -384,19 +396,27 @@ class MenuBar(component.Component):
'menuitem_up_speed': ['max_upload_speed', 'max_upload_speed'],
'menuitem_max_connections': ['max_connections', 'max_connections_global'],
'menuitem_upload_slots': ['max_upload_slots', 'max_upload_slots_global'],
- 'menuitem_stop_seed_at_ratio': ['stop_ratio', 'stop_seed_ratio']
+ 'menuitem_stop_seed_at_ratio': ['stop_ratio', 'stop_seed_ratio'],
}
other_dialog_info = {
- 'menuitem_down_speed': [_('Download Speed Limit'), _('Set the maximum download speed'),
- _('KiB/s'), 'downloading.svg'],
- 'menuitem_up_speed': [_('Upload Speed Limit'), _('Set the maximum upload speed'),
- _('KiB/s'), 'seeding.svg'],
- 'menuitem_max_connections': [_('Incoming Connections'), _('Set the maximum incoming connections'),
- '', gtk.STOCK_NETWORK],
- 'menuitem_upload_slots': [_('Peer Upload Slots'), _('Set the maximum upload slots'),
- '', gtk.STOCK_SORT_ASCENDING],
- 'menuitem_stop_seed_at_ratio': [_('Stop Seed At Ratio'), 'Stop torrent seeding at ratio', '', None]
+ 'menuitem_down_speed': [
+ _('Download Speed Limit'), _('Set the maximum download speed'),
+ _('KiB/s'), 'downloading.svg',
+ ],
+ 'menuitem_up_speed': [
+ _('Upload Speed Limit'), _('Set the maximum upload speed'),
+ _('KiB/s'), 'seeding.svg',
+ ],
+ 'menuitem_max_connections': [
+ _('Incoming Connections'), _('Set the maximum incoming connections'),
+ '', gtk.STOCK_NETWORK,
+ ],
+ 'menuitem_upload_slots': [
+ _('Peer Upload Slots'), _('Set the maximum upload slots'),
+ '', gtk.STOCK_SORT_ASCENDING,
+ ],
+ 'menuitem_stop_seed_at_ratio': [_('Stop Seed At Ratio'), 'Stop torrent seeding at ratio', '', None],
}
core_key = status_map[widget.get_name()][0]
@@ -429,16 +449,22 @@ class MenuBar(component.Component):
d.addCallback(_on_torrent_status)
def on_menuitem_set_automanaged_on(self, widget):
- client.core.set_torrent_options(component.get('TorrentView').get_selected_torrents(),
- {'auto_managed': True})
+ client.core.set_torrent_options(
+ component.get('TorrentView').get_selected_torrents(),
+ {'auto_managed': True},
+ )
def on_menuitem_set_automanaged_off(self, widget):
- client.core.set_torrent_options(component.get('TorrentView').get_selected_torrents(),
- {'auto_managed': False})
+ client.core.set_torrent_options(
+ component.get('TorrentView').get_selected_torrents(),
+ {'auto_managed': False},
+ )
def on_menuitem_set_stop_seed_at_ratio_disable(self, widget):
- client.core.set_torrent_options(component.get('TorrentView').get_selected_torrents(),
- {'stop_at_ratio': False})
+ client.core.set_torrent_options(
+ component.get('TorrentView').get_selected_torrents(),
+ {'stop_at_ratio': False},
+ )
def on_menuitem_sidebar_zero_toggled(self, widget):
self.config['sidebar_show_zero'] = widget.get_active()
@@ -484,7 +510,7 @@ class MenuBar(component.Component):
self.change_owner_submenu_items[None].set_active(True)
self.change_owner_submenu_items[None].hide()
self.builder.get_object('menuitem_change_owner').connect(
- 'activate', self._on_change_owner_submenu_active
+ 'activate', self._on_change_owner_submenu_active,
)
self.builder.get_object('menuitem_change_owner').set_submenu(self.change_owner_submenu)
@@ -518,7 +544,8 @@ class MenuBar(component.Component):
ErrorDialog(
_('Ownership Change Error'),
_('There was an error while trying changing ownership.'),
- self.mainwindow.window, details=failure.value.logable()
+ self.mainwindow.window, details=failure.value.logable(),
).run()
client.core.set_torrent_options(
- update_torrents, {'owner': username}).addErrback(failed_change_owner)
+ update_torrents, {'owner': username},
+ ).addErrback(failed_change_owner)
diff --git a/deluge/ui/gtkui/new_release_dialog.py b/deluge/ui/gtkui/new_release_dialog.py
index 5f2871f2c..c9df8a5bc 100644
--- a/deluge/ui/gtkui/new_release_dialog.py
+++ b/deluge/ui/gtkui/new_release_dialog.py
@@ -27,17 +27,21 @@ class NewReleaseDialog(object):
# Set the version labels
if deluge.common.windows_check() or deluge.common.osx_check():
main_builder.get_object('image_new_release').set_from_file(
- deluge.common.get_pixmap('deluge16.png'))
+ deluge.common.get_pixmap('deluge16.png'),
+ )
else:
main_builder.get_object('image_new_release').set_from_icon_name('deluge', 4)
main_builder.get_object('label_available_version').set_text(available_version)
main_builder.get_object('label_client_version').set_text(
- deluge.common.get_version())
+ deluge.common.get_version(),
+ )
self.chk_not_show_dialog = main_builder.get_object('chk_do_not_show_new_release')
main_builder.get_object('button_goto_downloads').connect(
- 'clicked', self._on_button_goto_downloads)
+ 'clicked', self._on_button_goto_downloads,
+ )
main_builder.get_object('button_close_new_release').connect(
- 'clicked', self._on_button_close_new_release)
+ 'clicked', self._on_button_close_new_release,
+ )
if client.connected():
def on_info(version):
diff --git a/deluge/ui/gtkui/options_tab.py b/deluge/ui/gtkui/options_tab.py
index 16e323d85..6fdb13d2e 100644
--- a/deluge/ui/gtkui/options_tab.py
+++ b/deluge/ui/gtkui/options_tab.py
@@ -50,9 +50,11 @@ class OptionsTab(Tab):
self.move_completed_path_chooser = PathChooser('move_completed_paths_list')
self.move_completed_path_chooser.set_sensitive(
- self.tab_widgets['chk_move_completed'].obj.get_active())
+ self.tab_widgets['chk_move_completed'].obj.get_active(),
+ )
self.move_completed_path_chooser.connect(
- 'text-changed', self.on_path_chooser_text_changed_event)
+ 'text-changed', self.on_path_chooser_text_changed_event,
+ )
self.status_keys.append('move_completed_path')
self.move_completed_hbox = self.main_builder.get_object('hbox_move_completed_path_chooser')
@@ -83,8 +85,8 @@ class OptionsTab(Tab):
self.clear()
component.get('SessionProxy').get_torrents_status(
- {'id': torrent_ids}, self.status_keys
- ).addCallback(self.parse_torrents_statuses)
+ {'id': torrent_ids}, self.status_keys,
+ ).addCallback(self.parse_torrents_statuses)
self.prev_torrent_ids = torrent_ids
@@ -159,7 +161,8 @@ class OptionsTab(Tab):
continue # A label so read-only
widget_value = getattr(widget.obj, 'get_' + widget.func)()
if widget_value != self.prev_status[status_key] or (
- status_key in self.inconsistent_keys and not widget.obj.get_inconsistent()):
+ status_key in self.inconsistent_keys and not widget.obj.get_inconsistent()
+ ):
options[status_key] = widget_value
if options.get('move_completed', False):
diff --git a/deluge/ui/gtkui/path_combo_chooser.py b/deluge/ui/gtkui/path_combo_chooser.py
index b7d73da19..f45335623 100755
--- a/deluge/ui/gtkui/path_combo_chooser.py
+++ b/deluge/ui/gtkui/path_combo_chooser.py
@@ -76,8 +76,10 @@ class ValueList(object):
values.append(row[0])
return values
- def add_values(self, paths, append=True, scroll_to_row=False,
- clear=False, emit_signal=False):
+ def add_values(
+ self, paths, append=True, scroll_to_row=False,
+ clear=False, emit_signal=False,
+ ):
"""
Add paths to the liststore
@@ -193,8 +195,10 @@ class ValueList(object):
state = event.get_state() & gtk.accelerator_get_default_mod_mask()
if keyval == keysyms.Escape or\
- (key_is_up(keyval) and
- state == gdk.MOD1_MASK): # ALT Key
+ (
+ key_is_up(keyval) and
+ state == gdk.MOD1_MASK
+ ): # ALT Key
self.popdown()
return True
# Set entry value to the selected row
@@ -299,8 +303,10 @@ class ValueList(object):
if swap:
p1 = self.tree_store[path][0]
p2 = self.tree_store[new_path][0]
- self.tree_store.swap(self.tree_store.get_iter(path),
- self.tree_store.get_iter(new_path))
+ self.tree_store.swap(
+ self.tree_store.get_iter(path),
+ self.tree_store.get_iter(new_path),
+ )
self.emit('list-values-reordered', [p1, p2])
self.emit('list-values-changed', self.get_values())
path = new_path
@@ -423,8 +429,10 @@ class StoredValuesList(ValueList):
elif key_is_up_or_down(keyval):
# Swap the row value
if event.get_state() & gdk.CONTROL_MASK:
- self.handle_list_scroll(_next=key_is_down(keyval),
- swap=True)
+ self.handle_list_scroll(
+ _next=key_is_down(keyval),
+ swap=True,
+ )
else:
self.handle_list_scroll(_next=key_is_down(keyval))
elif key_is_pgup_or_pgdown(event.keyval):
@@ -628,8 +636,10 @@ class PathChooserPopup(object):
# Not enough space downwards on the screen
elif y - height >= monitor.y:
y -= height
- elif (monitor.y + monitor.height - (y + self.path_entry.get_allocation().height) >
- y - monitor.y):
+ elif (
+ monitor.y + monitor.height - (y + self.path_entry.get_allocation().height) >
+ y - monitor.y
+ ):
y += self.path_entry.get_allocation().height
height = monitor.y + monitor.height - y
else:
@@ -640,11 +650,15 @@ class PathChooserPopup(object):
def popup_grab_window(self):
activate_time = 0
- if gdk.pointer_grab(self.popup_window.get_window(), True,
- (gdk.BUTTON_PRESS_MASK |
- gdk.BUTTON_RELEASE_MASK |
- gdk.POINTER_MOTION_MASK),
- None, None, activate_time) == 0:
+ if gdk.pointer_grab(
+ self.popup_window.get_window(), True,
+ (
+ gdk.BUTTON_PRESS_MASK |
+ gdk.BUTTON_RELEASE_MASK |
+ gdk.POINTER_MOTION_MASK
+ ),
+ None, None, activate_time,
+ ) == 0:
if gdk.keyboard_grab(self.popup_window.get_window(), True, activate_time) == 0:
return True
else:
@@ -682,8 +696,11 @@ class PathChooserPopup(object):
# Also if the intersection of self and the event is empty, hide
# the path_list
if (tuple(self.popup_window.get_allocation().intersect(
- gdk.Rectangle(x=int(event.x), y=int(event.y),
- width=1, height=1))) == (0, 0, 0, 0)):
+ gdk.Rectangle(
+ x=int(event.x), y=int(event.y),
+ width=1, height=1,
+ ),
+ )) == (0, 0, 0, 0)):
hide = True
# Toplevel is the window that received the event, and parent is the
# path_list window. If they are not the same, means the popup should
@@ -776,8 +793,10 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup):
"""
swap = event.get_state() & gdk.CONTROL_MASK
scroll_window = event.get_state() & gdk.SHIFT_MASK
- self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN,
- set_entry=widget != self.treeview, swap=swap, scroll_window=scroll_window)
+ self.handle_list_scroll(
+ _next=event.direction == gdk.SCROLL_DOWN,
+ set_entry=widget != self.treeview, swap=swap, scroll_window=scroll_window,
+ )
return True
def on_buttonbox_key_press_event(self, widget, event):
@@ -898,8 +917,10 @@ class PathCompletionPopup(CompletionList, PathChooserPopup):
"""
x, y, state = event.window.get_pointer()
- self.handle_list_scroll(_next=event.direction == gdk.SCROLL_DOWN,
- set_entry=widget != self.treeview, scroll_window=True)
+ self.handle_list_scroll(
+ _next=event.direction == gdk.SCROLL_DOWN,
+ set_entry=widget != self.treeview, scroll_window=True,
+ )
path = self.treeview.get_path_at_pos(int(x), int(y))
if path:
self.handle_list_scroll(path=path[0], _next=None)
@@ -1031,7 +1052,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, GObject):
self.builder = gtk.Builder()
self.popup_buttonbox = self.builder.get_object('buttonbox')
self.builder.add_from_file(resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'path_combo_chooser.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'path_combo_chooser.ui'),
))
self.button_toggle = self.builder.get_object('button_toggle_dropdown')
self.text_entry = self.builder.get_object('entry_text')
@@ -1298,8 +1319,10 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, GObject):
# Select new row with arrow up/down is pressed
if key_is_up_or_down(keyval):
- self.handle_list_scroll(_next=key_is_down(keyval),
- set_entry=True)
+ self.handle_list_scroll(
+ _next=key_is_down(keyval),
+ set_entry=True,
+ )
return True
elif self.auto_completer.is_auto_completion_accelerator(keyval, state):
if self.auto_completer.auto_complete_enabled:
@@ -1520,13 +1543,15 @@ if __name__ == '__main__':
'/media/Series/2',
'/media/Series/17',
'/media/Series/18',
- '/media/Series/19'
+ '/media/Series/19',
]
entry1.add_values(test_paths)
entry1.set_text('/home/bro/', default_text=True)
- entry2.set_text('/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/',
- cursor_end=False)
+ entry2.set_text(
+ '/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/',
+ cursor_end=False,
+ )
entry2.set_filechooser_button_visible(False)
# entry2.set_enable_properties(False)
diff --git a/deluge/ui/gtkui/peers_tab.py b/deluge/ui/gtkui/peers_tab.py
index a989edef3..ca2fd6366 100644
--- a/deluge/ui/gtkui/peers_tab.py
+++ b/deluge/ui/gtkui/peers_tab.py
@@ -152,13 +152,13 @@ class PeersTab(Tab):
state = {
'columns': {},
'sort_id': column_id,
- 'sort_order': int(sort_order) if sort_order else None
+ 'sort_order': int(sort_order) if sort_order else None,
}
for index, column in enumerate(self.listview.get_columns()):
state['columns'][column.get_title()] = {
'position': index,
- 'width': column.get_width()
+ 'width': column.get_width(),
}
save_pickled_state_file('peers_tab.state', state)
@@ -221,7 +221,9 @@ class PeersTab(Tab):
self.cached_flag_pixbufs[country] = pixbuf_new_from_file(
deluge.common.resource_filename(
'deluge',
- os.path.join('ui', 'data', 'pixmaps', 'flags', country.lower() + '.png')))
+ os.path.join('ui', 'data', 'pixmaps', 'flags', country.lower() + '.png'),
+ ),
+ )
except Exception as ex:
log.debug('Unable to load flag: %s', ex)
return None
@@ -263,8 +265,10 @@ class PeersTab(Tab):
# Create an int IP address for sorting purposes
if peer['ip'].count(':') == 1:
# This is an IPv4 address
- ip_int = sum([int(byte) << shift
- for byte, shift in zip(peer['ip'].split(':')[0].split('.'), (24, 16, 8, 0))])
+ ip_int = sum(
+ int(byte) << shift
+ for byte, shift in zip(peer['ip'].split(':')[0].split('.'), (24, 16, 8, 0))
+ )
peer_ip = peer['ip']
else:
# This is an IPv6 address
@@ -289,7 +293,8 @@ class PeersTab(Tab):
peer['country'],
float(ip_int),
icon,
- peer['progress']])
+ peer['progress'],
+ ])
self.peers[peer['ip']] = row
@@ -319,8 +324,10 @@ class PeersTab(Tab):
if country_code != ' ' and country_code in COUNTRIES:
tooltip.set_text(COUNTRIES[country_code])
# widget here is self.listview
- widget.set_tooltip_cell(tooltip, path, widget.get_column(0),
- None)
+ widget.set_tooltip_cell(
+ tooltip, path, widget.get_column(0),
+ None,
+ )
return True
else:
return False
@@ -330,7 +337,7 @@ class PeersTab(Tab):
log.debug('on_menuitem_add_peer')
builder = Builder()
builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'connect_peer_dialog.ui')
+ 'deluge.ui.gtkui', os.path.join('glade', 'connect_peer_dialog.ui'),
))
peer_dialog = builder.get_object('connect_peer_dialog')
txt_ip = builder.get_object('txt_ip')
diff --git a/deluge/ui/gtkui/piecesbar.py b/deluge/ui/gtkui/piecesbar.py
index 43c7c7080..2819540a4 100644
--- a/deluge/ui/gtkui/piecesbar.py
+++ b/deluge/ui/gtkui/piecesbar.py
@@ -117,8 +117,10 @@ class PiecesBar(DrawingArea):
pieces = [COLOR_STATES.index('completed')] * self.num_pieces
start_pos = 0
piece_width = self.width / len(pieces)
- pieces_colors = [[color / 65535 for color in self.gtkui_config['pieces_color_%s' % state]]
- for state in COLOR_STATES]
+ pieces_colors = [
+ [color / 65535 for color in self.gtkui_config['pieces_color_%s' % state]]
+ for state in COLOR_STATES
+ ]
for state in pieces:
ctx.set_source_rgb(*pieces_colors[state])
ctx.rectangle(start_pos, 0, piece_width, self.height)
diff --git a/deluge/ui/gtkui/pluginmanager.py b/deluge/ui/gtkui/pluginmanager.py
index 5cabee010..0e0797877 100644
--- a/deluge/ui/gtkui/pluginmanager.py
+++ b/deluge/ui/gtkui/pluginmanager.py
@@ -24,11 +24,12 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
component.Component.__init__(self, 'PluginManager')
self.config = ConfigManager('gtkui.conf')
deluge.pluginmanagerbase.PluginManagerBase.__init__(
- self, 'gtkui.conf', 'deluge.plugin.gtkui')
+ self, 'gtkui.conf', 'deluge.plugin.gtkui',
+ )
self.hooks = {
'on_apply_prefs': [],
- 'on_show_prefs': []
+ 'on_show_prefs': [],
}
client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event)
diff --git a/deluge/ui/gtkui/preferences.py b/deluge/ui/gtkui/preferences.py
index ba4f80f03..ab7619c83 100644
--- a/deluge/ui/gtkui/preferences.py
+++ b/deluge/ui/gtkui/preferences.py
@@ -48,7 +48,7 @@ COLOR_STATES = {
'missing': COLOR_MISSING,
'waiting': COLOR_WAITING,
'downloading': COLOR_DOWNLOADING,
- 'completed': COLOR_COMPLETED
+ 'completed': COLOR_COMPLETED,
}
@@ -57,7 +57,8 @@ class Preferences(component.Component):
component.Component.__init__(self, 'Preferences')
self.builder = gtk.Builder()
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'preferences_dialog.ui')))
+ 'deluge.ui.gtkui', os.path.join('glade', 'preferences_dialog.ui'),
+ ))
self.pref_dialog = self.builder.get_object('pref_dialog')
self.pref_dialog.set_transient_for(component.get('MainWindow').window)
self.pref_dialog.set_icon(get_deluge_icon())
@@ -69,7 +70,8 @@ class Preferences(component.Component):
self.load_pref_dialog_state()
self.builder.get_object('image_magnet').set_from_file(
- deluge.common.get_pixmap('magnet.png'))
+ deluge.common.get_pixmap('magnet.png'),
+ )
# Hide the unused associate magnet button on OSX see: #2420
if deluge.common.osx_check():
@@ -85,7 +87,8 @@ class Preferences(component.Component):
# Add the default categories
prefs_categories = (
'interface', 'downloads', 'bandwidth', 'queue', 'network', 'proxy',
- 'cache', 'other', 'daemon', 'plugins')
+ 'cache', 'other', 'daemon', 'plugins',
+ )
for idx, category in enumerate(prefs_categories):
self.liststore.append([idx, category, PREFS_CATOG_TRANS[category]])
@@ -105,9 +108,11 @@ class Preferences(component.Component):
self.accounts_liststore.set_sort_column_id(ACCOUNTS_USERNAME, gtk.SORT_ASCENDING)
self.accounts_listview = self.builder.get_object('accounts_listview')
self.accounts_listview.append_column(
- gtk.TreeViewColumn(_('Username'), gtk.CellRendererText(), text=ACCOUNTS_USERNAME))
+ gtk.TreeViewColumn(_('Username'), gtk.CellRendererText(), text=ACCOUNTS_USERNAME),
+ )
self.accounts_listview.append_column(
- gtk.TreeViewColumn(_('Level'), gtk.CellRendererText(), text=ACCOUNTS_LEVEL))
+ gtk.TreeViewColumn(_('Level'), gtk.CellRendererText(), text=ACCOUNTS_LEVEL),
+ )
password_column = gtk.TreeViewColumn('password', gtk.CellRendererText(), text=ACCOUNTS_PASSWORD)
self.accounts_listview.append_column(password_column)
password_column.set_visible(False)
@@ -440,7 +445,8 @@ class Preferences(component.Component):
self.builder.get_object('radio_thinclient').set_active(not self.gtkui_config['standalone'])
self.builder.get_object('chk_show_rate_in_title').set_active(self.gtkui_config['show_rate_in_title'])
self.builder.get_object('chk_focus_main_window_on_add').set_active(
- self.gtkui_config['focus_main_window_on_add'])
+ self.gtkui_config['focus_main_window_on_add'],
+ )
self.builder.get_object('piecesbar_toggle').set_active(self.gtkui_config['show_piecesbar'])
self.__set_color('completed', from_config=True)
self.__set_color('downloading', from_config=True)
@@ -488,25 +494,30 @@ class Preferences(component.Component):
for state in ('missing', 'waiting', 'downloading', 'completed'):
color = self.builder.get_object('%s_color' % state).get_color()
new_gtkui_config['pieces_color_%s' % state] = [
- color.red, color.green, color.blue
+ color.red, color.green, color.blue,
]
new_core_config['copy_torrent_file'] = self.builder.get_object(
- 'chk_copy_torrent_file').get_active()
+ 'chk_copy_torrent_file',
+ ).get_active()
new_core_config['del_copy_torrent_file'] = self.builder.get_object(
- 'chk_del_copy_torrent_file').get_active()
+ 'chk_del_copy_torrent_file',
+ ).get_active()
new_core_config['move_completed'] = self.builder.get_object('chk_move_completed').get_active()
new_core_config['download_location'] = self.download_location_path_chooser.get_text()
new_core_config['move_completed_path'] = self.move_completed_path_chooser.get_text()
new_core_config['torrentfiles_location'] = self.copy_torrent_files_path_chooser.get_text()
new_core_config['prioritize_first_last_pieces'] = self.builder.get_object(
- 'chk_prioritize_first_last_pieces').get_active()
+ 'chk_prioritize_first_last_pieces',
+ ).get_active()
new_core_config['sequential_download'] = self.builder.get_object(
- 'chk_sequential_download').get_active()
+ 'chk_sequential_download',
+ ).get_active()
new_core_config['add_paused'] = self.builder.get_object('chk_add_paused').get_active()
new_core_config['pre_allocate_storage'] = self.builder.get_object(
- 'chk_pre_allocation').get_active()
+ 'chk_pre_allocation',
+ ).get_active()
# Network tab #
listen_ports = [self.builder.get_object('spin_incoming_port').get_value_as_int()] * 2
@@ -514,11 +525,12 @@ class Preferences(component.Component):
new_core_config['random_port'] = self.builder.get_object('chk_random_incoming_port').get_active()
outgoing_ports = (
self.builder.get_object('spin_outgoing_port_min').get_value_as_int(),
- self.builder.get_object('spin_outgoing_port_max').get_value_as_int()
+ self.builder.get_object('spin_outgoing_port_max').get_value_as_int(),
)
new_core_config['outgoing_ports'] = outgoing_ports
new_core_config['random_outgoing_ports'] = self.builder.get_object(
- 'chk_random_outgoing_ports').get_active()
+ 'chk_random_outgoing_ports',
+ ).get_active()
incoming_address = self.builder.get_object('entry_interface').get_text().strip()
outgoing_address = self.builder.get_object('entry_outgoing_interface').get_text().strip()
if deluge.common.is_ip(incoming_address) or not incoming_address:
@@ -537,27 +549,37 @@ class Preferences(component.Component):
# Bandwidth tab #
new_core_config['max_connections_global'] = self.builder.get_object(
- 'spin_max_connections_global').get_value_as_int()
+ 'spin_max_connections_global',
+ ).get_value_as_int()
new_core_config['max_download_speed'] = self.builder.get_object('spin_max_download').get_value()
new_core_config['max_upload_speed'] = self.builder.get_object('spin_max_upload').get_value()
new_core_config['max_upload_slots_global'] = self.builder.get_object(
- 'spin_max_upload_slots_global').get_value_as_int()
+ 'spin_max_upload_slots_global',
+ ).get_value_as_int()
new_core_config['max_half_open_connections'] = self.builder.get_object(
- 'spin_max_half_open_connections').get_value_as_int()
+ 'spin_max_half_open_connections',
+ ).get_value_as_int()
new_core_config['max_connections_per_second'] = self.builder.get_object(
- 'spin_max_connections_per_second').get_value_as_int()
+ 'spin_max_connections_per_second',
+ ).get_value_as_int()
new_core_config['max_connections_per_torrent'] = self.builder.get_object(
- 'spin_max_connections_per_torrent').get_value_as_int()
+ 'spin_max_connections_per_torrent',
+ ).get_value_as_int()
new_core_config['max_upload_slots_per_torrent'] = self.builder.get_object(
- 'spin_max_upload_slots_per_torrent').get_value_as_int()
+ 'spin_max_upload_slots_per_torrent',
+ ).get_value_as_int()
new_core_config['max_upload_speed_per_torrent'] = self.builder.get_object(
- 'spin_max_upload_per_torrent').get_value()
+ 'spin_max_upload_per_torrent',
+ ).get_value()
new_core_config['max_download_speed_per_torrent'] = self.builder.get_object(
- 'spin_max_download_per_torrent').get_value()
+ 'spin_max_download_per_torrent',
+ ).get_value()
new_core_config['ignore_limits_on_local_network'] = self.builder.get_object(
- 'chk_ignore_limits_on_local_network').get_active()
+ 'chk_ignore_limits_on_local_network',
+ ).get_active()
new_core_config['rate_limit_ip_overhead'] = self.builder.get_object(
- 'chk_rate_limit_ip_overhead').get_active()
+ 'chk_rate_limit_ip_overhead',
+ ).get_active()
# Interface tab #
new_gtkui_config['enable_system_tray'] = self.builder.get_object('chk_use_tray').get_active()
@@ -574,20 +596,24 @@ class Preferences(component.Component):
new_gtkui_config['standalone'] = new_gtkui_standalone
new_gtkui_config['show_rate_in_title'] = self.builder.get_object(
- 'chk_show_rate_in_title').get_active()
+ 'chk_show_rate_in_title',
+ ).get_active()
new_gtkui_config['focus_main_window_on_add'] = self.builder.get_object(
- 'chk_focus_main_window_on_add').get_active()
+ 'chk_focus_main_window_on_add',
+ ).get_active()
# Other tab #
new_gtkui_config['show_new_releases'] = self.builder.get_object(
- 'chk_show_new_releases').get_active()
+ 'chk_show_new_releases',
+ ).get_active()
new_core_config['send_info'] = self.builder.get_object('chk_send_info').get_active()
new_core_config['geoip_db_location'] = self.builder.get_object('entry_geoip').get_text()
# Daemon tab #
new_core_config['daemon_port'] = self.builder.get_object('spin_daemon_port').get_value_as_int()
new_core_config['allow_remote'] = self.builder.get_object(
- 'chk_allow_remote_connections').get_active()
+ 'chk_allow_remote_connections',
+ ).get_active()
new_core_config['new_release_check'] = self.builder.get_object('chk_new_releases').get_active()
# Proxy tab #
@@ -601,28 +627,35 @@ class Preferences(component.Component):
'proxy_peer_connections': self.builder.get_object('chk_proxy_peer_conn').get_active(),
'proxy_tracker_connections': self.builder.get_object('chk_proxy_tracker_conn').get_active(),
'force_proxy': self.builder.get_object('chk_force_proxy').get_active(),
- 'anonymous_mode': self.builder.get_object('chk_anonymous_mode').get_active()
+ 'anonymous_mode': self.builder.get_object('chk_anonymous_mode').get_active(),
}
# Queue tab #
new_core_config['queue_new_to_top'] = self.builder.get_object('chk_queue_new_top').get_active()
new_core_config['max_active_seeding'] = self.builder.get_object(
- 'spin_seeding').get_value_as_int()
+ 'spin_seeding',
+ ).get_value_as_int()
new_core_config['max_active_downloading'] = self.builder.get_object(
- 'spin_downloading').get_value_as_int()
+ 'spin_downloading',
+ ).get_value_as_int()
new_core_config['max_active_limit'] = self.builder.get_object('spin_active').get_value_as_int()
new_core_config['dont_count_slow_torrents'] = self.builder.get_object(
- 'chk_dont_count_slow_torrents').get_active()
+ 'chk_dont_count_slow_torrents',
+ ).get_active()
new_core_config['auto_manage_prefer_seeds'] = self.builder.get_object(
- 'chk_auto_manage_prefer_seeds').get_active()
+ 'chk_auto_manage_prefer_seeds',
+ ).get_active()
new_core_config['stop_seed_at_ratio'] = self.builder.get_object('chk_share_ratio').get_active()
new_core_config['remove_seed_at_ratio'] = self.builder.get_object(
- 'radio_remove_ratio').get_active()
+ 'radio_remove_ratio',
+ ).get_active()
new_core_config['stop_seed_ratio'] = self.builder.get_object('spin_share_ratio').get_value()
new_core_config['share_ratio_limit'] = self.builder.get_object(
- 'spin_share_ratio_limit').get_value()
+ 'spin_share_ratio_limit',
+ ).get_value()
new_core_config['seed_time_ratio_limit'] = self.builder.get_object(
- 'spin_seed_time_ratio_limit').get_value()
+ 'spin_seed_time_ratio_limit',
+ ).get_value()
new_core_config['seed_time_limit'] = self.builder.get_object('spin_seed_time_limit').get_value()
# Cache tab #
@@ -640,7 +673,7 @@ class Preferences(component.Component):
if active == -1:
dialog = InformationDialog(
_('Attention'),
- _('You must choose a language')
+ _('You must choose a language'),
)
dialog.run()
return
@@ -651,7 +684,7 @@ class Preferences(component.Component):
if new_gtkui_config['language'] != self.gtkui_config['language']:
dialog = InformationDialog(
_('Attention'),
- _('You must now restart the deluge UI for the changes to take effect.')
+ _('You must now restart the deluge UI for the changes to take effect.'),
)
dialog.run()
@@ -693,13 +726,15 @@ class Preferences(component.Component):
else:
self.gtkui_config['standalone'] = not new_gtkui_standalone
self.builder.get_object('radio_standalone').set_active(
- self.gtkui_config['standalone'])
+ self.gtkui_config['standalone'],
+ )
self.builder.get_object('radio_thinclient').set_active(
- not self.gtkui_config['standalone'])
+ not self.gtkui_config['standalone'],
+ )
mode = 'Thinclient' if was_standalone else 'Standalone'
dialog = YesNoDialog(
_('Switching Deluge Client Mode...'),
- _('Do you want to restart to use %s mode?' % mode)
+ _('Do you want to restart to use %s mode?' % mode),
)
dialog.run().addCallback(on_response)
@@ -710,11 +745,13 @@ class Preferences(component.Component):
def __update_cache_status(self):
# Updates the cache status labels with the info in the dict
- cache_labels = ('label_cache_read_ops', 'label_cache_write_ops',
- 'label_cache_num_blocks_read', 'label_cache_num_blocks_written',
- 'label_cache_read_hit_ratio', 'label_cache_write_hit_ratio',
- 'label_cache_num_blocks_cache_hits', 'label_cache_disk_blocks_in_use',
- 'label_cache_read_cache_blocks')
+ cache_labels = (
+ 'label_cache_read_ops', 'label_cache_write_ops',
+ 'label_cache_num_blocks_read', 'label_cache_num_blocks_written',
+ 'label_cache_read_hit_ratio', 'label_cache_write_hit_ratio',
+ 'label_cache_num_blocks_cache_hits', 'label_cache_disk_blocks_in_use',
+ 'label_cache_read_cache_blocks',
+ )
for widget_name in cache_labels:
widget = self.builder.get_object(widget_name)
@@ -760,30 +797,42 @@ class Preferences(component.Component):
path_choosers = {
'download_location_path_chooser': self.download_location_path_chooser,
'move_completed_path_chooser': self.move_completed_path_chooser,
- 'torrentfiles_location_path_chooser': self.copy_torrent_files_path_chooser
+ 'torrentfiles_location_path_chooser': self.copy_torrent_files_path_chooser,
}
dependents = {
'chk_show_dialog': {'chk_focus_dialog': True},
'chk_random_incoming_port': {'spin_incoming_port': False},
- 'chk_random_outgoing_ports': {'spin_outgoing_port_min': False,
- 'spin_outgoing_port_max': False},
- 'chk_use_tray': {'radio_appind': True,
- 'radio_systray': True,
- 'chk_min_on_close': True,
- 'chk_start_in_tray': True,
- 'alignment_tray_type': True,
- 'chk_lock_tray': True},
- 'chk_lock_tray': {'txt_tray_password': True,
- 'password_label': True},
- 'radio_open_folder_custom': {'combo_file_manager': False,
- 'txt_open_folder_location': True},
+ 'chk_random_outgoing_ports': {
+ 'spin_outgoing_port_min': False,
+ 'spin_outgoing_port_max': False,
+ },
+ 'chk_use_tray': {
+ 'radio_appind': True,
+ 'radio_systray': True,
+ 'chk_min_on_close': True,
+ 'chk_start_in_tray': True,
+ 'alignment_tray_type': True,
+ 'chk_lock_tray': True,
+ },
+ 'chk_lock_tray': {
+ 'txt_tray_password': True,
+ 'password_label': True,
+ },
+ 'radio_open_folder_custom': {
+ 'combo_file_manager': False,
+ 'txt_open_folder_location': True,
+ },
'chk_move_completed': {'move_completed_path_chooser': True},
- 'chk_copy_torrent_file': {'torrentfiles_location_path_chooser': True,
- 'chk_del_copy_torrent_file': True},
- 'chk_share_ratio': {'spin_share_ratio': True,
- 'radio_pause_ratio': True,
- 'radio_remove_ratio': True}
+ 'chk_copy_torrent_file': {
+ 'torrentfiles_location_path_chooser': True,
+ 'chk_del_copy_torrent_file': True,
+ },
+ 'chk_share_ratio': {
+ 'spin_share_ratio': True,
+ 'radio_pause_ratio': True,
+ 'radio_remove_ratio': True,
+ },
}
def update_dependent_widgets(name, value):
@@ -883,7 +932,7 @@ class Preferences(component.Component):
_('Select the Plugin'),
self.pref_dialog,
gtk.FILE_CHOOSER_ACTION_OPEN,
- buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
+ buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK),
)
chooser.set_transient_for(self.pref_dialog)
@@ -909,7 +958,8 @@ class Preferences(component.Component):
filename = os.path.split(filepath)[1]
shutil.copyfile(
filepath,
- os.path.join(get_config_dir(), 'plugins', filename))
+ os.path.join(get_config_dir(), 'plugins', filename),
+ )
component.get('PluginManager').scan_for_plugins()
@@ -949,17 +999,20 @@ class Preferences(component.Component):
proxy_entries = [
'label_proxy_host', 'entry_proxy_host', 'label_proxy_port', 'spin_proxy_port',
'label_proxy_pass', 'entry_proxy_pass', 'label_proxy_user', 'entry_proxy_user',
- 'chk_proxy_host_resolve', 'chk_proxy_peer_conn', 'chk_proxy_tracker_conn']
+ 'chk_proxy_host_resolve', 'chk_proxy_peer_conn', 'chk_proxy_tracker_conn',
+ ]
# 0: None, 1: Socks4, 2: Socks5, 3: Socks5 Auth, 4: HTTP, 5: HTTP Auth, 6: I2P
show_entries = []
if proxy_type > 0:
show_entries.extend([
'label_proxy_host', 'entry_proxy_host', 'label_proxy_port', 'spin_proxy_port',
- 'chk_proxy_peer_conn', 'chk_proxy_tracker_conn'])
+ 'chk_proxy_peer_conn', 'chk_proxy_tracker_conn',
+ ])
if proxy_type in (3, 5):
show_entries.extend([
- 'label_proxy_pass', 'entry_proxy_pass', 'label_proxy_user', 'entry_proxy_user'])
+ 'label_proxy_pass', 'entry_proxy_pass', 'label_proxy_user', 'entry_proxy_user',
+ ])
if proxy_type in (2, 3, 4, 5):
show_entries.extend(['chk_proxy_host_resolve'])
@@ -999,7 +1052,7 @@ class Preferences(component.Component):
ErrorDialog(
_('Server Side Error'),
_('An error occurred on the server'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
client.core.get_known_accounts().addCallback(on_ok).addErrback(on_fail)
@@ -1054,18 +1107,18 @@ class Preferences(component.Component):
ErrorDialog(
_('Error Adding Account'),
_('Authentication failed'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
else:
ErrorDialog(
_('Error Adding Account'),
_('An error occurred while adding account'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
if response_id == gtk.RESPONSE_OK:
client.core.create_account(
- username, password, authlevel
+ username, password, authlevel,
).addCallback(add_ok).addErrback(add_fail)
dialog.run().addCallback(dialog_finished)
@@ -1080,7 +1133,7 @@ class Preferences(component.Component):
model[itr][ACCOUNTS_PASSWORD],
model[itr][ACCOUNTS_LEVEL],
levels_mapping=client.auth_levels_mapping,
- parent=self.pref_dialog
+ parent=self.pref_dialog,
)
def dialog_finished(response_id):
@@ -1093,14 +1146,14 @@ class Preferences(component.Component):
ErrorDialog(
_('Error Updating Account'),
_('An error occurred while updating account'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
if response_id == gtk.RESPONSE_OK:
client.core.update_account(
dialog.get_username(),
dialog.get_password(),
- dialog.get_authlevel()
+ dialog.get_authlevel(),
).addCallback(update_ok).addErrback(update_fail)
dialog.run().addCallback(dialog_finished)
@@ -1113,7 +1166,7 @@ class Preferences(component.Component):
username = model[itr][0]
header = _('Remove Account')
text = _('Are you sure you want to remove the account with the '
- 'username "%(username)s"?' % dict(username=username))
+ 'username "%(username)s"?' % {'username': username})
dialog = YesNoDialog(header, text, parent=self.pref_dialog)
def dialog_finished(response_id):
@@ -1125,17 +1178,17 @@ class Preferences(component.Component):
ErrorDialog(
_('Error Removing Account'),
_('Auhentication failed'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
else:
ErrorDialog(
_('Error Removing Account'),
_('An error occurred while removing account'),
- parent=self.pref_dialog, details=failure.getErrorMessage()
+ parent=self.pref_dialog, details=failure.getErrorMessage(),
).run()
if response_id == gtk.RESPONSE_YES:
client.core.remove_account(
- username
+ username,
).addCallback(remove_ok).addErrback(remove_fail)
dialog.run().addCallback(dialog_finished)
@@ -1184,7 +1237,8 @@ class Preferences(component.Component):
self.gtkui_config.apply_set_functions('pieces_colors')
self.builder.get_object('revert_color_%s' % state).set_sensitive(
- [color.red, color.green, color.blue] != self.COLOR_DEFAULTS[state])
+ [color.red, color.green, color.blue] != self.COLOR_DEFAULTS[state],
+ )
def __revert_color(self, state, from_config=False):
log.debug('Reverting %r color state', state)
diff --git a/deluge/ui/gtkui/queuedtorrents.py b/deluge/ui/gtkui/queuedtorrents.py
index 64cf4baad..9312d1da1 100644
--- a/deluge/ui/gtkui/queuedtorrents.py
+++ b/deluge/ui/gtkui/queuedtorrents.py
@@ -33,7 +33,8 @@ class QueuedTorrents(component.Component):
self.config = ConfigManager('gtkui.conf')
self.builder = Builder()
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'queuedtorrents.ui')))
+ 'deluge.ui.gtkui', os.path.join('glade', 'queuedtorrents.ui'),
+ ))
self.builder.get_object('chk_autoadd').set_active(self.config['autoadd_queued'])
self.dialog = self.builder.get_object('queued_torrents_dialog')
self.dialog.set_icon(get_logo(32))
@@ -117,7 +118,8 @@ class QueuedTorrents(component.Component):
self.status_item = component.get('StatusBar').add_item(
stock=STOCK_SORT_DESCENDING,
text=label,
- callback=self.on_statusbar_click)
+ callback=self.on_statusbar_click,
+ )
else:
self.status_item.set_text(label)
diff --git a/deluge/ui/gtkui/removetorrentdialog.py b/deluge/ui/gtkui/removetorrentdialog.py
index 4d2893278..27faad359 100644
--- a/deluge/ui/gtkui/removetorrentdialog.py
+++ b/deluge/ui/gtkui/removetorrentdialog.py
@@ -43,7 +43,8 @@ class RemoveTorrentDialog(object):
self.builder = gtk.Builder()
self.builder.add_from_file(deluge.common.resource_filename(
- 'deluge.ui.gtkui', os.path.join('glade', 'remove_torrent_dialog.ui')))
+ 'deluge.ui.gtkui', os.path.join('glade', 'remove_torrent_dialog.ui'),
+ ))
self.__dialog = self.builder.get_object('remove_torrent_dialog')
self.__dialog.set_transient_for(component.get('MainWindow').window)
diff --git a/deluge/ui/gtkui/status_tab.py b/deluge/ui/gtkui/status_tab.py
index 38dbbf6fb..740a7b0d0 100644
--- a/deluge/ui/gtkui/status_tab.py
+++ b/deluge/ui/gtkui/status_tab.py
@@ -32,14 +32,22 @@ class StatusTab(Tab):
self.piecesbar = None
self.add_tab_widget('summary_availability', fratio, ('distributed_copies',))
- self.add_tab_widget('summary_total_downloaded', ftotal_sized,
- ('all_time_download', 'total_payload_download'))
- self.add_tab_widget('summary_total_uploaded', ftotal_sized,
- ('total_uploaded', 'total_payload_upload'))
- self.add_tab_widget('summary_download_speed', fspeed_max,
- ('download_payload_rate', 'max_download_speed'))
- self.add_tab_widget('summary_upload_speed', fspeed_max,
- ('upload_payload_rate', 'max_upload_speed'))
+ self.add_tab_widget(
+ 'summary_total_downloaded', ftotal_sized,
+ ('all_time_download', 'total_payload_download'),
+ )
+ self.add_tab_widget(
+ 'summary_total_uploaded', ftotal_sized,
+ ('total_uploaded', 'total_payload_upload'),
+ )
+ self.add_tab_widget(
+ 'summary_download_speed', fspeed_max,
+ ('download_payload_rate', 'max_download_speed'),
+ )
+ self.add_tab_widget(
+ 'summary_upload_speed', fspeed_max,
+ ('upload_payload_rate', 'max_upload_speed'),
+ )
self.add_tab_widget('summary_seeds', fpeer, ('num_seeds', 'total_seeds'))
self.add_tab_widget('summary_peers', fpeer, ('num_peers', 'total_peers'))
self.add_tab_widget('summary_eta', ftime_or_dash, ('eta',))
@@ -68,7 +76,8 @@ class StatusTab(Tab):
status_keys.extend(['pieces', 'num_pieces'])
component.get('SessionProxy').get_torrent_status(
- selected, status_keys).addCallback(self._on_get_torrent_status)
+ selected, status_keys,
+ ).addCallback(self._on_get_torrent_status)
def _on_get_torrent_status(self, status):
# Check to see if we got valid data from the core
@@ -105,7 +114,8 @@ class StatusTab(Tab):
if self.piecesbar is None:
self.piecesbar = PiecesBar()
self.main_builder.get_object(
- 'status_progress_vbox').pack_start(self.piecesbar, False, False, 0)
+ 'status_progress_vbox',
+ ).pack_start(self.piecesbar, False, False, 0)
self.tab_widgets['piecesbar'] = TabWidget(self.piecesbar, fpcnt, ('progress', 'state', 'message'))
self.piecesbar.show()
self.progressbar.hide()
diff --git a/deluge/ui/gtkui/statusbar.py b/deluge/ui/gtkui/statusbar.py
index 27ade3dbb..d9edc9d81 100644
--- a/deluge/ui/gtkui/statusbar.py
+++ b/deluge/ui/gtkui/statusbar.py
@@ -122,7 +122,7 @@ class StatusBar(component.Component):
'max_connections_global': self._on_max_connections_global,
'max_download_speed': self._on_max_download_speed,
'max_upload_speed': self._on_max_upload_speed,
- 'dht': self._on_dht
+ 'dht': self._on_dht,
}
self.current_warnings = []
# Add a HBox to the statusbar after removing the initial label widget
@@ -138,7 +138,8 @@ class StatusBar(component.Component):
# Create the not connected item
self.not_connected_item = StatusBarItem(
stock=gtk.STOCK_STOP, text=_('Not Connected'),
- callback=self._on_notconnected_item_clicked)
+ callback=self._on_notconnected_item_clicked,
+ )
# Show the not connected status bar
self.show_not_connected()
@@ -154,40 +155,48 @@ class StatusBar(component.Component):
self.connections_item = self.add_item(
stock=gtk.STOCK_NETWORK,
callback=self._on_connection_item_clicked,
- tooltip=_('Connections (Limit)'), pack_start=True)
+ tooltip=_('Connections (Limit)'), pack_start=True,
+ )
self.download_item = self.add_item(
image=get_pixmap('downloading16.png'),
callback=self._on_download_item_clicked,
- tooltip=_('Download Speed (Limit)'), pack_start=True)
+ tooltip=_('Download Speed (Limit)'), pack_start=True,
+ )
self.upload_item = self.add_item(
image=get_pixmap('seeding16.png'),
callback=self._on_upload_item_clicked,
- tooltip=_('Upload Speed (Limit)'), pack_start=True)
+ tooltip=_('Upload Speed (Limit)'), pack_start=True,
+ )
self.traffic_item = self.add_item(
image=get_pixmap('traffic16.png'),
callback=self._on_traffic_item_clicked,
- tooltip=_('Protocol Traffic (Down:Up)'), pack_start=True)
+ tooltip=_('Protocol Traffic (Down:Up)'), pack_start=True,
+ )
self.dht_item = StatusBarItem(
- image=get_pixmap('dht16.png'), tooltip=_('DHT Nodes'))
+ image=get_pixmap('dht16.png'), tooltip=_('DHT Nodes'),
+ )
self.diskspace_item = self.add_item(
stock=gtk.STOCK_HARDDISK,
callback=self._on_diskspace_item_clicked,
- tooltip=_('Free Disk Space'), pack_start=True)
+ tooltip=_('Free Disk Space'), pack_start=True,
+ )
self.health_item = self.add_item(
stock=gtk.STOCK_DIALOG_ERROR,
text=_('<b><small>Port Issue</small></b>'),
markup=True,
tooltip=_('No incoming connections, check port forwarding'),
- callback=self._on_health_icon_clicked)
+ callback=self._on_health_icon_clicked,
+ )
self.external_ip_item = self.add_item(
- tooltip=_('External IP Address'), pack_start=True)
+ tooltip=_('External IP Address'), pack_start=True,
+ )
self.health = False
@@ -197,8 +206,10 @@ class StatusBar(component.Component):
self._on_max_upload_speed(configs['max_upload_speed'])
self._on_dht(configs['dht'])
# Get some config values
- client.core.get_config_values(['max_connections_global', 'max_download_speed',
- 'max_upload_speed', 'dht']).addCallback(update_config_values)
+ client.core.get_config_values([
+ 'max_connections_global', 'max_download_speed',
+ 'max_upload_speed', 'dht',
+ ]).addCallback(update_config_values)
def stop(self):
# When stopped, we just show the not connected thingy
@@ -255,7 +266,8 @@ class StatusBar(component.Component):
"""Displays a warning to the user in the status bar"""
if text not in self.current_warnings:
item = self.add_item(
- stock=gtk.STOCK_DIALOG_WARNING, text=text, callback=callback)
+ stock=gtk.STOCK_DIALOG_WARNING, text=text, callback=callback,
+ )
self.current_warnings.append(text)
timeout_add(3000, self.remove_warning, item)
@@ -359,7 +371,8 @@ class StatusBar(component.Component):
label_string = self.download_rate
else:
label_string = '%s <small>(%i %s)</small>' % (
- self.download_rate, self.max_download_speed, _('K/s'))
+ self.download_rate, self.max_download_speed, _('K/s'),
+ )
self.download_item.set_markup(label_string)
@@ -369,7 +382,8 @@ class StatusBar(component.Component):
label_string = self.upload_rate
else:
label_string = '%s <small>(%i %s)</small>' % (
- self.upload_rate, self.max_upload_speed, _('K/s'))
+ self.upload_rate, self.max_upload_speed, _('K/s'),
+ )
self.upload_item.set_markup(label_string)
@@ -383,12 +397,18 @@ class StatusBar(component.Component):
def set_limit_value(self, widget, core_key):
log.debug('_on_set_unlimit_other %s', core_key)
other_dialog_info = {
- 'max_download_speed': (_('Download Speed Limit'), _('Set the maximum download speed'),
- _('K/s'), 'downloading.svg', self.max_download_speed),
- 'max_upload_speed': (_('Upload Speed Limit'), _('Set the maximum upload speed'),
- _('K/s'), 'seeding.svg', self.max_upload_speed),
- 'max_connections_global': (_('Incoming Connections'), _('Set the maximum incoming connections'),
- '', gtk.STOCK_NETWORK, self.max_connections_global)
+ 'max_download_speed': (
+ _('Download Speed Limit'), _('Set the maximum download speed'),
+ _('K/s'), 'downloading.svg', self.max_download_speed,
+ ),
+ 'max_upload_speed': (
+ _('Upload Speed Limit'), _('Set the maximum upload speed'),
+ _('K/s'), 'seeding.svg', self.max_upload_speed,
+ ),
+ 'max_connections_global': (
+ _('Incoming Connections'), _('Set the maximum incoming connections'),
+ '', gtk.STOCK_NETWORK, self.max_connections_global,
+ ),
}
def set_value(value):
@@ -418,7 +438,8 @@ class StatusBar(component.Component):
self.config['tray_download_speed_list'],
self._on_set_download_speed,
self.max_download_speed,
- _('K/s'), show_notset=True, show_other=True)
+ _('K/s'), show_notset=True, show_other=True,
+ )
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
@@ -431,7 +452,8 @@ class StatusBar(component.Component):
self.config['tray_upload_speed_list'],
self._on_set_upload_speed,
self.max_upload_speed,
- _('K/s'), show_notset=True, show_other=True)
+ _('K/s'), show_notset=True, show_other=True,
+ )
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
@@ -443,7 +465,8 @@ class StatusBar(component.Component):
menu = common.build_menu_radio_list(
self.config['connection_limit_list'],
self._on_set_connection_limit,
- self.max_connections_global, show_notset=True, show_other=True)
+ self.max_connections_global, show_notset=True, show_other=True,
+ )
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
diff --git a/deluge/ui/gtkui/systemtray.py b/deluge/ui/gtkui/systemtray.py
index d2ed55a35..c59280077 100644
--- a/deluge/ui/gtkui/systemtray.py
+++ b/deluge/ui/gtkui/systemtray.py
@@ -46,7 +46,7 @@ class SystemTray(component.Component):
'separatormenuitem1',
'separatormenuitem2',
'separatormenuitem3',
- 'separatormenuitem4'
+ 'separatormenuitem4',
]
self.config.register_set_function('enable_system_tray', self.on_enable_system_tray_set)
# bit of a hack to prevent function from doing something on startup
@@ -60,14 +60,16 @@ class SystemTray(component.Component):
self.config_value_changed_dict = {
'max_download_speed': self._on_max_download_speed,
- 'max_upload_speed': self._on_max_upload_speed
+ 'max_upload_speed': self._on_max_upload_speed,
}
def enable(self):
"""Enables the system tray icon."""
self.builder = Builder()
- self.builder.add_from_file(resource_filename('deluge.ui.gtkui', os.path.join(
- 'glade', 'tray_menu.ui')))
+ self.builder.add_from_file(resource_filename(
+ 'deluge.ui.gtkui',
+ os.path.join('glade', 'tray_menu.ui'),
+ ))
self.builder.connect_signals(self)
@@ -75,8 +77,11 @@ class SystemTray(component.Component):
if appindicator and self.config['enable_appindicator']:
log.debug('Enabling the Application Indicator...')
- self.indicator = appindicator.Indicator('deluge', 'deluge',
- appindicator.CATEGORY_APPLICATION_STATUS)
+ self.indicator = appindicator.Indicator(
+ 'deluge',
+ 'deluge',
+ appindicator.CATEGORY_APPLICATION_STATUS,
+ )
try:
self.indicator.set_property('title', _('Deluge'))
except TypeError:
@@ -167,7 +172,8 @@ class SystemTray(component.Component):
def send_status_request(self):
client.core.get_session_status([
'payload_upload_rate',
- 'payload_download_rate']).addCallback(self._on_get_session_status)
+ 'payload_download_rate',
+ ]).addCallback(self._on_get_session_status)
def config_value_changed(self, key, value):
"""This is called when we received a config_value_changed signal from
@@ -216,7 +222,7 @@ class SystemTray(component.Component):
msg = '%s\n%s: %s (%s)\n%s: %s (%s)' % (
_('Deluge'), _('Down'), self.download_rate,
- max_download_speed, _('Up'), self.upload_rate, max_upload_speed
+ max_download_speed, _('Up'), self.upload_rate, max_upload_speed,
)
# Set the tooltip
@@ -229,20 +235,22 @@ class SystemTray(component.Component):
submenu_bwdownset = build_menu_radio_list(
self.config['tray_download_speed_list'], self.on_tray_setbwdown,
self.max_download_speed,
- _('K/s'), show_notset=True, show_other=True
+ _('K/s'), show_notset=True, show_other=True,
)
# Create the Upload speed list sub-menu
submenu_bwupset = build_menu_radio_list(
self.config['tray_upload_speed_list'], self.on_tray_setbwup,
self.max_upload_speed,
- _('K/s'), show_notset=True, show_other=True
+ _('K/s'), show_notset=True, show_other=True,
)
# Add the sub-menus to the tray menu
self.builder.get_object('menuitem_download_limit').set_submenu(
- submenu_bwdownset)
+ submenu_bwdownset,
+ )
self.builder.get_object('menuitem_upload_limit').set_submenu(
- submenu_bwupset)
+ submenu_bwupset,
+ )
# Show the sub-menus for all to see
submenu_bwdownset.show_all()
@@ -350,18 +358,22 @@ class SystemTray(component.Component):
# ignore previous radiomenuitem value
if not widget.get_active():
return
- self.setbwlimit(widget, _('Download Speed Limit'), _('Set the maximum download speed'),
- 'max_download_speed', 'tray_download_speed_list', self.max_download_speed,
- 'downloading.svg')
+ self.setbwlimit(
+ widget, _('Download Speed Limit'), _('Set the maximum download speed'),
+ 'max_download_speed', 'tray_download_speed_list', self.max_download_speed,
+ 'downloading.svg',
+ )
def on_tray_setbwup(self, widget, data=None):
if isinstance(widget, RadioMenuItem):
# ignore previous radiomenuitem value
if not widget.get_active():
return
- self.setbwlimit(widget, _('Upload Speed Limit'), _('Set the maximum upload speed'),
- 'max_upload_speed', 'tray_upload_speed_list', self.max_upload_speed,
- 'seeding.svg')
+ self.setbwlimit(
+ widget, _('Upload Speed Limit'), _('Set the maximum upload speed'),
+ 'max_upload_speed', 'tray_upload_speed_list', self.max_upload_speed,
+ 'seeding.svg',
+ )
def _on_window_hide(self, widget, data=None):
"""_on_window_hide - update the menuitem's status"""
diff --git a/deluge/ui/gtkui/toolbar.py b/deluge/ui/gtkui/toolbar.py
index 75512568d..c266806c4 100644
--- a/deluge/ui/gtkui/toolbar.py
+++ b/deluge/ui/gtkui/toolbar.py
@@ -37,7 +37,7 @@ class ToolBar(component.Component):
'toolbutton_queue_up',
'toolbutton_queue_down',
'toolbutton_filter',
- 'find_menuitem'
+ 'find_menuitem',
]
# Hide if necessary
@@ -45,7 +45,8 @@ class ToolBar(component.Component):
def start(self):
self.main_builder.get_object('toolbutton_connectionmanager').set_visible(
- not self.config['standalone'])
+ not self.config['standalone'],
+ )
for widget in self.change_sensitivity:
self.main_builder.get_object(widget).set_sensitive(True)
diff --git a/deluge/ui/gtkui/torrentdetails.py b/deluge/ui/gtkui/torrentdetails.py
index 1f09ee9b3..6be19dffb 100644
--- a/deluge/ui/gtkui/torrentdetails.py
+++ b/deluge/ui/gtkui/torrentdetails.py
@@ -122,7 +122,7 @@ class TorrentDetails(component.Component):
'Files': FilesTab,
'Peers': PeersTab,
'Options': OptionsTab,
- 'Trackers': TrackersTab
+ 'Trackers': TrackersTab,
}
# tab_name, visible
@@ -132,7 +132,7 @@ class TorrentDetails(component.Component):
('Options', True),
('Files', True),
('Peers', True),
- ('Trackers', True)
+ ('Trackers', True),
]
self.translate_tabs = {
@@ -142,7 +142,7 @@ class TorrentDetails(component.Component):
'Files': _('Fi_les'),
'Peers': _('_Peers'),
'Options': _('_Options'),
- 'Trackers': _('_Trackers')
+ 'Trackers': _('_Trackers'),
}
# Get the state from saved file
@@ -174,7 +174,10 @@ class TorrentDetails(component.Component):
# Determine insert position based on weight
# weights is a list of visible tab names in weight order
- weights = sorted([(tab.weight, name) for name, tab in self.tabs.items() if tab.is_visible])
+ weights = sorted(
+ (tab.weight, name)
+ for name, tab in self.tabs.items() if tab.is_visible
+ )
log.debug('weights: %s', weights)
log.debug('weight of tab: %s', weight)
@@ -215,7 +218,8 @@ class TorrentDetails(component.Component):
pos = self.notebook.insert_page(
tab.get_child_widget(),
tab.get_tab_label(),
- insert_pos)
+ insert_pos,
+ )
log.debug('Tab inserted at %d', pos)
tab.position = pos
if not self.notebook.get_property('visible'):
@@ -283,8 +287,10 @@ class TorrentDetails(component.Component):
self.visible(show)
def show_tab(self, tab_name, generate_menu=True):
- log.debug('%s\n%s\n%s', self.tabs[tab_name].get_child_widget(),
- self.tabs[tab_name].get_tab_label(), self.tabs[tab_name].position)
+ log.debug(
+ '%s\n%s\n%s', self.tabs[tab_name].get_child_widget(),
+ self.tabs[tab_name].get_tab_label(), self.tabs[tab_name].position,
+ )
position = self.tab_insert_position(self.tabs[tab_name].weight)
@@ -292,7 +298,8 @@ class TorrentDetails(component.Component):
self.notebook.insert_page(
self.tabs[tab_name].get_child_widget(),
self.tabs[tab_name].get_tab_label(),
- position)
+ position,
+ )
self.tabs[tab_name].is_visible = True
self.regenerate_positions()
if generate_menu:
diff --git a/deluge/ui/gtkui/torrentview.py b/deluge/ui/gtkui/torrentview.py
index 814a5ce1d..c87c197d1 100644
--- a/deluge/ui/gtkui/torrentview.py
+++ b/deluge/ui/gtkui/torrentview.py
@@ -256,63 +256,107 @@ class TorrentView(ListView, component.Component):
# Add the columns to the listview
self.add_text_column('torrent_id', hidden=True, unique=True)
self.add_bool_column('dirty', hidden=True)
- self.add_func_column('#', funcs.cell_data_queue, [int],
- status_field=['queue'],
- sort_func=queue_column_sort)
- self.add_texticon_column(_('Name'),
- status_field=['state', 'name'],
- function=funcs.cell_data_statusicon,
- default_sort=True)
- self.add_func_column(_('Size'), funcs.cell_data_size,
- [TYPE_UINT64],
- status_field=['total_wanted'])
- self.add_func_column(_('Downloaded'), funcs.cell_data_size,
- [TYPE_UINT64],
- status_field=['all_time_download'], default=False)
- self.add_func_column(_('Uploaded'), funcs.cell_data_size,
- [TYPE_UINT64],
- status_field=['total_uploaded'], default=False)
- self.add_func_column(_('Remaining'), funcs.cell_data_size, [TYPE_UINT64],
- status_field=['total_remaining'], default=False)
- self.add_progress_column(_('Progress'),
- status_field=['progress', 'state'],
- col_types=[float, str],
- function=funcs.cell_data_progress,
- sort_func=progress_sort)
- self.add_func_column(_('Seeds'), funcs.cell_data_peer, [int, int],
- status_field=['num_seeds', 'total_seeds'],
- sort_func=seed_peer_column_sort, default=False)
- self.add_func_column(_('Peers'), funcs.cell_data_peer, [int, int],
- status_field=['num_peers', 'total_peers'],
- sort_func=seed_peer_column_sort, default=False)
- self.add_func_column(_('Seeds:Peers'), funcs.cell_data_ratio_seeds_peers, [float],
- status_field=['seeds_peers_ratio'], default=False)
- self.add_func_column(_('Down Speed'), funcs.cell_data_speed_down, [int],
- status_field=['download_payload_rate'])
- self.add_func_column(_('Up Speed'), funcs.cell_data_speed_up, [int],
- status_field=['upload_payload_rate'])
- self.add_func_column(_('Down Limit'), funcs.cell_data_speed_limit_down, [float],
- status_field=['max_download_speed'], default=False)
- self.add_func_column(_('Up Limit'), funcs.cell_data_speed_limit_up, [float],
- status_field=['max_upload_speed'], default=False)
- self.add_func_column(_('ETA'), funcs.cell_data_time, [int],
- status_field=['eta'], sort_func=eta_column_sort)
- self.add_func_column(_('Ratio'), funcs.cell_data_ratio_ratio, [float],
- status_field=['ratio'], default=False)
- self.add_func_column(_('Avail'), funcs.cell_data_ratio_avail, [float],
- status_field=['distributed_copies'], default=False)
- self.add_func_column(_('Added'), funcs.cell_data_date_added, [int],
- status_field=['time_added'], default=False)
- self.add_func_column(_('Completed'), funcs.cell_data_date_completed, [int],
- status_field=['completed_time'], default=False)
- self.add_func_column(_('Complete Seen'), funcs.cell_data_date_or_never, [int],
- status_field=['last_seen_complete'], default=False)
- self.add_texticon_column(_('Tracker'), function=funcs.cell_data_trackericon,
- status_field=['tracker_host', 'tracker_host'], default=False)
+ self.add_func_column(
+ '#', funcs.cell_data_queue, [int],
+ status_field=['queue'],
+ sort_func=queue_column_sort,
+ )
+ self.add_texticon_column(
+ _('Name'),
+ status_field=['state', 'name'],
+ function=funcs.cell_data_statusicon,
+ default_sort=True,
+ )
+ self.add_func_column(
+ _('Size'), funcs.cell_data_size,
+ [TYPE_UINT64],
+ status_field=['total_wanted'],
+ )
+ self.add_func_column(
+ _('Downloaded'), funcs.cell_data_size,
+ [TYPE_UINT64],
+ status_field=['all_time_download'], default=False,
+ )
+ self.add_func_column(
+ _('Uploaded'), funcs.cell_data_size,
+ [TYPE_UINT64],
+ status_field=['total_uploaded'], default=False,
+ )
+ self.add_func_column(
+ _('Remaining'), funcs.cell_data_size, [TYPE_UINT64],
+ status_field=['total_remaining'], default=False,
+ )
+ self.add_progress_column(
+ _('Progress'),
+ status_field=['progress', 'state'],
+ col_types=[float, str],
+ function=funcs.cell_data_progress,
+ sort_func=progress_sort,
+ )
+ self.add_func_column(
+ _('Seeds'), funcs.cell_data_peer, [int, int],
+ status_field=['num_seeds', 'total_seeds'],
+ sort_func=seed_peer_column_sort, default=False,
+ )
+ self.add_func_column(
+ _('Peers'), funcs.cell_data_peer, [int, int],
+ status_field=['num_peers', 'total_peers'],
+ sort_func=seed_peer_column_sort, default=False,
+ )
+ self.add_func_column(
+ _('Seeds:Peers'), funcs.cell_data_ratio_seeds_peers, [float],
+ status_field=['seeds_peers_ratio'], default=False,
+ )
+ self.add_func_column(
+ _('Down Speed'), funcs.cell_data_speed_down, [int],
+ status_field=['download_payload_rate'],
+ )
+ self.add_func_column(
+ _('Up Speed'), funcs.cell_data_speed_up, [int],
+ status_field=['upload_payload_rate'],
+ )
+ self.add_func_column(
+ _('Down Limit'), funcs.cell_data_speed_limit_down, [float],
+ status_field=['max_download_speed'], default=False,
+ )
+ self.add_func_column(
+ _('Up Limit'), funcs.cell_data_speed_limit_up, [float],
+ status_field=['max_upload_speed'], default=False,
+ )
+ self.add_func_column(
+ _('ETA'), funcs.cell_data_time, [int],
+ status_field=['eta'], sort_func=eta_column_sort,
+ )
+ self.add_func_column(
+ _('Ratio'), funcs.cell_data_ratio_ratio, [float],
+ status_field=['ratio'], default=False,
+ )
+ self.add_func_column(
+ _('Avail'), funcs.cell_data_ratio_avail, [float],
+ status_field=['distributed_copies'], default=False,
+ )
+ self.add_func_column(
+ _('Added'), funcs.cell_data_date_added, [int],
+ status_field=['time_added'], default=False,
+ )
+ self.add_func_column(
+ _('Completed'), funcs.cell_data_date_completed, [int],
+ status_field=['completed_time'], default=False,
+ )
+ self.add_func_column(
+ _('Complete Seen'), funcs.cell_data_date_or_never, [int],
+ status_field=['last_seen_complete'], default=False,
+ )
+ self.add_texticon_column(
+ _('Tracker'), function=funcs.cell_data_trackericon,
+ status_field=['tracker_host', 'tracker_host'], default=False,
+ )
self.add_text_column(_('Download Folder'), status_field=['download_location'], default=False)
self.add_text_column(_('Owner'), status_field=['owner'], default=False)
- self.add_bool_column(_('Shared'), status_field=['shared'], default=False,
- tooltip=_('Torrent is shared between other Deluge users or not.'))
+ self.add_bool_column(
+ _('Shared'), status_field=['shared'], default=False,
+ tooltip=_('Torrent is shared between other Deluge users or not.'),
+ )
self.restore_columns_order_from_state()
# Set filter to None for now
@@ -350,7 +394,8 @@ class TorrentView(ListView, component.Component):
continue
status_fields.extend(listview_column.status_field)
component.get('SessionProxy').get_torrents_status(
- {}, status_fields).addCallback(self._on_session_state)
+ {}, status_fields,
+ ).addCallback(self._on_session_state)
client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
client.register_event_handler('TorrentAddedEvent', self.on_torrentadded_event)
@@ -428,9 +473,11 @@ class TorrentView(ListView, component.Component):
for column in columns:
# Make sure column is visible and has 'status_field' set.
# If not, we can ignore it.
- if (self.columns[column].column.get_visible() is True
- and self.columns[column].hidden is False
- and self.columns[column].status_field is not None):
+ if (
+ self.columns[column].column.get_visible() is True
+ and self.columns[column].hidden is False
+ and self.columns[column].status_field is not None
+ ):
for field in self.columns[column].status_field:
status_keys.append(field)
self.columns_to_update.append(column)
@@ -454,7 +501,8 @@ class TorrentView(ListView, component.Component):
# Request the statuses for all these torrent_ids, this is async so we
# will deal with the return in a signal callback.
d = component.get('SessionProxy').get_torrents_status(
- self.filter, status_keys).addCallback(self._on_get_torrents_status)
+ self.filter, status_keys,
+ ).addCallback(self._on_get_torrents_status)
if select_row:
d.addCallback(self.select_first_row)
diff --git a/deluge/ui/gtkui/torrentview_data_funcs.py b/deluge/ui/gtkui/torrentview_data_funcs.py
index c591513b6..4e3260c0d 100644
--- a/deluge/ui/gtkui/torrentview_data_funcs.py
+++ b/deluge/ui/gtkui/torrentview_data_funcs.py
@@ -26,7 +26,7 @@ ICON_STATE = {
'Paused': icon_inactive,
'Error': icon_alert,
'Queued': icon_queued,
- 'Moving': icon_checking
+ 'Moving': icon_checking,
}
# Cache the key used to calculate the current value set for the specific cell
@@ -48,7 +48,7 @@ func_last_value = {
'cell_data_statusicon': None,
'cell_data_queue': None,
'cell_data_progress': [None, None],
- 'cell_data_peer_progress': None
+ 'cell_data_peer_progress': None,
}
diff --git a/deluge/ui/sessionproxy.py b/deluge/ui/sessionproxy.py
index 912d58625..8c363b478 100644
--- a/deluge/ui/sessionproxy.py
+++ b/deluge/ui/sessionproxy.py
@@ -132,7 +132,7 @@ class SessionProxy(component.Component):
keys_to_get.append(key)
if not keys_to_get:
return succeed(
- self.create_status_dict([torrent_id], keys)[torrent_id]
+ self.create_status_dict([torrent_id], keys)[torrent_id],
)
else:
d = client.core.get_torrent_status(torrent_id, keys_to_get, True)
diff --git a/deluge/ui/tracker_icons.py b/deluge/ui/tracker_icons.py
index dd367ec3b..492d96d23 100644
--- a/deluge/ui/tracker_icons.py
+++ b/deluge/ui/tracker_icons.py
@@ -208,14 +208,20 @@ class TrackerIcons(Component):
self.pending[host] = []
# Start callback chain
d = self.download_page(host)
- d.addCallbacks(self.on_download_page_complete, self.on_download_page_fail,
- errbackArgs=(host,))
+ d.addCallbacks(
+ self.on_download_page_complete, self.on_download_page_fail,
+ errbackArgs=(host,),
+ )
d.addCallback(self.parse_html_page)
- d.addCallbacks(self.on_parse_complete, self.on_parse_fail,
- callbackArgs=(host,))
+ d.addCallbacks(
+ self.on_parse_complete, self.on_parse_fail,
+ callbackArgs=(host,),
+ )
d.addCallback(self.download_icon, host)
- d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail,
- callbackArgs=(host,), errbackArgs=(host,))
+ d.addCallbacks(
+ self.on_download_icon_complete, self.on_download_icon_fail,
+ callbackArgs=(host,), errbackArgs=(host,),
+ )
if PIL_INSTALLED:
d.addCallback(self.resize_icon)
d.addCallback(self.store_icon, host)
@@ -272,8 +278,10 @@ class TrackerIcons(Component):
location = urljoin(self.host_to_url(host), error_msg.split(' to ')[1])
self.redirects[host] = url_to_host(location)
d = self.download_page(host, url=location)
- d.addCallbacks(self.on_download_page_complete, self.on_download_page_fail,
- errbackArgs=(host,))
+ d.addCallbacks(
+ self.on_download_page_complete, self.on_download_page_fail,
+ errbackArgs=(host,),
+ )
return d
@@ -345,8 +353,10 @@ class TrackerIcons(Component):
if len(icons) == 0:
raise NoIconsError('empty icons list')
(url, mimetype) = icons.pop(0)
- d = download_file(url, os.path.join(self.dir, host_to_icon_name(host, mimetype)),
- force_filename=True)
+ d = download_file(
+ url, os.path.join(self.dir, host_to_icon_name(host, mimetype)),
+ force_filename=True,
+ )
d.addCallback(self.check_icon_is_valid)
if icons:
d.addErrback(self.on_download_icon_fail, host, icons)
@@ -413,16 +423,24 @@ class TrackerIcons(Component):
location = urljoin(self.host_to_url(host), error_msg.split(' to ')[1])
d = self.download_icon([(location, extension_to_mimetype(location.rpartition('.')[2]))] + icons, host)
if not icons:
- d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail,
- callbackArgs=(host,), errbackArgs=(host,))
+ d.addCallbacks(
+ self.on_download_icon_complete, self.on_download_icon_fail,
+ callbackArgs=(host,), errbackArgs=(host,),
+ )
elif f.check(NoResource, ForbiddenResource) and icons:
d = self.download_icon(icons, host)
elif f.check(NoIconsError):
# No icons, try favicon.ico as an act of desperation
- d = self.download_icon([(urljoin(self.host_to_url(host), 'favicon.ico'),
- extension_to_mimetype('ico'))], host)
- d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail,
- callbackArgs=(host,), errbackArgs=(host,))
+ d = self.download_icon(
+ [(
+ urljoin(self.host_to_url(host), 'favicon.ico'),
+ extension_to_mimetype('ico'),
+ )], host,
+ )
+ d.addCallbacks(
+ self.on_download_icon_complete, self.on_download_icon_fail,
+ callbackArgs=(host,), errbackArgs=(host,),
+ )
else:
# No icons :(
# Return the None Icon
diff --git a/deluge/ui/ui_entry.py b/deluge/ui/ui_entry.py
index 4e4ae2b65..c4f2f3b26 100644
--- a/deluge/ui/ui_entry.py
+++ b/deluge/ui/ui_entry.py
@@ -27,7 +27,7 @@ from deluge.ui.baseargparser import BaseArgParser
from deluge.ui.translations_util import setup_translations
DEFAULT_PREFS = {
- 'default_ui': 'gtk'
+ 'default_ui': 'gtk',
}
AMBIGUOUS_CMD_ARGS = ('-h', '--help', '-v', '-V', '--version')
@@ -51,8 +51,10 @@ def start_ui():
def add_ui_options_group(_parser):
"""Function to enable reuse of UI Options group"""
group = _parser.add_argument_group(_('UI Options'))
- group.add_argument('-s', '--set-default-ui', dest='default_ui', choices=ui_titles,
- help=_('Set the default UI to be run, when no UI is specified'))
+ group.add_argument(
+ '-s', '--set-default-ui', dest='default_ui', choices=ui_titles,
+ help=_('Set the default UI to be run, when no UI is specified'),
+ )
return _parser
# Setup parser with Common Options and add UI Options group.
@@ -81,11 +83,15 @@ def start_ui():
parser = add_ui_options_group(BaseArgParser(common_help=True))
# Create subparser for each registered UI. Empty title is used to remove unwanted positional text.
- subparsers = parser.add_subparsers(dest='selected_ui', metavar='{%s} [UI args]' % ','.join(ui_titles), title=None,
- help=_('Alternative UI to launch, with optional ui args \n (default UI: *)'))
+ subparsers = parser.add_subparsers(
+ dest='selected_ui', metavar='{%s} [UI args]' % ','.join(ui_titles), title=None,
+ help=_('Alternative UI to launch, with optional ui args \n (default UI: *)'),
+ )
for ui in ui_titles:
- parser_ui = subparsers.add_parser(ui, common_help=False,
- help=getattr(ui_entrypoints[ui], 'cmd_description', ''))
+ parser_ui = subparsers.add_parser(
+ ui, common_help=False,
+ help=getattr(ui_entrypoints[ui], 'cmd_description', ''),
+ )
parser_ui.add_argument('ui_args', nargs=argparse.REMAINDER)
# If the UI is set as default, indicate this in help by prefixing with a star.
subactions = subparsers._get_subactions()
@@ -106,16 +112,20 @@ def start_ui():
try:
ui = ui_entrypoints[selected_ui](prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args)
except KeyError as ex:
- log.error('Unable to find chosen UI: "%s". Please choose a different UI '
- 'or use "--set-default-ui" to change default UI.', selected_ui)
+ log.error(
+ 'Unable to find chosen UI: "%s". Please choose a different UI '
+ 'or use "--set-default-ui" to change default UI.', selected_ui,
+ )
except ImportError as ex:
import traceback
error_type, error_value, tb = sys.exc_info()
stack = traceback.extract_tb(tb)
last_frame = stack[-1]
if last_frame[0] == __file__:
- log.error('Unable to find chosen UI: "%s". Please choose a different UI '
- 'or use "--set-default-ui" to change default UI.', selected_ui)
+ log.error(
+ 'Unable to find chosen UI: "%s". Please choose a different UI '
+ 'or use "--set-default-ui" to change default UI.', selected_ui,
+ )
else:
log.exception(ex)
log.error('Encountered an error launching the request UI: %s', selected_ui)
diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py
index 5416b677d..3ab8ccf9f 100644
--- a/deluge/ui/web/auth.py
+++ b/deluge/ui/web/auth.py
@@ -102,8 +102,10 @@ class Auth(JSONComponent):
expires, expires_str = make_expires(self.config['session_timeout'])
checksum = str(make_checksum(session_id))
- request.addCookie(b'_session_id', session_id + checksum,
- path=request.base + b'json', expires=expires_str)
+ request.addCookie(
+ b'_session_id', session_id + checksum,
+ path=request.base + b'json', expires=expires_str,
+ )
log.debug('Creating session for %s', login)
@@ -113,7 +115,7 @@ class Auth(JSONComponent):
self.config['sessions'][session_id] = {
'login': login,
'level': AUTH_LEVEL_ADMIN,
- 'expires': expires
+ 'expires': expires,
}
return True
@@ -197,8 +199,10 @@ class Auth(JSONComponent):
session['expires'] = expires
_session_id = request.getCookie('_session_id')
- request.addCookie(b'_session_id', _session_id,
- path=request.base + b'json', expires=expires_str)
+ request.addCookie(
+ b'_session_id', _session_id,
+ path=request.base + b'json', expires=expires_str,
+ )
if method:
if not hasattr(method, '_json_export'):
diff --git a/deluge/ui/web/common.py b/deluge/ui/web/common.py
index 688e9361e..8e41feb7a 100644
--- a/deluge/ui/web/common.py
+++ b/deluge/ui/web/common.py
@@ -52,7 +52,7 @@ try:
builtins = {
'_': _,
'escape': escape,
- 'version': common.get_version()
+ 'version': common.get_version(),
}
def render(self, *args, **data):
@@ -61,11 +61,13 @@ try:
return rendered.encode('utf-8', 'replace')
except ImportError:
import warnings
- warnings.warn('The Mako library is required to run deluge.ui.web',
- RuntimeWarning)
+ warnings.warn(
+ 'The Mako library is required to run deluge.ui.web',
+ RuntimeWarning,
+ )
class Template(object):
def __new__(cls, *args, **kwargs):
raise RuntimeError(
- 'The Mako library is required to run deluge.ui.web'
+ 'The Mako library is required to run deluge.ui.web',
)
diff --git a/deluge/ui/web/json_api.py b/deluge/ui/web/json_api.py
index f2b03e171..1cc78610c 100644
--- a/deluge/ui/web/json_api.py
+++ b/deluge/ui/web/json_api.py
@@ -206,9 +206,13 @@ class JSON(resource.Resource, component.Component):
Returns the error in json response.
"""
log.error(reason)
- response = {'result': None, 'id': None,
- 'error': {'code': 5,
- 'message': '%s: %s' % (reason.__class__.__name__, str(reason))}}
+ response = {
+ 'result': None, 'id': None,
+ 'error': {
+ 'code': 5,
+ 'message': '%s: %s' % (reason.__class__.__name__, str(reason)),
+ },
+ }
return self._send_response(request, response)
def _send_response(self, request, response):
@@ -355,7 +359,7 @@ class WebApi(JSONComponent):
'message',
'comment',
'tracker_status',
- 'peers'
+ 'peers',
]
def __init__(self):
@@ -470,8 +474,8 @@ class WebApi(JSONComponent):
'stats': {
'max_download': self.core_config.get('max_download_speed'),
'max_upload': self.core_config.get('max_upload_speed'),
- 'max_num_connections': self.core_config.get('max_connections_global')
- }
+ 'max_num_connections': self.core_config.get('max_connections_global'),
+ },
}
if not client.connected():
@@ -515,7 +519,7 @@ class WebApi(JSONComponent):
'download_rate',
'upload_rate',
'dht_nodes',
- 'has_incoming_connections'
+ 'has_incoming_connections',
])
d3.addCallback(got_stats)
@@ -690,16 +694,20 @@ class WebApi(JSONComponent):
for torrent in torrents:
if is_magnet(torrent['path']):
- log.info('Adding torrent from magnet uri `%s` with options `%r`',
- torrent['path'], torrent['options'])
+ log.info(
+ 'Adding torrent from magnet uri `%s` with options `%r`',
+ torrent['path'], torrent['options'],
+ )
d = client.core.add_torrent_magnet(torrent['path'], torrent['options'])
deferreds.append(d)
else:
filename = os.path.basename(torrent['path'])
with open(torrent['path'], 'rb') as _file:
fdump = base64.encodestring(_file.read())
- log.info('Adding torrent from file `%s` with options `%r`',
- filename, torrent['options'])
+ log.info(
+ 'Adding torrent from file `%s` with options `%r`',
+ filename, torrent['options'],
+ )
d = client.core.add_torrent_file_async(filename, fdump, torrent['options'])
deferreds.append(d)
return DeferredList(deferreds, consumeErrors=False)
@@ -873,7 +881,7 @@ class WebApi(JSONComponent):
return {
'enabled_plugins': list(component.get('Web.PluginManager').plugins),
- 'available_plugins': component.get('Web.PluginManager').available_plugins
+ 'available_plugins': component.get('Web.PluginManager').available_plugins,
}
@export
diff --git a/deluge/ui/web/pluginmanager.py b/deluge/ui/web/pluginmanager.py
index 278b0c04b..fe5f0bf25 100644
--- a/deluge/ui/web/pluginmanager.py
+++ b/deluge/ui/web/pluginmanager.py
@@ -33,7 +33,7 @@ def gather_info(plugin):
return {
'scripts': scripts,
'debug_scripts': debug_scripts,
- 'script_directories': directories
+ 'script_directories': directories,
}
diff --git a/deluge/ui/web/server.py b/deluge/ui/web/server.py
index 92e63dedd..7516ff43e 100644
--- a/deluge/ui/web/server.py
+++ b/deluge/ui/web/server.py
@@ -60,12 +60,12 @@ CONFIG_DEFAULTS = {
'port': 8112,
'https': False,
'pkey': 'ssl/daemon.pkey',
- 'cert': 'ssl/daemon.cert'
+ 'cert': 'ssl/daemon.cert',
}
UI_CONFIG_KEYS = (
'theme', 'sidebar_show_zero', 'sidebar_multiple_filters',
- 'show_session_speed', 'base', 'first_login'
+ 'show_session_speed', 'base', 'first_login',
)
@@ -103,7 +103,7 @@ class Upload(resource.Resource):
request.setResponseCode(http.OK)
return json.dumps({
'success': True,
- 'files': []
+ 'files': [],
})
tempdir = tempfile.mkdtemp(prefix='delugeweb-')
@@ -119,10 +119,12 @@ class Upload(resource.Resource):
request.setHeader(b'content-type', b'text/html')
request.setResponseCode(http.OK)
- return compress(json.dumps({
- 'success': True,
- 'files': filenames
- }), request)
+ return compress(
+ json.dumps({
+ 'success': True,
+ 'files': filenames,
+ }), request,
+ )
class Render(resource.Resource):
@@ -167,8 +169,10 @@ class Tracker(resource.Resource):
def on_got_icon(self, icon, request):
if icon:
- request.setHeader(b'cache-control',
- b'public, must-revalidate, max-age=86400')
+ request.setHeader(
+ b'cache-control',
+ b'public, must-revalidate, max-age=86400',
+ )
request.setHeader(b'content-type', icon.get_mimetype().encode('utf8'))
request.setResponseCode(http.OK)
request.write(icon.get_data())
@@ -192,8 +196,10 @@ class Flag(resource.Resource):
path = ('ui', 'data', 'pixmaps', 'flags', request.country.lower() + '.png')
filename = common.resource_filename('deluge', os.path.join(*path))
if os.path.exists(filename):
- request.setHeader('cache-control',
- 'public, must-revalidate, max-age=86400')
+ request.setHeader(
+ 'cache-control',
+ 'public, must-revalidate, max-age=86400',
+ )
request.setHeader('content-type', 'image/png')
with open(filename, 'rb') as _file:
data = _file.read()
@@ -420,7 +426,7 @@ class TopLevel(resource.Resource):
__stylesheets = [
'css/ext-all-notheme.css',
'css/ext-extensions.css',
- 'css/deluge.css'
+ 'css/deluge.css',
]
def __init__(self):
@@ -547,11 +553,13 @@ class TopLevel(resource.Resource):
web_config = component.get('Web').get_config()
web_config['base'] = request.base
- config = dict([(key, web_config[key]) for key in UI_CONFIG_KEYS])
+ config = {key: web_config[key] for key in UI_CONFIG_KEYS}
js_config = json.dumps(config)
# Insert the values into 'index.html' and return.
- return template.render(scripts=scripts, stylesheets=self.stylesheets,
- debug=debug_arg, base=request.base, js_config=js_config)
+ return template.render(
+ scripts=scripts, stylesheets=self.stylesheets,
+ debug=debug_arg, base=request.base, js_config=js_config,
+ )
class DelugeWeb(component.Component):
diff --git a/deluge/ui/web/web.py b/deluge/ui/web/web.py
index 2e8327b27..8d1e12794 100644
--- a/deluge/ui/web/web.py
+++ b/deluge/ui/web/web.py
@@ -28,12 +28,18 @@ class Web(UI):
self.__server = None
group = self.parser.add_argument_group(_('Web Server Options'))
- group.add_argument('-i', '--interface', metavar='<ip_address>', action='store',
- help=_('IP address for web server to listen on'))
- group.add_argument('-p', '--port', metavar='<port>', type=int, action='store',
- help=_('Port for web server to listen on'))
- group.add_argument('-b', '--base', metavar='<path>', action='store',
- help=_('Set the base path that the ui is running on'))
+ group.add_argument(
+ '-i', '--interface', metavar='<ip_address>', action='store',
+ help=_('IP address for web server to listen on'),
+ )
+ group.add_argument(
+ '-p', '--port', metavar='<port>', type=int, action='store',
+ help=_('Port for web server to listen on'),
+ )
+ group.add_argument(
+ '-b', '--base', metavar='<path>', action='store',
+ help=_('Set the base path that the ui is running on'),
+ )
group.add_argument('--ssl', action='store_true', help=_('Force the web server to use SSL'))
group.add_argument('--no-ssl', action='store_true', help=_('Force the web server to disable SSL'))
self.parser.add_process_arg_group()
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 18e7c3f96..4b6300fa0 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -83,7 +83,7 @@ master_doc = 'index'
# General substitutions.
project = 'Deluge'
current_year = date.today().year
-copyright = '2008-%s, Deluge Team' % current_year
+copyright = '2008-%s, Deluge Team' % current_year # noqa: A001
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
diff --git a/gen_web_gettext.py b/gen_web_gettext.py
index aea337cef..a769ae3aa 100755
--- a/gen_web_gettext.py
+++ b/gen_web_gettext.py
@@ -46,7 +46,7 @@ def check_missing_markup(js_dir):
# Create a list of the matching strings to search for with the except_chars appended to each one.
string_re = re.compile(
- '(' + ')|('.join(['%s[^' + except_chars + "].*'"]*len(attr_list)) % tuple(attr_list) + ')'
+ '(' + ')|('.join(['%s[^' + except_chars + "].*'"] * len(attr_list)) % tuple(attr_list) + ')',
)
strings = {}
diff --git a/packaging/win32/deluge-bbfreeze.py b/packaging/win32/deluge-bbfreeze.py
index 0ee03e371..54aefb49f 100644
--- a/packaging/win32/deluge-bbfreeze.py
+++ b/packaging/win32/deluge-bbfreeze.py
@@ -161,7 +161,7 @@ theme_include_list = [
[gtk_root, 'share/themes/MS-Windows'],
['DelugeStart Theme', 'lib/gtk-2.0/2.10.0/engines/libmurrine.dll'],
['DelugeStart Theme', 'share/themes/DelugeStart'],
- ['DelugeStart Theme', 'etc/gtk-2.0/gtkrc']
+ ['DelugeStart Theme', 'etc/gtk-2.0/gtkrc'],
]
for path_root, path in theme_include_list:
full_path = os.path.join(path_root, path)
diff --git a/setup.py b/setup.py
index 6008dfd31..6fbe198ec 100755
--- a/setup.py
+++ b/setup.py
@@ -171,7 +171,7 @@ class BuildTranslations(cmd.Command):
user_options = [
('build-lib', None, 'lib build folder'),
- ('develop', 'D', 'Compile translations in develop mode (deluge/i18n)')
+ ('develop', 'D', 'Compile translations in develop mode (deluge/i18n)'),
]
boolean_options = ['develop']
@@ -258,7 +258,7 @@ class BuildPlugins(cmd.Command):
user_options = [
('install-dir=', None, 'develop install folder'),
- ('develop', 'D', 'Compile plugins in develop mode')
+ ('develop', 'D', 'Compile plugins in develop mode'),
]
boolean_options = ['develop']
@@ -353,7 +353,7 @@ class Build(_build):
sub_commands = [
('build_webui', None),
('build_trans', None),
- ('build_plugins', None)
+ ('build_plugins', None),
] + _build.sub_commands
def run(self):
@@ -372,7 +372,7 @@ class InstallData(_install_data):
def finalize_options(self):
self.install_dir = None
self.set_undefined_options('install', ('install_data', 'install_dir'),
- ('root', 'root'), ('force', 'force'),)
+ ('root', 'root'), ('force', 'force'))
def run(self):
_install_data.run(self)
@@ -548,5 +548,5 @@ setup(
exclude_package_data=_exclude_package_data,
packages=find_packages(exclude=['deluge.plugins.*', 'deluge.tests']),
namespace_packages=['deluge', 'deluge.plugins'],
- entry_points=_entry_points
+ entry_points=_entry_points,
)
diff --git a/tox.ini b/tox.ini
index afe8ab1f5..3119c2b8c 100644
--- a/tox.ini
+++ b/tox.ini
@@ -7,12 +7,19 @@
max-line-length = 120
builtins = _,_n,__request__
exclude = .git,.tox,dist,build
+ignore =
+# A003 Class attribute is a python builtin.
+ A003,
+# C813, C815, C816: PY3 missing trailing commas.
+ C813,C815,C816,
+# W503 line break before binary operator.
+ W503,
[pycodestyle]
max-line-length = 120
[tox]
-envlist = py27, flake8, docs, pylint
+envlist = py27, flake8, docs
minversion=1.8
[testenv]