summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--deluge/_libtorrent.py4
-rw-r--r--deluge/bencode.py2
-rw-r--r--deluge/common.py222
-rw-r--r--deluge/component.py52
-rw-r--r--deluge/config.py70
-rw-r--r--deluge/configmanager.py8
-rw-r--r--deluge/core/alertmanager.py20
-rw-r--r--deluge/core/authmanager.py76
-rw-r--r--deluge/core/core.py192
-rw-r--r--deluge/core/daemon.py40
-rw-r--r--deluge/core/daemon_entry.py28
-rw-r--r--deluge/core/eventmanager.py6
-rw-r--r--deluge/core/filtermanager.py82
-rw-r--r--deluge/core/pluginmanager.py16
-rw-r--r--deluge/core/preferencesmanager.py396
-rw-r--r--deluge/core/rpcserver.py110
-rw-r--r--deluge/core/torrent.py490
-rw-r--r--deluge/core/torrentmanager.py440
-rw-r--r--deluge/decorators.py6
-rw-r--r--deluge/error.py8
-rw-r--r--deluge/event.py4
-rw-r--r--deluge/httpdownloader.py30
-rw-r--r--deluge/log.py86
-rw-r--r--deluge/maketorrent.py70
-rw-r--r--deluge/metafile.py22
-rw-r--r--deluge/path_chooser_common.py8
-rw-r--r--deluge/pluginmanagerbase.py76
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/common.py2
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py270
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py138
-rw-r--r--deluge/plugins/AutoAdd/deluge/plugins/autoadd/webui.py2
-rw-r--r--deluge/plugins/AutoAdd/setup.py18
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py6
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py210
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py28
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py142
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/peerguardian.py18
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py10
-rw-r--r--deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py10
-rw-r--r--deluge/plugins/Blocklist/setup.py18
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/common.py4
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/core.py74
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/gtkui.py66
-rw-r--r--deluge/plugins/Execute/deluge/plugins/execute/webui.py2
-rw-r--r--deluge/plugins/Execute/setup.py18
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/common.py4
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/core.py80
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py38
-rw-r--r--deluge/plugins/Extractor/deluge/plugins/extractor/webui.py2
-rw-r--r--deluge/plugins/Extractor/setup.py18
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/core.py158
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py14
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/gtkui/label_config.py18
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py106
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/gtkui/submenu.py16
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/test.py32
-rw-r--r--deluge/plugins/Label/deluge/plugins/label/webui.py6
-rw-r--r--deluge/plugins/Label/setup.py18
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/common.py28
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/core.py64
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py260
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/test.py28
-rw-r--r--deluge/plugins/Notifications/deluge/plugins/notifications/webui.py6
-rwxr-xr-xdeluge/plugins/Notifications/setup.py18
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/common.py2
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py82
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py110
-rw-r--r--deluge/plugins/Scheduler/deluge/plugins/scheduler/webui.py2
-rw-r--r--deluge/plugins/Scheduler/setup.py18
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/common.py2
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/core.py62
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/graph.py12
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/gtkui.py60
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py24
-rw-r--r--deluge/plugins/Stats/deluge/plugins/stats/webui.py6
-rw-r--r--deluge/plugins/Stats/setup.py18
-rw-r--r--deluge/plugins/Toggle/deluge/plugins/toggle/common.py4
-rw-r--r--deluge/plugins/Toggle/deluge/plugins/toggle/core.py2
-rw-r--r--deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py22
-rw-r--r--deluge/plugins/Toggle/deluge/plugins/toggle/webui.py2
-rw-r--r--deluge/plugins/Toggle/setup.py18
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/common.py4
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/core.py28
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py38
-rw-r--r--deluge/plugins/WebUi/deluge/plugins/webui/tests/test_plugin_webui.py10
-rw-r--r--deluge/plugins/WebUi/setup.py18
-rw-r--r--deluge/plugins/pluginbase.py22
-rw-r--r--deluge/rencode.py12
-rw-r--r--deluge/scripts/create_plugin.py88
-rw-r--r--deluge/scripts/deluge_remote.py42
-rw-r--r--deluge/tests/__init__.py2
-rw-r--r--deluge/tests/basetest.py6
-rw-r--r--deluge/tests/common.py80
-rw-r--r--deluge/tests/common_web.py16
-rw-r--r--deluge/tests/daemon_base.py14
-rw-r--r--deluge/tests/test_alertmanager.py12
-rw-r--r--deluge/tests/test_client.py28
-rw-r--r--deluge/tests/test_common.py126
-rw-r--r--deluge/tests/test_component.py88
-rw-r--r--deluge/tests/test_config.py112
-rw-r--r--deluge/tests/test_core.py94
-rw-r--r--deluge/tests/test_error.py14
-rw-r--r--deluge/tests/test_files_tab.py44
-rw-r--r--deluge/tests/test_httpdownloader.py128
-rw-r--r--deluge/tests/test_json_api.py74
-rw-r--r--deluge/tests/test_log.py6
-rw-r--r--deluge/tests/test_maketorrent.py48
-rw-r--r--deluge/tests/test_plugin_metadata.py10
-rw-r--r--deluge/tests/test_rpcserver.py30
-rw-r--r--deluge/tests/test_sessionproxy.py56
-rw-r--r--deluge/tests/test_torrent.py40
-rw-r--r--deluge/tests/test_torrentmanager.py6
-rw-r--r--deluge/tests/test_torrentview.py36
-rw-r--r--deluge/tests/test_tracker_icons.py18
-rw-r--r--deluge/tests/test_transfer.py60
-rw-r--r--deluge/tests/test_ui_common.py22
-rw-r--r--deluge/tests/test_ui_console_fields.py2
-rw-r--r--deluge/tests/test_ui_entry.py184
-rw-r--r--deluge/tests/test_web_api.py68
-rw-r--r--deluge/tests/test_webserver.py4
-rw-r--r--deluge/tests/twisted/plugins/delugereporter.py12
-rw-r--r--deluge/transfer.py20
-rw-r--r--deluge/ui/Win32IconImagePlugin.py12
-rw-r--r--deluge/ui/baseargparser.py106
-rw-r--r--deluge/ui/client.py90
-rw-r--r--deluge/ui/common.py294
-rw-r--r--deluge/ui/console/cmdline/command.py44
-rw-r--r--deluge/ui/console/cmdline/commands/add.py30
-rw-r--r--deluge/ui/console/cmdline/commands/cache.py4
-rw-r--r--deluge/ui/console/cmdline/commands/config.py56
-rw-r--r--deluge/ui/console/cmdline/commands/connect.py18
-rw-r--r--deluge/ui/console/cmdline/commands/debug.py14
-rw-r--r--deluge/ui/console/cmdline/commands/gui.py4
-rw-r--r--deluge/ui/console/cmdline/commands/halt.py8
-rw-r--r--deluge/ui/console/cmdline/commands/help.py20
-rw-r--r--deluge/ui/console/cmdline/commands/info.py324
-rw-r--r--deluge/ui/console/cmdline/commands/manage.py52
-rw-r--r--deluge/ui/console/cmdline/commands/move.py16
-rw-r--r--deluge/ui/console/cmdline/commands/pause.py10
-rw-r--r--deluge/ui/console/cmdline/commands/plugin.py42
-rw-r--r--deluge/ui/console/cmdline/commands/quit.py2
-rw-r--r--deluge/ui/console/cmdline/commands/recheck.py12
-rw-r--r--deluge/ui/console/cmdline/commands/resume.py10
-rw-r--r--deluge/ui/console/cmdline/commands/rm.py30
-rw-r--r--deluge/ui/console/cmdline/commands/status.py32
-rw-r--r--deluge/ui/console/cmdline/commands/update_tracker.py12
-rw-r--r--deluge/ui/console/console.py26
-rw-r--r--deluge/ui/console/main.py234
-rw-r--r--deluge/ui/console/modes/add_util.py22
-rw-r--r--deluge/ui/console/modes/addtorrents.py156
-rw-r--r--deluge/ui/console/modes/basemode.py22
-rw-r--r--deluge/ui/console/modes/cmdline.py166
-rw-r--r--deluge/ui/console/modes/connectionmanager.py74
-rw-r--r--deluge/ui/console/modes/eventview.py16
-rw-r--r--deluge/ui/console/modes/preferences/preference_panes.py444
-rw-r--r--deluge/ui/console/modes/preferences/preferences.py34
-rw-r--r--deluge/ui/console/modes/torrentdetail.py236
-rw-r--r--deluge/ui/console/modes/torrentlist/__init__.py26
-rw-r--r--deluge/ui/console/modes/torrentlist/add_torrents_popup.py54
-rw-r--r--deluge/ui/console/modes/torrentlist/filtersidebar.py36
-rw-r--r--deluge/ui/console/modes/torrentlist/queue_mode.py20
-rw-r--r--deluge/ui/console/modes/torrentlist/search_mode.py56
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentactions.py110
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentlist.py52
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentview.py178
-rw-r--r--deluge/ui/console/modes/torrentlist/torrentviewcolumns.py36
-rw-r--r--deluge/ui/console/parser.py18
-rw-r--r--deluge/ui/console/utils/colors.py190
-rw-r--r--deluge/ui/console/utils/column.py92
-rw-r--r--deluge/ui/console/utils/format_utils.py102
-rw-r--r--deluge/ui/console/widgets/fields.py220
-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.py90
-rw-r--r--deluge/ui/console/widgets/window.py10
-rw-r--r--deluge/ui/coreconfig.py6
-rw-r--r--deluge/ui/gtkui/__init__.py10
-rw-r--r--deluge/ui/gtkui/aboutdialog.py436
-rw-r--r--deluge/ui/gtkui/addtorrentdialog.py350
-rw-r--r--deluge/ui/gtkui/common.py82
-rw-r--r--deluge/ui/gtkui/connectionmanager.py274
-rw-r--r--deluge/ui/gtkui/createtorrentdialog.py186
-rw-r--r--deluge/ui/gtkui/details_tab.py34
-rw-r--r--deluge/ui/gtkui/dialogs.py52
-rw-r--r--deluge/ui/gtkui/edittrackersdialog.py96
-rw-r--r--deluge/ui/gtkui/files_tab.py322
-rw-r--r--deluge/ui/gtkui/filtertreeview.py146
-rw-r--r--deluge/ui/gtkui/gtkui.py216
-rw-r--r--deluge/ui/gtkui/ipcinterface.py74
-rw-r--r--deluge/ui/gtkui/listview.py34
-rw-r--r--deluge/ui/gtkui/mainwindow.py158
-rw-r--r--deluge/ui/gtkui/menubar.py396
-rw-r--r--deluge/ui/gtkui/menubar_osx.py14
-rw-r--r--deluge/ui/gtkui/new_release_dialog.py40
-rw-r--r--deluge/ui/gtkui/options_tab.py208
-rw-r--r--deluge/ui/gtkui/path_chooser.py56
-rwxr-xr-xdeluge/ui/gtkui/path_combo_chooser.py278
-rw-r--r--deluge/ui/gtkui/peers_tab.py178
-rw-r--r--deluge/ui/gtkui/piecesbar.py14
-rw-r--r--deluge/ui/gtkui/pluginmanager.py52
-rw-r--r--deluge/ui/gtkui/preferences.py850
-rw-r--r--deluge/ui/gtkui/queuedtorrents.py48
-rw-r--r--deluge/ui/gtkui/removetorrentdialog.py30
-rw-r--r--deluge/ui/gtkui/sidebar.py26
-rw-r--r--deluge/ui/gtkui/status_tab.py64
-rw-r--r--deluge/ui/gtkui/statusbar.py168
-rw-r--r--deluge/ui/gtkui/systemtray.py210
-rw-r--r--deluge/ui/gtkui/tab_data_funcs.py30
-rw-r--r--deluge/ui/gtkui/toolbar.py84
-rw-r--r--deluge/ui/gtkui/torrentdetails.py104
-rw-r--r--deluge/ui/gtkui/torrentview.py224
-rw-r--r--deluge/ui/gtkui/torrentview_data_funcs.py152
-rw-r--r--deluge/ui/gtkui/trackers_tab.py32
-rw-r--r--deluge/ui/sessionproxy.py30
-rw-r--r--deluge/ui/tracker_icons.py82
-rw-r--r--deluge/ui/ui.py12
-rw-r--r--deluge/ui/ui_entry.py38
-rw-r--r--deluge/ui/util/lang.py30
-rw-r--r--deluge/ui/web/auth.py104
-rw-r--r--deluge/ui/web/common.py14
-rw-r--r--deluge/ui/web/json_api.py298
-rw-r--r--deluge/ui/web/pluginmanager.py68
-rw-r--r--deluge/ui/web/server.py326
-rw-r--r--deluge/ui/web/web.py22
-rw-r--r--docs/source/conf.py8
-rwxr-xr-xgen_web_gettext.py8
-rwxr-xr-xgenerate_pot.py82
-rwxr-xr-xmsgfmt.py10
-rw-r--r--packaging/win32/deluge-bbfreeze.py76
-rwxr-xr-xsetup.py6
-rwxr-xr-xversion.py28
231 files changed, 8841 insertions, 8841 deletions
diff --git a/deluge/_libtorrent.py b/deluge/_libtorrent.py
index 6926e4095..f2aed8962 100644
--- a/deluge/_libtorrent.py
+++ b/deluge/_libtorrent.py
@@ -23,7 +23,7 @@ try:
except ImportError:
import libtorrent as lt
-REQUIRED_VERSION = "1.0.7.0"
+REQUIRED_VERSION = '1.0.7.0'
if VersionSplit(lt.__version__) < VersionSplit(REQUIRED_VERSION):
- raise ImportError("Deluge %s requires libtorrent >= %s" % (get_version(), REQUIRED_VERSION))
+ raise ImportError('Deluge %s requires libtorrent >= %s' % (get_version(), REQUIRED_VERSION))
diff --git a/deluge/bencode.py b/deluge/bencode.py
index 8c00a15c8..5ca7a4a20 100644
--- a/deluge/bencode.py
+++ b/deluge/bencode.py
@@ -75,7 +75,7 @@ def bdecode(x):
try:
r, l = decode_func[x[0]](x, 0)
except (IndexError, KeyError, ValueError):
- raise BTFailure("not a valid bencoded string")
+ raise BTFailure('not a valid bencoded string')
return r
diff --git a/deluge/common.py b/deluge/common.py
index 563b02e81..350239628 100644
--- a/deluge/common.py
+++ b/deluge/common.py
@@ -32,7 +32,7 @@ from deluge.error import InvalidPathError
try:
import dbus
bus = dbus.SessionBus()
- dbus_fileman = bus.get_object("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1")
+ dbus_fileman = bus.get_object('org.freedesktop.FileManager1', '/org/freedesktop/FileManager1')
except Exception:
dbus_fileman = None
@@ -40,29 +40,29 @@ except Exception:
log = logging.getLogger(__name__)
TORRENT_STATE = [
- "Allocating",
- "Checking",
- "Downloading",
- "Seeding",
- "Paused",
- "Error",
- "Queued",
- "Moving"
+ 'Allocating',
+ 'Checking',
+ 'Downloading',
+ 'Seeding',
+ 'Paused',
+ 'Error',
+ 'Queued',
+ 'Moving'
]
FILE_PRIORITY = {
- 0: "Do Not Download",
- 1: "Normal Priority",
- 2: "High Priority",
- 3: "High Priority",
- 4: "High Priority",
- 5: "High Priority",
- 6: "High Priority",
- 7: "Highest Priority",
- "Do Not Download": 0,
- "Normal Priority": 1,
- "High Priority": 5,
- "Highest Priority": 7
+ 0: 'Do Not Download',
+ 1: 'Normal Priority',
+ 2: 'High Priority',
+ 3: 'High Priority',
+ 4: 'High Priority',
+ 5: 'High Priority',
+ 6: 'High Priority',
+ 7: 'Highest Priority',
+ 'Do Not Download': 0,
+ 'Normal Priority': 1,
+ 'High Priority': 5,
+ 'Highest Priority': 7
}
@@ -74,7 +74,7 @@ def get_version():
:rtype: string
"""
- return pkg_resources.require("Deluge")[0].version
+ return pkg_resources.require('Deluge')[0].version
def get_default_config_dir(filename=None):
@@ -89,12 +89,12 @@ def get_default_config_dir(filename=None):
if windows_check():
def save_config_path(resource):
- app_data_path = os.environ.get("APPDATA")
+ app_data_path = os.environ.get('APPDATA')
if not app_data_path:
import _winreg
hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
- "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
- app_data_reg = _winreg.QueryValueEx(hkey, "AppData")
+ 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
+ app_data_reg = _winreg.QueryValueEx(hkey, 'AppData')
app_data_path = app_data_reg[0]
_winreg.CloseKey(hkey)
return os.path.join(app_data_path, resource)
@@ -103,9 +103,9 @@ def get_default_config_dir(filename=None):
if not filename:
filename = ''
try:
- return os.path.join(save_config_path("deluge"), filename)
+ return os.path.join(save_config_path('deluge'), filename)
except OSError as ex:
- log.error("Unable to use default config directory, exiting... (%s)", ex)
+ log.error('Unable to use default config directory, exiting... (%s)', ex)
sys.exit(1)
@@ -115,20 +115,20 @@ def get_default_download_dir():
:rtype: string
"""
- download_dir = ""
+ download_dir = ''
if not windows_check():
from xdg.BaseDirectory import xdg_config_home
try:
with open(os.path.join(xdg_config_home, 'user-dirs.dirs'), 'r') as _file:
for line in _file:
if not line.startswith('#') and line.startswith('XDG_DOWNLOAD_DIR'):
- download_dir = os.path.expandvars(line.partition("=")[2].rstrip().strip('"'))
+ download_dir = os.path.expandvars(line.partition('=')[2].rstrip().strip('"'))
break
except IOError:
pass
if not download_dir:
- download_dir = os.path.join(os.path.expanduser("~"), 'Downloads')
+ download_dir = os.path.join(os.path.expanduser('~'), 'Downloads')
return download_dir
@@ -151,7 +151,7 @@ def vista_check():
:rtype: bool
"""
- return platform.release() == "Vista"
+ return platform.release() == 'Vista'
def osx_check():
@@ -162,7 +162,7 @@ def osx_check():
:rtype: bool
"""
- return platform.system() == "Darwin"
+ return platform.system() == 'Darwin'
def linux_check():
@@ -173,7 +173,7 @@ def linux_check():
:rtype: bool
"""
- return platform.system() == "Linux"
+ return platform.system() == 'Linux'
def get_os_version():
@@ -197,7 +197,7 @@ def get_pixmap(fname):
:rtype: string
"""
- return resource_filename("deluge", os.path.join("ui", "data", "pixmaps", fname))
+ return resource_filename('deluge', os.path.join('ui', 'data', 'pixmaps', fname))
def resource_filename(module, path):
@@ -207,8 +207,8 @@ def resource_filename(module, path):
# not, it returns the first found on the python path, which is not good
# enough.
# 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]))
+ return pkg_resources.require('Deluge>=%s' % get_version())[0].get_resource_filename(
+ pkg_resources._manager, os.path.join(*(module.split('.') + [path]))
)
@@ -223,14 +223,14 @@ def open_file(path, timestamp=None):
if windows_check():
os.startfile(path)
elif osx_check():
- subprocess.Popen(["open", path])
+ subprocess.Popen(['open', path])
else:
if timestamp is None:
timestamp = int(time.time())
env = os.environ.copy()
- env["DESKTOP_STARTUP_ID"] = "%s-%u-%s-xdg_open_TIME%d" % \
+ env['DESKTOP_STARTUP_ID'] = '%s-%u-%s-xdg_open_TIME%d' % \
(os.path.basename(sys.argv[0]), os.getpid(), os.uname()[1], timestamp)
- subprocess.Popen(["xdg-open", "%s" % path], env=env)
+ subprocess.Popen(['xdg-open', '%s' % path], env=env)
def show_file(path, timestamp=None):
@@ -242,21 +242,21 @@ def show_file(path, timestamp=None):
"""
if windows_check():
- subprocess.Popen(["explorer", "/select,", path])
+ subprocess.Popen(['explorer', '/select,', path])
elif osx_check():
- subprocess.Popen(["open", "-R", path])
+ subprocess.Popen(['open', '-R', path])
else:
if timestamp is None:
timestamp = int(time.time())
- startup_id = "%s_%u_%s-dbus_TIME%d" % (os.path.basename(sys.argv[0]), os.getpid(), os.uname()[1], timestamp)
+ startup_id = '%s_%u_%s-dbus_TIME%d' % (os.path.basename(sys.argv[0]), os.getpid(), os.uname()[1], timestamp)
if dbus_fileman:
- paths = [urlparse.urljoin("file:", urllib.pathname2url(utf8_encoded(path)))]
- dbus_fileman.ShowItems(paths, startup_id, dbus_interface="org.freedesktop.FileManager1")
+ paths = [urlparse.urljoin('file:', urllib.pathname2url(utf8_encoded(path)))]
+ dbus_fileman.ShowItems(paths, startup_id, dbus_interface='org.freedesktop.FileManager1')
else:
env = os.environ.copy()
- env["DESKTOP_STARTUP_ID"] = startup_id.replace("dbus", "xdg-open")
+ env['DESKTOP_STARTUP_ID'] = startup_id.replace('dbus', 'xdg-open')
# No option in xdg to highlight a file so just open parent folder.
- subprocess.Popen(["xdg-open", os.path.dirname(path.rstrip("/"))], env=env)
+ subprocess.Popen(['xdg-open', os.path.dirname(path.rstrip('/'))], env=env)
def open_url_in_browser(url):
@@ -272,15 +272,15 @@ def open_url_in_browser(url):
# Formatting text functions
-byte_txt = "B"
-kib_txt = "KiB"
-mib_txt = "MiB"
-gib_txt = "GiB"
-tib_txt = "TiB"
-kib_txt_short = "K"
-mib_txt_short = "M"
-gib_txt_short = "G"
-tib_txt_short = "T"
+byte_txt = 'B'
+kib_txt = 'KiB'
+mib_txt = 'MiB'
+gib_txt = 'GiB'
+tib_txt = 'TiB'
+kib_txt_short = 'K'
+mib_txt_short = 'M'
+gib_txt_short = 'G'
+tib_txt_short = 'T'
def translate_size_units():
@@ -289,15 +289,15 @@ def translate_size_units():
global byte_txt, kib_txt, mib_txt, gib_txt, tib_txt
global kib_txt_short, mib_txt_short, gib_txt_short, tib_txt_short
- byte_txt = _("B")
- kib_txt = _("KiB")
- mib_txt = _("MiB")
- gib_txt = _("GiB")
- tib_txt = _("TiB")
- kib_txt_short = _("K")
- mib_txt_short = _("M")
- gib_txt_short = _("G")
- tib_txt_short = _("T")
+ byte_txt = _('B')
+ kib_txt = _('KiB')
+ mib_txt = _('MiB')
+ gib_txt = _('GiB')
+ tib_txt = _('TiB')
+ kib_txt_short = _('K')
+ mib_txt_short = _('M')
+ gib_txt_short = _('G')
+ tib_txt_short = _('T')
def fsize(fsize_b, precision=1, shortform=False):
@@ -324,15 +324,15 @@ def fsize(fsize_b, precision=1, shortform=False):
"""
if fsize_b >= 1024 ** 4:
- return "%.*f %s" % (precision, fsize_b / 1024 ** 4, tib_txt_short if shortform else tib_txt)
+ return '%.*f %s' % (precision, fsize_b / 1024 ** 4, tib_txt_short if shortform else tib_txt)
elif fsize_b >= 1024 ** 3:
- return "%.*f %s" % (precision, fsize_b / 1024 ** 3, gib_txt_short if shortform else gib_txt)
+ return '%.*f %s' % (precision, fsize_b / 1024 ** 3, gib_txt_short if shortform else gib_txt)
elif fsize_b >= 1024 ** 2:
- return "%.*f %s" % (precision, fsize_b / 1024 ** 2, mib_txt_short if shortform else mib_txt)
+ return '%.*f %s' % (precision, fsize_b / 1024 ** 2, mib_txt_short if shortform else mib_txt)
elif fsize_b >= 1024:
- return "%.*f %s" % (precision, fsize_b / 1024, kib_txt_short if shortform else kib_txt)
+ return '%.*f %s' % (precision, fsize_b / 1024, kib_txt_short if shortform else kib_txt)
else:
- return "%d %s" % (fsize_b, byte_txt)
+ return '%d %s' % (fsize_b, byte_txt)
def fpcnt(dec, precision=2):
@@ -375,13 +375,13 @@ def fspeed(bps, precision=1, shortform=False):
"""
if bps < 1024 ** 2:
- return "%.*f %s" % (precision, bps / 1024, _("K/s") if shortform else _("KiB/s"))
+ return '%.*f %s' % (precision, bps / 1024, _('K/s') if shortform else _('KiB/s'))
elif bps < 1024 ** 3:
- return "%.*f %s" % (precision, bps / 1024 ** 2, _("M/s") if shortform else _("MiB/s"))
+ return '%.*f %s' % (precision, bps / 1024 ** 2, _('M/s') if shortform else _('MiB/s'))
elif bps < 1024 ** 4:
- return "%.*f %s" % (precision, bps / 1024 ** 3, _("G/s") if shortform else _("GiB/s"))
+ return '%.*f %s' % (precision, bps / 1024 ** 3, _('G/s') if shortform else _('GiB/s'))
else:
- return "%.*f %s" % (precision, bps / 1024 ** 4, _("T/s") if shortform else _("TiB/s"))
+ return '%.*f %s' % (precision, bps / 1024 ** 4, _('T/s') if shortform else _('TiB/s'))
def fpeer(num_peers, total_peers):
@@ -402,9 +402,9 @@ def fpeer(num_peers, total_peers):
"""
if total_peers > -1:
- return "{:d} ({:d})".format(num_peers, total_peers)
+ return '{:d} ({:d})'.format(num_peers, total_peers)
else:
- return "{:d}".format(num_peers)
+ return '{:d}'.format(num_peers)
def ftime(secs):
@@ -456,8 +456,8 @@ def fdate(seconds, date_only=False, precision_secs=False):
"""
if seconds < 0:
- return ""
- time_format = "%x %X" if precision_secs else "%x %H:%M"
+ return ''
+ time_format = '%x %X' if precision_secs else '%x %H:%M'
if date_only:
time_format = time_format.split()[0]
return time.strftime(time_format, time.localtime(seconds))
@@ -535,7 +535,7 @@ def parse_human_size(size):
if normalized_unit.startswith(unit['prefix'].lower()):
return int(tokens[0] * unit['divider'])
# We failed to parse the size specification.
- msg = "Failed to parse size! (input %r was tokenized as %r)"
+ msg = 'Failed to parse size! (input %r was tokenized as %r)'
raise InvalidSize(msg % (size, tokens))
@@ -554,7 +554,7 @@ def is_url(url):
True
"""
- return url.partition('://')[0] in ("http", "https", "ftp", "udp")
+ return url.partition('://')[0] in ('http', 'https', 'ftp', 'udp')
def is_infohash(infohash):
@@ -623,9 +623,9 @@ def get_magnet_info(uri):
xt_hash = param[len(xt_param):]
if len(xt_hash) == 32:
try:
- info_hash = base64.b32decode(xt_hash.upper()).encode("hex")
+ info_hash = base64.b32decode(xt_hash.upper()).encode('hex')
except TypeError as ex:
- log.debug("Invalid base32 magnet hash: %s, %s", xt_hash, ex)
+ log.debug('Invalid base32 magnet hash: %s, %s', xt_hash, ex)
break
elif is_infohash(xt_hash):
info_hash = xt_hash.lower()
@@ -637,7 +637,7 @@ def get_magnet_info(uri):
if info_hash:
if not name:
name = info_hash
- return {"name": name, "info_hash": info_hash, "files_tree": ''}
+ return {'name': name, 'info_hash': info_hash, 'files_tree': ''}
return False
@@ -657,12 +657,12 @@ def create_magnet_uri(infohash, name=None, trackers=None):
"""
from base64 import b32encode
- uri = "magnet:?xt=urn:btih:" + b32encode(infohash.decode("hex"))
+ uri = 'magnet:?xt=urn:btih:' + b32encode(infohash.decode('hex'))
if name:
- uri = uri + "&dn=" + name
+ uri = uri + '&dn=' + name
if trackers:
for t in trackers:
- uri = uri + "&tr=" + t
+ uri = uri + '&tr=' + t
return uri
@@ -704,13 +704,13 @@ def free_space(path):
"""
if not path or not os.path.exists(path):
- raise InvalidPathError("%s is not a valid path" % path)
+ raise InvalidPathError('%s is not a valid path' % path)
if windows_check():
from win32file import GetDiskFreeSpaceEx
return GetDiskFreeSpaceEx(path)[0]
else:
- disk_data = os.statvfs(path.encode("utf8"))
+ disk_data = os.statvfs(path.encode('utf8'))
block_size = disk_data.f_frsize
return disk_data.f_bavail * block_size
@@ -745,7 +745,7 @@ def is_ip(ip):
# now test ipv6
try:
if windows_check():
- log.warning("ipv6 check unavailable on windows")
+ log.warning('ipv6 check unavailable on windows')
return True
else:
if socket.inet_pton(socket.AF_INET6, ip):
@@ -754,7 +754,7 @@ def is_ip(ip):
return False
-def decode_string(s, encoding="utf8"):
+def decode_string(s, encoding='utf8'):
"""
Decodes a string and return unicode. If it cannot decode using
`:param:encoding` then it will try latin1, and if that fails,
@@ -774,12 +774,12 @@ def decode_string(s, encoding="utf8"):
elif isinstance(s, unicode):
return s
- encodings = [lambda: ("utf8", 'strict'),
- lambda: ("iso-8859-1", 'strict'),
- lambda: (chardet.detect(s)["encoding"], 'strict'),
+ encodings = [lambda: ('utf8', 'strict'),
+ lambda: ('iso-8859-1', 'strict'),
+ lambda: (chardet.detect(s)['encoding'], 'strict'),
lambda: (encoding, 'ignore')]
- if encoding is not "utf8":
+ if encoding is not 'utf8':
encodings.insert(0, lambda: (encoding, 'strict'))
for l in encodings:
@@ -790,7 +790,7 @@ def decode_string(s, encoding="utf8"):
return u''
-def utf8_encoded(s, encoding="utf8"):
+def utf8_encoded(s, encoding='utf8'):
"""
Returns a utf8 encoded string of s
@@ -803,9 +803,9 @@ def utf8_encoded(s, encoding="utf8"):
"""
if isinstance(s, str):
- s = decode_string(s, encoding).encode("utf8")
+ s = decode_string(s, encoding).encode('utf8')
elif isinstance(s, unicode):
- s = s.encode("utf8")
+ s = s.encode('utf8')
return s
@@ -838,13 +838,13 @@ class VersionSplit(object):
vs = [''.join(group[0:2]), ''.join(group[2:4]), group[4].lstrip('.')]
else:
ver = ver.lower()
- vs = ver.replace("_", "-").split("-")
+ vs = ver.replace('_', '-').split('-')
- self.version = [int(x) for x in vs[0].split(".") if x.isdigit()]
+ self.version = [int(x) for x in vs[0].split('.') if x.isdigit()]
self.suffix = None
self.dev = False
if len(vs) > 1:
- if vs[1].startswith(("rc", "a", "b", "c")):
+ if vs[1].startswith(('rc', 'a', 'b', 'c')):
self.suffix = vs[1]
if vs[-1].startswith('dev'):
self.dev = vs[-1]
@@ -889,10 +889,10 @@ def create_auth_file():
import stat
import deluge.configmanager
- auth_file = deluge.configmanager.get_config_dir("auth")
+ auth_file = deluge.configmanager.get_config_dir('auth')
# Check for auth file and create if necessary
if not os.path.exists(auth_file):
- with open(auth_file, "w") as _file:
+ with open(auth_file, 'w') as _file:
_file.flush()
os.fsync(_file.fileno())
# Change the permissions on the file so only this user can read/write it
@@ -904,13 +904,13 @@ def create_localclient_account(append=False):
from hashlib import sha1 as sha
import deluge.configmanager
- auth_file = deluge.configmanager.get_config_dir("auth")
+ auth_file = deluge.configmanager.get_config_dir('auth')
if not os.path.exists(auth_file):
create_auth_file()
- with open(auth_file, "a" if append else "w") as _file:
- _file.write(":".join([
- "localclient",
+ with open(auth_file, 'a' if append else 'w') as _file:
+ _file.write(':'.join([
+ 'localclient',
sha(str(random.random())).hexdigest(),
str(AUTH_LEVEL_ADMIN)
]) + '\n')
@@ -1008,11 +1008,11 @@ def unicode_argv():
else:
# On other platforms, we have to find the likely encoding of the args and decode
# First check if sys.stdout or stdin have encoding set
- encoding = getattr(sys.stdout, "encoding") or getattr(sys.stdin, "encoding")
+ encoding = getattr(sys.stdout, 'encoding') or getattr(sys.stdin, 'encoding')
# If that fails, check what the locale is set to
encoding = encoding or locale.getpreferredencoding()
# As a last resort, just default to utf-8
- encoding = encoding or "utf-8"
+ encoding = encoding or 'utf-8'
return [arg.decode(encoding) for arg in sys.argv]
@@ -1028,16 +1028,16 @@ def run_profiled(func, *args, **kwargs):
output_file (str, optional): Filename to save profile results. If None, print to stdout.
Defaults to None.
"""
- if kwargs.get("do_profile", True) is not False:
+ if kwargs.get('do_profile', True) is not False:
import cProfile
profiler = cProfile.Profile()
def on_shutdown():
- output_file = kwargs.get("output_file", None)
+ output_file = kwargs.get('output_file', None)
if output_file:
profiler.dump_stats(output_file)
- log.info("Profile stats saved to %s", output_file)
- print("Profile stats saved to %s" % output_file)
+ log.info('Profile stats saved to %s', output_file)
+ print('Profile stats saved to %s' % output_file)
else:
import pstats
import StringIO
diff --git a/deluge/component.py b/deluge/component.py
index ea9cb9676..787664fa2 100644
--- a/deluge/component.py
+++ b/deluge/component.py
@@ -31,7 +31,7 @@ class ComponentException(Exception):
def __str__(self):
s = super(ComponentException, self).__str__()
- return "%s\n%s" % (s, "".join(self.tb))
+ return '%s\n%s' % (s, ''.join(self.tb))
def __eq__(self, other):
if isinstance(other, self.__class__):
@@ -101,7 +101,7 @@ class Component(object):
self._component_name = name
self._component_interval = interval
self._component_depend = depend
- self._component_state = "Stopped"
+ self._component_state = 'Stopped'
self._component_timer = None
self._component_starting_deferred = None
self._component_stopping_deferred = None
@@ -112,34 +112,34 @@ class Component(object):
_ComponentRegistry.deregister(self)
def _component_start_timer(self):
- if hasattr(self, "update"):
+ if hasattr(self, 'update'):
self._component_timer = LoopingCall(self.update)
self._component_timer.start(self._component_interval)
def _component_start(self):
def on_start(result):
- self._component_state = "Started"
+ self._component_state = 'Started'
self._component_starting_deferred = None
self._component_start_timer()
return True
def on_start_fail(result):
- self._component_state = "Stopped"
+ self._component_state = 'Stopped'
self._component_starting_deferred = None
log.error(result)
return fail(result)
- if self._component_state == "Stopped":
- if hasattr(self, "start"):
- self._component_state = "Starting"
+ if self._component_state == 'Stopped':
+ if hasattr(self, 'start'):
+ self._component_state = 'Starting'
d = deferLater(reactor, 0, self.start)
d.addCallbacks(on_start, on_start_fail)
self._component_starting_deferred = d
else:
d = maybeDeferred(on_start, None)
- elif self._component_state == "Starting":
+ elif self._component_state == 'Starting':
return self._component_starting_deferred
- elif self._component_state == "Started":
+ elif self._component_state == 'Started':
d = succeed(True)
else:
d = fail(ComponentException("Trying to start a component ('%s') not in stopped state. Current state: '%s'" %
@@ -148,20 +148,20 @@ class Component(object):
def _component_stop(self):
def on_stop(result):
- self._component_state = "Stopped"
+ self._component_state = 'Stopped'
if self._component_timer and self._component_timer.running:
self._component_timer.stop()
return True
def on_stop_fail(result):
- self._component_state = "Started"
+ self._component_state = 'Started'
self._component_stopping_deferred = None
log.error(result)
return result
- if self._component_state != "Stopped" and self._component_state != "Stopping":
- if hasattr(self, "stop"):
- self._component_state = "Stopping"
+ if self._component_state != 'Stopped' and self._component_state != 'Stopping':
+ if hasattr(self, 'stop'):
+ self._component_state = 'Stopping'
d = maybeDeferred(self.stop)
d.addCallback(on_stop)
d.addErrback(on_stop_fail)
@@ -169,22 +169,22 @@ class Component(object):
else:
d = maybeDeferred(on_stop, None)
- if self._component_state == "Stopping":
+ if self._component_state == 'Stopping':
return self._component_stopping_deferred
return succeed(None)
def _component_pause(self):
def on_pause(result):
- self._component_state = "Paused"
+ self._component_state = 'Paused'
- if self._component_state == "Started":
+ if self._component_state == 'Started':
if self._component_timer and self._component_timer.running:
d = maybeDeferred(self._component_timer.stop)
d.addCallback(on_pause)
else:
d = succeed(None)
- elif self._component_state == "Paused":
+ elif self._component_state == 'Paused':
d = succeed(None)
else:
d = fail(ComponentException("Trying to pause a component ('%s') not in started state. Current state: '%s'" %
@@ -193,9 +193,9 @@ class Component(object):
def _component_resume(self):
def on_resume(result):
- self._component_state = "Started"
+ self._component_state = 'Started'
- if self._component_state == "Paused":
+ if self._component_state == 'Paused':
d = maybeDeferred(self._component_start_timer)
d.addCallback(on_resume)
else:
@@ -205,7 +205,7 @@ class Component(object):
def _component_shutdown(self):
def on_stop(result):
- if hasattr(self, "shutdown"):
+ if hasattr(self, 'shutdown'):
return maybeDeferred(self.shutdown)
return succeed(None)
@@ -254,7 +254,7 @@ class ComponentRegistry(object):
"""
name = obj._component_name
if name in self.components:
- raise ComponentAlreadyRegistered("Component already registered with name %s" % name)
+ raise ComponentAlreadyRegistered('Component already registered with name %s' % name)
self.components[obj._component_name] = obj
if obj._component_depend:
@@ -273,7 +273,7 @@ class ComponentRegistry(object):
"""
if obj in self.components.values():
- log.debug("Deregistering Component: %s", obj._component_name)
+ log.debug('Deregistering Component: %s', obj._component_name)
d = self.stop([obj._component_name])
def on_stop(result, name):
@@ -377,7 +377,7 @@ class ComponentRegistry(object):
deferreds = []
for name in names:
- if self.components[name]._component_state == "Started":
+ if self.components[name]._component_state == 'Started':
deferreds.append(self.components[name]._component_pause())
return DeferredList(deferreds)
@@ -403,7 +403,7 @@ class ComponentRegistry(object):
deferreds = []
for name in names:
- if self.components[name]._component_state == "Paused":
+ if self.components[name]._component_state == 'Paused':
deferreds.append(self.components[name]._component_resume())
return DeferredList(deferreds)
diff --git a/deluge/config.py b/deluge/config.py
index c7ad1c2b8..14bf703b5 100644
--- a/deluge/config.py
+++ b/deluge/config.py
@@ -82,16 +82,16 @@ def find_json_objects(s):
"""
objects = []
opens = 0
- start = s.find("{")
+ start = s.find('{')
offset = start
if start < 0:
return []
for index, c in enumerate(s[offset:]):
- if c == "{":
+ if c == '{':
opens += 1
- elif c == "}":
+ elif c == '}':
opens -= 1
if opens == 0:
objects.append((start, index + offset + 1))
@@ -119,8 +119,8 @@ class Config(object):
# These hold the version numbers and they will be set when loaded
self.__version = {
- "format": 1,
- "file": file_version
+ 'format': 1,
+ 'file': file_version
}
# This will get set with a reactor.callLater whenever a config option
@@ -186,7 +186,7 @@ class Config(object):
try:
oldtype = type(self.__config[key])
if isinstance(self.__config[key], unicode):
- value = oldtype(value, "utf8")
+ value = oldtype(value, 'utf8')
else:
value = oldtype(value)
except ValueError:
@@ -244,7 +244,7 @@ class Config(object):
"""
if isinstance(self.__config[key], str):
try:
- return self.__config[key].decode("utf8")
+ return self.__config[key].decode('utf8')
except UnicodeDecodeError:
return self.__config[key]
else:
@@ -342,7 +342,7 @@ class Config(object):
test 5
"""
- log.debug("Registering function for %s key..", key)
+ log.debug('Registering function for %s key..', key)
if key not in self.__set_functions:
self.__set_functions[key] = []
@@ -367,7 +367,7 @@ class Config(object):
test 5
"""
- log.debug("Calling all set functions..")
+ log.debug('Calling all set functions..')
for key, value in self.__set_functions.iteritems():
for func in value:
func(key, self.__config[key])
@@ -379,7 +379,7 @@ class Config(object):
key (str): the config key
"""
- log.debug("Calling set functions for key %s..", key)
+ log.debug('Calling set functions for key %s..', key)
if key in self.__set_functions:
for func in self.__set_functions[key]:
func(key, self.__config[key])
@@ -395,10 +395,10 @@ class Config(object):
filename = self.__config_file
try:
- with open(filename, "rb") as _file:
+ with open(filename, 'rb') as _file:
data = _file.read()
except IOError as ex:
- log.warning("Unable to open config file %s: %s", filename, ex)
+ log.warning('Unable to open config file %s: %s', filename, ex)
return
objects = find_json_objects(data)
@@ -409,14 +409,14 @@ class Config(object):
self.__config.update(pickle.loads(data))
except Exception as ex:
log.exception(ex)
- log.warning("Unable to load config file: %s", filename)
+ log.warning('Unable to load config file: %s', filename)
elif len(objects) == 1:
start, end = objects[0]
try:
self.__config.update(json.loads(data[start:end]))
except Exception as ex:
log.exception(ex)
- log.warning("Unable to load config file: %s", filename)
+ log.warning('Unable to load config file: %s', filename)
elif len(objects) == 2:
try:
start, end = objects[0]
@@ -425,10 +425,10 @@ class Config(object):
self.__config.update(json.loads(data[start:end]))
except Exception as ex:
log.exception(ex)
- log.warning("Unable to load config file: %s", filename)
+ 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
@@ -445,7 +445,7 @@ class Config(object):
# Check to see if the current config differs from the one on disk
# We will only write a new config file if there is a difference
try:
- with open(filename, "rb") as _file:
+ with open(filename, 'rb') as _file:
data = _file.read()
objects = find_json_objects(data)
start, end = objects[0]
@@ -458,34 +458,34 @@ class Config(object):
self._save_timer.cancel()
return True
except (IOError, IndexError) as ex:
- log.warning("Unable to open config file: %s because: %s", filename, ex)
+ log.warning('Unable to open config file: %s because: %s', filename, ex)
# Save the new config and make sure it's written to disk
try:
- log.debug("Saving new config file %s", filename + ".new")
- with open(filename + ".new", "wb") as _file:
+ log.debug('Saving new config file %s', filename + '.new')
+ with open(filename + '.new', 'wb') as _file:
json.dump(self.__version, _file, indent=2)
json.dump(self.__config, _file, indent=2, sort_keys=True)
_file.flush()
os.fsync(_file.fileno())
except IOError as ex:
- log.error("Error writing new config file: %s", ex)
+ log.error('Error writing new config file: %s', ex)
return False
# Make a backup of the old config
try:
- log.debug("Backing up old config file to %s.bak", filename)
- shutil.move(filename, filename + ".bak")
+ log.debug('Backing up old config file to %s.bak', filename)
+ shutil.move(filename, filename + '.bak')
except IOError as ex:
- log.warning("Unable to backup old config: %s", ex)
+ log.warning('Unable to backup old config: %s', ex)
# The new config file has been written successfully, so let's move it over
# the existing one.
try:
- log.debug("Moving new config file %s to %s..", filename + ".new", filename)
- shutil.move(filename + ".new", filename)
+ log.debug('Moving new config file %s to %s..', filename + '.new', filename)
+ shutil.move(filename + '.new', filename)
except IOError as ex:
- log.error("Error moving new config file: %s", ex)
+ log.error('Error moving new config file: %s', ex)
return False
else:
return True
@@ -508,22 +508,22 @@ class Config(object):
"""
if output_version in input_range or output_version <= max(input_range):
- raise ValueError("output_version needs to be greater than input_range")
+ 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)
+ 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)
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
+ self.__version['file'] = output_version
self.save()
@property
diff --git a/deluge/configmanager.py b/deluge/configmanager.py
index 4738a30e3..1fef1c873 100644
--- a/deluge/configmanager.py
+++ b/deluge/configmanager.py
@@ -19,7 +19,7 @@ log = logging.getLogger(__name__)
class _ConfigManager(object):
def __init__(self):
- log.debug("ConfigManager started..")
+ log.debug('ConfigManager started..')
self.config_files = {}
self.__config_directory = None
@@ -44,16 +44,16 @@ class _ConfigManager(object):
if not directory:
return False
- log.info("Setting config directory to: %s", directory)
+ log.info('Setting config directory to: %s', directory)
if not os.path.exists(directory):
# Try to create the config folder if it doesn't exist
try:
os.makedirs(directory)
except OSError as ex:
- log.error("Unable to make config directory: %s", ex)
+ log.error('Unable to make config directory: %s', ex)
return False
elif not os.path.isdir(directory):
- log.error("Config directory needs to be a directory!")
+ log.error('Config directory needs to be a directory!')
return False
self.__config_directory = directory
diff --git a/deluge/core/alertmanager.py b/deluge/core/alertmanager.py
index 4b06798b7..8a45dbde5 100644
--- a/deluge/core/alertmanager.py
+++ b/deluge/core/alertmanager.py
@@ -30,9 +30,9 @@ log = logging.getLogger(__name__)
class AlertManager(component.Component):
"""AlertManager fetches and processes libtorrent alerts"""
def __init__(self):
- log.debug("AlertManager init...")
- component.Component.__init__(self, "AlertManager", interval=0.3)
- self.session = component.get("Core").session
+ log.debug('AlertManager init...')
+ component.Component.__init__(self, 'AlertManager', interval=0.3)
+ self.session = component.get('Core').session
# Increase the alert queue size so that alerts don't get lost.
self.alert_queue_size = 10000
@@ -47,7 +47,7 @@ class AlertManager(component.Component):
lt.alert.category_t.performance_warning)
try:
- self.session.apply_settings("alert_mask", alert_mask)
+ self.session.apply_settings('alert_mask', alert_mask)
except AttributeError:
self.session.set_alert_mask(alert_mask)
@@ -81,7 +81,7 @@ class AlertManager(component.Component):
# Append the handler to the list in the handlers dictionary
self.handlers[alert_type].append(handler)
- log.debug("Registered handler for alert %s", alert_type)
+ log.debug('Registered handler for alert %s', alert_type)
def deregister_handler(self, handler):
"""
@@ -105,16 +105,16 @@ class AlertManager(component.Component):
num_alerts = len(alerts)
if log.isEnabledFor(logging.DEBUG):
- log.debug("Alerts queued: %s", num_alerts)
+ log.debug('Alerts queued: %s', num_alerts)
if num_alerts > 0.9 * self.alert_queue_size:
- log.warning("Warning total alerts queued, %s, passes 90%% of queue size.", num_alerts)
+ log.warning('Warning total alerts queued, %s, passes 90%% of queue size.', num_alerts)
# Loop through all alerts in the queue
for alert in alerts:
alert_type = type(alert).__name__
# Display the alert message
if log.isEnabledFor(logging.DEBUG):
- log.debug("%s: %s", alert_type, decode_string(alert.message()))
+ log.debug('%s: %s', alert_type, decode_string(alert.message()))
# Call any handlers for this alert type
if alert_type in self.handlers:
for handler in self.handlers[alert_type]:
@@ -122,6 +122,6 @@ class AlertManager(component.Component):
def set_alert_queue_size(self, queue_size):
"""Sets the maximum size of the libtorrent alert queue"""
- log.info("Alert Queue Size set to %s", queue_size)
+ log.info('Alert Queue Size set to %s', queue_size)
self.alert_queue_size = queue_size
- component.get("Core").apply_session_setting("alert_queue_size", self.alert_queue_size)
+ component.get('Core').apply_session_setting('alert_queue_size', self.alert_queue_size)
diff --git a/deluge/core/authmanager.py b/deluge/core/authmanager.py
index ee94f003e..d04982bea 100644
--- a/deluge/core/authmanager.py
+++ b/deluge/core/authmanager.py
@@ -51,12 +51,12 @@ class Account(object):
def __repr__(self):
return ('<Account username="%(username)s" authlevel=%(authlevel)s>' %
- {"username": self.username, "authlevel": self.authlevel})
+ {'username': self.username, 'authlevel': self.authlevel})
class AuthManager(component.Component):
def __init__(self):
- component.Component.__init__(self, "AuthManager", interval=10)
+ component.Component.__init__(self, 'AuthManager', interval=10)
self.__auth = {}
self.__auth_modification_time = None
@@ -70,16 +70,16 @@ class AuthManager(component.Component):
pass
def update(self):
- auth_file = configmanager.get_config_dir("auth")
+ auth_file = configmanager.get_config_dir('auth')
# Check for auth file and create if necessary
if not os.path.isfile(auth_file):
- log.info("Authfile not found, recreating it.")
+ log.info('Authfile not found, recreating it.')
self.__load_auth_file()
return
auth_file_modification_time = os.stat(auth_file).st_mtime
if self.__auth_modification_time != auth_file_modification_time:
- log.info("Auth file changed, reloading it!")
+ log.info('Auth file changed, reloading it!')
self.__load_auth_file()
def authorize(self, username, password):
@@ -99,22 +99,22 @@ 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:
# Let's try to re-load the file.. Maybe it's been updated
self.__load_auth_file()
if username not in self.__auth:
- raise BadLoginError("Username does not exist", username)
+ raise BadLoginError('Username does not exist', username)
if self.__auth[username].password == password:
# Return the users auth level
return self.__auth[username].authlevel
elif not password and self.__auth[username].password:
- raise AuthenticationRequired("Password is required", username)
+ raise AuthenticationRequired('Password is required', username)
else:
- raise BadLoginError("Password does not match", username)
+ raise BadLoginError('Password does not match', username)
def has_account(self, username):
return username in self.__auth
@@ -126,7 +126,7 @@ class AuthManager(component.Component):
def create_account(self, username, password, authlevel):
if username in self.__auth:
- raise AuthManagerError("Username in use.", username)
+ raise AuthManagerError('Username in use.', username)
if authlevel not in AUTH_LEVELS_MAPPING:
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
try:
@@ -140,7 +140,7 @@ class AuthManager(component.Component):
def update_account(self, username, password, authlevel):
if username not in self.__auth:
- raise AuthManagerError("Username not known", username)
+ raise AuthManagerError('Username not known', username)
if authlevel not in AUTH_LEVELS_MAPPING:
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
try:
@@ -155,10 +155,10 @@ class AuthManager(component.Component):
def remove_account(self, username):
if username not in self.__auth:
- raise AuthManagerError("Username not known", username)
- elif username == component.get("RPCServer").get_session_user():
+ 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]
@@ -166,39 +166,39 @@ class AuthManager(component.Component):
return True
def write_auth_file(self):
- filename = "auth"
+ filename = 'auth'
filepath = os.path.join(configmanager.get_config_dir(), filename)
- filepath_bak = filepath + ".bak"
- filepath_tmp = filepath + ".tmp"
+ filepath_bak = filepath + '.bak'
+ filepath_tmp = filepath + '.tmp'
try:
if os.path.isfile(filepath):
- log.debug("Creating backup of %s at: %s", filename, filepath_bak)
+ log.debug('Creating backup of %s at: %s', filename, filepath_bak)
shutil.copy2(filepath, filepath_bak)
except IOError as ex:
- log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex)
+ log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
else:
- log.info("Saving the %s at: %s", filename, filepath)
+ log.info('Saving the %s at: %s', filename, filepath)
try:
- with open(filepath_tmp, "wb") as _file:
+ with open(filepath_tmp, 'wb') as _file:
for account in self.__auth.values():
- _file.write("%(username)s:%(password)s:%(authlevel_int)s\n" % account.data())
+ _file.write('%(username)s:%(password)s:%(authlevel_int)s\n' % account.data())
_file.flush()
os.fsync(_file.fileno())
shutil.move(filepath_tmp, filepath)
except IOError as ex:
- log.error("Unable to save %s: %s", filename, ex)
+ log.error('Unable to save %s: %s', filename, ex)
if os.path.isfile(filepath_bak):
- log.info("Restoring backup of %s from: %s", filename, filepath_bak)
+ log.info('Restoring backup of %s from: %s', filename, filepath_bak)
shutil.move(filepath_bak, filepath)
self.__load_auth_file()
def __load_auth_file(self):
save_and_reload = False
- filename = "auth"
+ filename = 'auth'
auth_file = configmanager.get_config_dir(filename)
- auth_file_bak = auth_file + ".bak"
+ auth_file_bak = auth_file + '.bak'
# Check for auth file and create if necessary
if not os.path.isfile(auth_file):
@@ -213,28 +213,28 @@ class AuthManager(component.Component):
return
for _filepath in (auth_file, auth_file_bak):
- log.info("Opening %s for load: %s", filename, _filepath)
+ log.info('Opening %s for load: %s', filename, _filepath)
try:
- with open(_filepath, "rb") as _file:
+ with open(_filepath, 'rb') as _file:
file_data = _file.readlines()
except IOError as ex:
- log.warning("Unable to load %s: %s", _filepath, ex)
+ log.warning('Unable to load %s: %s', _filepath, ex)
file_data = []
else:
- log.info("Successfully loaded %s: %s", filename, _filepath)
+ log.info('Successfully loaded %s: %s', filename, _filepath)
break
# Load the auth file into a dictionary: {username: Account(...)}
for line in file_data:
line = line.strip()
- if line.startswith("#") or not line:
+ if line.startswith('#') or not line:
# This line is a comment or empty
continue
- lsplit = line.split(":")
+ 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:
@@ -244,7 +244,7 @@ class AuthManager(component.Component):
elif len(lsplit) == 3:
username, password, authlevel = lsplit
else:
- log.error("Your auth file is malformed: Incorrect number of fields!")
+ log.error('Your auth file is malformed: Incorrect number of fields!')
continue
username = username.strip()
@@ -255,16 +255,16 @@ class AuthManager(component.Component):
try:
authlevel = AUTH_LEVELS_MAPPING[authlevel]
except KeyError:
- log.error("Your auth file is malformed: %r is not a valid auth level", authlevel)
+ log.error('Your auth file is malformed: %r is not a valid auth level', authlevel)
continue
self.__auth[username] = Account(username, password, authlevel)
- if "localclient" not in self.__auth:
+ if 'localclient' not in self.__auth:
create_localclient_account(True)
return self.__load_auth_file()
if save_and_reload:
- log.info("Re-writing auth file (upgrade)")
+ log.info('Re-writing auth file (upgrade)')
self.write_auth_file()
self.__auth_modification_time = auth_file_modification_time
diff --git a/deluge/core/core.py b/deluge/core/core.py
index 604c93b91..b781501fa 100644
--- a/deluge/core/core.py
+++ b/deluge/core/core.py
@@ -44,22 +44,22 @@ log = logging.getLogger(__name__)
class Core(component.Component):
def __init__(self, listen_interface=None, read_only_config_keys=None):
- log.debug("Core init...")
- component.Component.__init__(self, "Core")
+ log.debug('Core init...')
+ component.Component.__init__(self, 'Core')
# These keys will be dropped from the set_config() RPC and are
# configurable from the command-line.
self.read_only_config_keys = read_only_config_keys
- log.debug("read_only_config_keys: %s", read_only_config_keys)
+ log.debug('read_only_config_keys: %s', read_only_config_keys)
# Create the client fingerprint
- client_id = "DE"
+ client_id = 'DE'
client_version = deluge.common.VersionSplit(deluge.common.get_version()).version
while len(client_version) < 4:
client_version.append(0)
# Start the libtorrent session
- log.info("Starting libtorrent %s (%s, %s) session...", lt.__version__, client_id, client_version)
+ log.info('Starting libtorrent %s (%s, %s) session...', lt.__version__, client_id, client_version)
self.session = lt.session(lt.fingerprint(client_id, *client_version), flags=0)
# Load the session state if available
@@ -67,20 +67,20 @@ class Core(component.Component):
# Apply session settings
self.apply_session_setting(
- "user_agent",
- "Deluge/%(deluge_version)s libtorrent/%(lt_version)s" % {
+ 'user_agent',
+ 'Deluge/%(deluge_version)s libtorrent/%(lt_version)s' % {
'deluge_version': deluge.common.get_version(),
- 'lt_version': self.get_libtorrent_version().rpartition(".")[0]}
+ 'lt_version': self.get_libtorrent_version().rpartition('.')[0]}
)
# No SSL torrent support in code so disable the listen port.
- self.apply_session_setting("ssl_listen", 0)
+ self.apply_session_setting('ssl_listen', 0)
# Enable libtorrent extensions
# Allows peers to download the metadata from the swarm directly
- self.session.add_extension("ut_metadata")
+ self.session.add_extension('ut_metadata')
# Ban peers that sends bad data
- self.session.add_extension("smart_ban")
+ self.session.add_extension('smart_ban')
# Create the components
self.eventmanager = EventManager()
@@ -96,13 +96,13 @@ class Core(component.Component):
# External IP Address from libtorrent
self.external_ip = None
- self.eventmanager.register_event_handler("ExternalIPEvent", self._on_external_ip_event)
+ self.eventmanager.register_event_handler('ExternalIPEvent', self._on_external_ip_event)
# GeoIP instance with db loaded
self.geoip_instance = None
# Get the core config
- self.config = ConfigManager("core.conf")
+ self.config = ConfigManager('core.conf')
self.config.save()
# If there was an interface value from the command line, use it, but
@@ -110,10 +110,10 @@ class Core(component.Component):
self.__old_interface = None
if listen_interface:
if deluge.common.is_ip(listen_interface):
- self.__old_interface = self.config["listen_interface"]
- self.config["listen_interface"] = listen_interface
+ self.__old_interface = self.config['listen_interface']
+ self.config['listen_interface'] = listen_interface
else:
- log.error("Invalid listen interface (must be IP Address): %s", listen_interface)
+ log.error('Invalid listen interface (must be IP Address): %s', listen_interface)
# New release check information
self.__new_release = None
@@ -123,14 +123,14 @@ class Core(component.Component):
pass
def stop(self):
- log.debug("Core stopping...")
+ log.debug('Core stopping...')
# Save the libtorrent session state
self.__save_session_state()
# We stored a copy of the old interface value
if self.__old_interface:
- self.config["listen_interface"] = self.__old_interface
+ self.config['listen_interface'] = self.__old_interface
# Make sure the config file has been saved
self.config.save()
@@ -156,64 +156,64 @@ class Core(component.Component):
def __save_session_state(self):
"""Saves the libtorrent session state"""
- filename = "session.state"
+ filename = 'session.state'
filepath = get_config_dir(filename)
- filepath_bak = filepath + ".bak"
- filepath_tmp = filepath + ".tmp"
+ filepath_bak = filepath + '.bak'
+ filepath_tmp = filepath + '.tmp'
try:
if os.path.isfile(filepath):
- log.debug("Creating backup of %s at: %s", filename, filepath_bak)
+ log.debug('Creating backup of %s at: %s', filename, filepath_bak)
shutil.copy2(filepath, filepath_bak)
except IOError as ex:
- log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex)
+ log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
else:
- log.info("Saving the %s at: %s", filename, filepath)
+ log.info('Saving the %s at: %s', filename, filepath)
try:
- with open(filepath_tmp, "wb") as _file:
+ with open(filepath_tmp, 'wb') as _file:
_file.write(lt.bencode(self.session.save_state()))
_file.flush()
os.fsync(_file.fileno())
shutil.move(filepath_tmp, filepath)
except (IOError, EOFError) as ex:
- log.error("Unable to save %s: %s", filename, ex)
+ log.error('Unable to save %s: %s', filename, ex)
if os.path.isfile(filepath_bak):
- log.info("Restoring backup of %s from: %s", filename, filepath_bak)
+ log.info('Restoring backup of %s from: %s', filename, filepath_bak)
shutil.move(filepath_bak, filepath)
def __load_session_state(self):
"""Loads the libtorrent session state"""
- filename = "session.state"
+ filename = 'session.state'
filepath = get_config_dir(filename)
- filepath_bak = filepath + ".bak"
+ filepath_bak = filepath + '.bak'
for _filepath in (filepath, filepath_bak):
- log.info("Opening %s for load: %s", filename, _filepath)
+ log.info('Opening %s for load: %s', filename, _filepath)
try:
- with open(_filepath, "rb") as _file:
+ with open(_filepath, 'rb') as _file:
state = lt.bdecode(_file.read())
except (IOError, EOFError, RuntimeError) as ex:
- log.warning("Unable to load %s: %s", _filepath, ex)
+ log.warning('Unable to load %s: %s', _filepath, ex)
else:
- log.info("Successfully loaded %s: %s", filename, _filepath)
+ log.info('Successfully loaded %s: %s', filename, _filepath)
self.session.load_state(state)
return
def get_new_release(self):
- log.debug("get_new_release")
+ log.debug('get_new_release')
from urllib2 import urlopen, URLError
try:
- self.new_release = urlopen("http://download.deluge-torrent.org/version-1.0").read().strip()
+ self.new_release = urlopen('http://download.deluge-torrent.org/version-1.0').read().strip()
except URLError as ex:
- log.debug("Unable to get release info from website: %s", ex)
+ log.debug('Unable to get release info from website: %s', ex)
return
self.check_new_release()
def check_new_release(self):
if self.new_release:
- log.debug("new_release: %s", self.new_release)
+ log.debug('new_release: %s', self.new_release)
if deluge.common.VersionSplit(self.new_release) > deluge.common.VersionSplit(deluge.common.get_version()):
- component.get("EventManager").emit(NewVersionAvailableEvent(self.new_release))
+ component.get('EventManager').emit(NewVersionAvailableEvent(self.new_release))
return self.new_release
return False
@@ -233,14 +233,14 @@ class Core(component.Component):
try:
filedump = base64.decodestring(filedump)
except Exception as ex:
- log.error("There was an error decoding the filedump string: %s", ex)
+ log.error('There was an error decoding the filedump string: %s', ex)
try:
d = self.torrentmanager.add(
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)
+ log.error('There was an error adding the torrent file %s: %s', filename, ex)
raise
else:
return d
@@ -301,11 +301,11 @@ class Core(component.Component):
:returns: a Deferred which returns the torrent_id as a str or None
"""
- log.info("Attempting to add url %s", url)
+ log.info('Attempting to add url %s', url)
def on_download_success(filename):
# We got the file, so add it to the session
- with open(filename, "rb") as _file:
+ with open(filename, 'rb') as _file:
data = _file.read()
try:
os.remove(filename)
@@ -315,7 +315,7 @@ class Core(component.Component):
def on_download_fail(failure):
# Log the error and pass the failure onto the client
- log.error("Failed to add torrent from url %s", url)
+ log.error('Failed to add torrent from url %s', url)
return failure
tmp_fd, tmp_file = tempfile.mkstemp(prefix='deluge_url.', suffix='.torrent')
@@ -338,7 +338,7 @@ class Core(component.Component):
:rtype: string
"""
- log.debug("Attempting to add by magnet uri: %s", uri)
+ log.debug('Attempting to add by magnet uri: %s', uri)
return self.torrentmanager.add(magnet=uri, options=options)
@@ -357,7 +357,7 @@ class Core(component.Component):
InvalidTorrentError: If the torrent ID does not exist in the session.
"""
- log.debug("Removing torrent %s from the core.", torrent_id)
+ log.debug('Removing torrent %s from the core.', torrent_id)
return self.torrentmanager.remove(torrent_id, remove_data)
@export
@@ -375,7 +375,7 @@ class Core(component.Component):
[("<torrent_id>", "Error removing torrent")]
"""
- log.info("Removing %d torrents from core.", len(torrent_ids))
+ log.info('Removing %d torrents from core.', len(torrent_ids))
def do_remove_torrents():
errors = []
@@ -387,7 +387,7 @@ class Core(component.Component):
# Save the session state
self.torrentmanager.save_state()
if errors:
- log.warn("Failed to remove %d of %d torrents.", len(errors), len(torrent_ids))
+ log.warn('Failed to remove %d of %d torrents.', len(errors), len(torrent_ids))
return errors
return task.deferLater(reactor, 0, do_remove_torrents)
@@ -426,55 +426,55 @@ class Core(component.Component):
status = self.session.get_cache_status()
cache = {}
for attr in dir(status):
- if attr.startswith("_"):
+ if attr.startswith('_'):
continue
cache[attr] = getattr(status, attr)
# Add in a couple ratios
try:
- cache["write_hit_ratio"] = (cache["blocks_written"] - cache["writes"]) / cache["blocks_written"]
+ cache['write_hit_ratio'] = (cache['blocks_written'] - cache['writes']) / cache['blocks_written']
except ZeroDivisionError:
- cache["write_hit_ratio"] = 0.0
+ cache['write_hit_ratio'] = 0.0
try:
- cache["read_hit_ratio"] = cache["blocks_read_hit"] / cache["blocks_read"]
+ cache['read_hit_ratio'] = cache['blocks_read_hit'] / cache['blocks_read']
except ZeroDivisionError:
- cache["read_hit_ratio"] = 0.0
+ cache['read_hit_ratio'] = 0.0
return cache
@export
def force_reannounce(self, torrent_ids):
- log.debug("Forcing reannouncment to: %s", torrent_ids)
+ log.debug('Forcing reannouncment to: %s', torrent_ids)
for torrent_id in torrent_ids:
self.torrentmanager[torrent_id].force_reannounce()
@export
def pause_torrent(self, torrent_ids):
- log.debug("Pausing: %s", torrent_ids)
+ log.debug('Pausing: %s', torrent_ids)
for torrent_id in torrent_ids:
if not self.torrentmanager[torrent_id].pause():
- log.warning("Error pausing torrent %s", torrent_id)
+ log.warning('Error pausing torrent %s', torrent_id)
@export
def connect_peer(self, torrent_id, ip, port):
- log.debug("adding peer %s to %s", ip, torrent_id)
+ log.debug('adding peer %s to %s', ip, torrent_id)
if not self.torrentmanager[torrent_id].connect_peer(ip, port):
- log.warning("Error adding peer %s:%s to %s", ip, port, torrent_id)
+ log.warning('Error adding peer %s:%s to %s', ip, port, torrent_id)
@export
def move_storage(self, torrent_ids, dest):
- log.debug("Moving storage %s to %s", torrent_ids, dest)
+ log.debug('Moving storage %s to %s', torrent_ids, dest)
for torrent_id in torrent_ids:
if not self.torrentmanager[torrent_id].move_storage(dest):
- log.warning("Error moving torrent %s to %s", torrent_id, dest)
+ log.warning('Error moving torrent %s to %s', torrent_id, dest)
@export
def pause_session(self):
"""Pause all torrents in the session"""
if not self.session.is_paused():
self.session.pause()
- component.get("EventManager").emit(SessionPausedEvent())
+ component.get('EventManager').emit(SessionPausedEvent())
@export
def resume_session(self):
@@ -483,11 +483,11 @@ class Core(component.Component):
self.session.resume()
for torrent_id in self.torrentmanager.torrents:
self.torrentmanager[torrent_id].update_state()
- component.get("EventManager").emit(SessionResumedEvent())
+ component.get('EventManager').emit(SessionResumedEvent())
@export
def resume_torrent(self, torrent_ids):
- log.debug("Resuming: %s", torrent_ids)
+ log.debug('Resuming: %s', torrent_ids)
for torrent_id in torrent_ids:
self.torrentmanager[torrent_id].resume()
@@ -566,7 +566,7 @@ class Core(component.Component):
if self.read_only_config_keys and key in self.read_only_config_keys:
continue
if isinstance(config[key], basestring):
- config[key] = config[key].encode("utf8")
+ config[key] = config[key].encode('utf8')
self.config[key] = config[key]
@export
@@ -578,7 +578,7 @@ class Core(component.Component):
def get_i2p_proxy(self):
"""Returns the active listen port"""
i2p_settings = self.session.i2p_proxy() # Deprecated, moved to proxy types
- i2p_dict = {"hostname": i2p_settings.hostname, "port": i2p_settings.port}
+ i2p_dict = {'hostname': i2p_settings.hostname, 'port': i2p_settings.port}
return i2p_dict
@export
@@ -586,13 +586,13 @@ class Core(component.Component):
"""Returns the active listen port"""
proxy_settings = self.session.proxy()
proxy_dict = {
- "type": int(proxy_settings.type),
- "hostname": proxy_settings.hostname,
- "username": proxy_settings.username,
- "password": proxy_settings.password,
- "port": proxy_settings.port,
- "proxy_hostnames": proxy_settings.proxy_hostnames,
- "proxy_peer_connections": proxy_settings.proxy_peer_connections
+ 'type': int(proxy_settings.type),
+ 'hostname': proxy_settings.hostname,
+ 'username': proxy_settings.username,
+ 'password': proxy_settings.password,
+ 'port': proxy_settings.port,
+ 'proxy_hostnames': proxy_settings.proxy_hostnames,
+ 'proxy_peer_connections': proxy_settings.proxy_peer_connections
}
return proxy_dict
@@ -733,7 +733,7 @@ class Core(component.Component):
def create_torrent(self, path, tracker, piece_length, comment, target,
webseeds, private, created_by, trackers, add_to_session):
- log.debug("creating torrent..")
+ log.debug('creating torrent..')
threading.Thread(target=self._create_torrent_thread,
args=(
path,
@@ -760,11 +760,11 @@ class Core(component.Component):
private=private,
created_by=created_by,
trackers=trackers)
- log.debug("torrent created!")
+ log.debug('torrent created!')
if add_to_session:
options = {}
- options["download_location"] = os.path.split(path)[0]
- with open(target, "rb") as _file:
+ options['download_location'] = os.path.split(path)[0]
+ with open(target, 'rb') as _file:
self.add_torrent_file(os.path.split(target)[1], _file.read(), options)
@export
@@ -777,20 +777,20 @@ class Core(component.Component):
try:
filedump = base64.decodestring(filedump)
except Exception as ex:
- log.error("There was an error decoding the filedump string!")
+ log.error('There was an error decoding the filedump string!')
log.exception(ex)
return
- with open(os.path.join(get_config_dir(), "plugins", filename), "wb") as _file:
+ with open(os.path.join(get_config_dir(), 'plugins', filename), 'wb') as _file:
_file.write(filedump)
- component.get("CorePluginManager").scan_for_plugins()
+ component.get('CorePluginManager').scan_for_plugins()
@export
def rescan_plugins(self):
"""
Rescans the plugin folders for new plugins
"""
- component.get("CorePluginManager").scan_for_plugins()
+ component.get('CorePluginManager').scan_for_plugins()
@export
def rename_files(self, torrent_id, filenames):
@@ -808,7 +808,7 @@ class Core(component.Component):
"""
if torrent_id not in self.torrentmanager.torrents:
- raise InvalidTorrentError("torrent_id is not in session")
+ raise InvalidTorrentError('torrent_id is not in session')
def rename():
self.torrentmanager[torrent_id].rename_files(filenames)
@@ -833,25 +833,25 @@ class Core(component.Component):
"""
if torrent_id not in self.torrentmanager.torrents:
- raise InvalidTorrentError("torrent_id is not in session")
+ raise InvalidTorrentError('torrent_id is not in session')
return self.torrentmanager[torrent_id].rename_folder(folder, new_folder)
@export
def queue_top(self, torrent_ids):
- log.debug("Attempting to queue %s to top", torrent_ids)
+ log.debug('Attempting to queue %s to top', torrent_ids)
# torrent_ids must be sorted in reverse before moving to preserve order
for torrent_id in sorted(torrent_ids, key=self.torrentmanager.get_queue_position, reverse=True):
try:
# If the queue method returns True, then we should emit a signal
if self.torrentmanager.queue_top(torrent_id):
- component.get("EventManager").emit(TorrentQueueChangedEvent())
+ component.get('EventManager').emit(TorrentQueueChangedEvent())
except KeyError:
- log.warning("torrent_id: %s does not exist in the queue", torrent_id)
+ log.warning('torrent_id: %s does not exist in the queue', torrent_id)
@export
def queue_up(self, torrent_ids):
- log.debug("Attempting to queue %s to up", torrent_ids)
+ log.debug('Attempting to queue %s to up', torrent_ids)
torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids)
torrent_moved = True
prev_queue_position = None
@@ -862,16 +862,16 @@ class Core(component.Component):
try:
torrent_moved = self.torrentmanager.queue_up(torrent_id)
except KeyError:
- log.warning("torrent_id: %s does not exist in the queue", torrent_id)
+ log.warning('torrent_id: %s does not exist in the queue', torrent_id)
# If the torrent moved, then we should emit a signal
if torrent_moved:
- component.get("EventManager").emit(TorrentQueueChangedEvent())
+ component.get('EventManager').emit(TorrentQueueChangedEvent())
else:
prev_queue_position = queue_position
@export
def queue_down(self, torrent_ids):
- log.debug("Attempting to queue %s to down", torrent_ids)
+ log.debug('Attempting to queue %s to down', torrent_ids)
torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids)
torrent_moved = True
prev_queue_position = None
@@ -882,24 +882,24 @@ class Core(component.Component):
try:
torrent_moved = self.torrentmanager.queue_down(torrent_id)
except KeyError:
- log.warning("torrent_id: %s does not exist in the queue", torrent_id)
+ log.warning('torrent_id: %s does not exist in the queue', torrent_id)
# If the torrent moved, then we should emit a signal
if torrent_moved:
- component.get("EventManager").emit(TorrentQueueChangedEvent())
+ component.get('EventManager').emit(TorrentQueueChangedEvent())
else:
prev_queue_position = queue_position
@export
def queue_bottom(self, torrent_ids):
- log.debug("Attempting to queue %s to bottom", torrent_ids)
+ log.debug('Attempting to queue %s to bottom', torrent_ids)
# torrent_ids must be sorted before moving to preserve order
for torrent_id in sorted(torrent_ids, key=self.torrentmanager.get_queue_position):
try:
# If the queue method returns True, then we should emit a signal
if self.torrentmanager.queue_bottom(torrent_id):
- component.get("EventManager").emit(TorrentQueueChangedEvent())
+ component.get('EventManager').emit(TorrentQueueChangedEvent())
except KeyError:
- log.warning("torrent_id: %s does not exist in the queue", torrent_id)
+ log.warning('torrent_id: %s does not exist in the queue', torrent_id)
@export
def glob(self, path):
@@ -914,14 +914,14 @@ class Core(component.Component):
:rtype: bool
"""
- d = getPage("http://deluge-torrent.org/test_port.php?port=%s" %
+ d = getPage('http://deluge-torrent.org/test_port.php?port=%s' %
self.get_listen_port(), timeout=30)
def on_get_page(result):
return bool(int(result))
def on_error(failure):
- log.warning("Error testing listen port: %s", failure)
+ log.warning('Error testing listen port: %s', failure)
d.addCallback(on_get_page)
d.addErrback(on_error)
@@ -943,7 +943,7 @@ class Core(component.Component):
"""
if not path:
- path = self.config["download_location"]
+ path = self.config['download_location']
try:
return deluge.common.free_space(path)
except InvalidPathError:
diff --git a/deluge/core/daemon.py b/deluge/core/daemon.py
index 21a011c4d..35aa8d834 100644
--- a/deluge/core/daemon.py
+++ b/deluge/core/daemon.py
@@ -43,7 +43,7 @@ def is_daemon_running(pid_file):
try:
with open(pid_file) as _file:
- pid, port = [int(x) for x in _file.readline().strip().split(";")]
+ pid, port = [int(x) for x in _file.readline().strip().split(';')]
except EnvironmentError:
return False
@@ -51,7 +51,7 @@ def is_daemon_running(pid_file):
# Ensure it's a deluged process by trying to open a socket to it's port.
_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
- _socket.connect(("127.0.0.1", port))
+ _socket.connect(('127.0.0.1', port))
except socket.error:
# Can't connect, so pid is not a deluged process.
return False
@@ -77,19 +77,19 @@ class Daemon(object):
altered by core.set_config() RPC method.
"""
self.standalone = standalone
- self.pid_file = get_config_dir("deluged.pid")
- log.info("Deluge daemon %s", get_version())
+ self.pid_file = get_config_dir('deluged.pid')
+ log.info('Deluge daemon %s', get_version())
if is_daemon_running(self.pid_file):
- raise DaemonRunningError("Deluge daemon already running with this config directory!")
+ raise DaemonRunningError('Deluge daemon already running with this config directory!')
# Twisted catches signals to terminate, so just have it call the shutdown method.
- reactor.addSystemEventTrigger("before", "shutdown", self._shutdown)
+ reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
# Catch some Windows specific signals
if windows_check():
def win_handler(ctrl_type):
"""Handle the Windows shutdown or close events."""
- log.debug("windows handler ctrl_type: %s", ctrl_type)
+ log.debug('windows handler ctrl_type: %s', ctrl_type)
if ctrl_type == CTRL_CLOSE_EVENT or ctrl_type == CTRL_SHUTDOWN_EVENT:
self._shutdown()
return 1
@@ -100,21 +100,21 @@ class Daemon(object):
read_only_config_keys=read_only_config_keys)
if port is None:
- port = self.core.config["daemon_port"]
+ port = self.core.config['daemon_port']
self.port = port
if interface and not is_ip(interface):
- log.error("Invalid UI interface (must be IP Address): %s", interface)
+ log.error('Invalid UI interface (must be IP Address): %s', interface)
interface = None
self.rpcserver = RPCServer(
port=port,
- allow_remote=self.core.config["allow_remote"],
+ allow_remote=self.core.config['allow_remote'],
listen=not standalone,
interface=interface
)
- log.debug("Listening to UI on: %s:%s and bittorrent on: %s", interface, port, listen_interface)
+ log.debug('Listening to UI on: %s:%s and bittorrent on: %s', interface, port, listen_interface)
def start(self):
# Register the daemon and the core RPCs
@@ -122,32 +122,32 @@ class Daemon(object):
self.rpcserver.register_object(self)
# Make sure we start the PreferencesManager first
- component.start("PreferencesManager")
+ component.start('PreferencesManager')
if not self.standalone:
- log.info("Deluge daemon starting...")
+ log.info('Deluge daemon starting...')
# Create pid file to track if deluged is running, also includes the port number.
pid = os.getpid()
- log.debug("Storing pid %s & port %s in: %s", pid, self.port, self.pid_file)
- with open(self.pid_file, "wb") as _file:
- _file.write("%s;%s\n" % (pid, self.port))
+ log.debug('Storing pid %s & port %s in: %s', pid, self.port, self.pid_file)
+ with open(self.pid_file, 'wb') as _file:
+ _file.write('%s;%s\n' % (pid, self.port))
component.start()
try:
reactor.run()
finally:
- log.debug("Remove pid file: %s", self.pid_file)
+ log.debug('Remove pid file: %s', self.pid_file)
os.remove(self.pid_file)
- log.info("Deluge daemon shutdown successfully")
+ log.info('Deluge daemon shutdown successfully')
@export()
def shutdown(self, *args, **kwargs):
- log.debug("Deluge daemon shutdown requested...")
+ log.debug('Deluge daemon shutdown requested...')
reactor.callLater(0, reactor.stop)
def _shutdown(self, *args, **kwargs):
- log.info("Deluge daemon shutting down, waiting for components to shutdown...")
+ log.info('Deluge daemon shutting down, waiting for components to shutdown...')
if not self.standalone:
return component.shutdown()
diff --git a/deluge/core/daemon_entry.py b/deluge/core/daemon_entry.py
index 60ca7a904..cccc50588 100644
--- a/deluge/core/daemon_entry.py
+++ b/deluge/core/daemon_entry.py
@@ -20,15 +20,15 @@ from deluge.ui.util import lang
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("--read-only-config-keys", metavar="<comma-separated-keys>", action="store",
- help=_("Config keys to be unmodified by `set_config` RPC"), type=str, default="")
+ 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('--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()
@@ -53,17 +53,17 @@ def start_daemon(skip_start=False):
# Check for any daemons running with this same config
from deluge.core.daemon import is_daemon_running
- pid_file = get_config_dir("deluged.pid")
+ pid_file = get_config_dir('deluged.pid')
if is_daemon_running(pid_file):
- print("Cannot run multiple daemons using the same config directory.\n"
- "If you believe this is an error, you can force a start by deleting: %s" % pid_file)
+ print('Cannot run multiple daemons using the same config directory.\n'
+ 'If you believe this is an error, you can force a start by deleting: %s' % pid_file)
sys.exit(1)
log = getLogger(__name__)
# If no logfile specified add logging to default location (as well as stdout)
if not options.logfile:
- options.logfile = get_config_dir("deluged.log")
+ options.logfile = get_config_dir('deluged.log')
file_handler = FileHandler(options.logfile)
log.addHandler(file_handler)
@@ -73,7 +73,7 @@ def start_daemon(skip_start=False):
daemon = Daemon(listen_interface=options.listen_interface,
interface=options.ui_interface,
port=options.port,
- read_only_config_keys=options.read_only_config_keys.split(","))
+ read_only_config_keys=options.read_only_config_keys.split(','))
if skip_start:
return daemon
else:
diff --git a/deluge/core/eventmanager.py b/deluge/core/eventmanager.py
index ef19783b1..7bfc7335b 100644
--- a/deluge/core/eventmanager.py
+++ b/deluge/core/eventmanager.py
@@ -16,7 +16,7 @@ log = logging.getLogger(__name__)
class EventManager(component.Component):
def __init__(self):
- component.Component.__init__(self, "EventManager")
+ component.Component.__init__(self, 'EventManager')
self.handlers = {}
def emit(self, event):
@@ -26,7 +26,7 @@ class EventManager(component.Component):
:param event: DelugeEvent
"""
# Emit the event to the interested clients
- component.get("RPCServer").emit_event(event)
+ component.get('RPCServer').emit_event(event)
# Call any handlers for the event
if event.name in self.handlers:
for handler in self.handlers[event.name]:
@@ -34,7 +34,7 @@ class EventManager(component.Component):
try:
handler(*event.args)
except Exception as ex:
- log.error("Event handler %s failed in %s with exception %s", event.name, handler, ex)
+ log.error('Event handler %s failed in %s with exception %s', event.name, handler, ex)
def register_event_handler(self, event, handler):
"""
diff --git a/deluge/core/filtermanager.py b/deluge/core/filtermanager.py
index e58c1b53f..2944c30d9 100644
--- a/deluge/core/filtermanager.py
+++ b/deluge/core/filtermanager.py
@@ -14,14 +14,14 @@ from deluge.common import TORRENT_STATE
log = logging.getLogger(__name__)
-STATE_SORT = ["All", "Active"] + TORRENT_STATE
+STATE_SORT = ['All', 'Active'] + TORRENT_STATE
# Special purpose filters:
def filter_keywords(torrent_ids, values):
# Cleanup
- keywords = ",".join([v.lower() for v in values])
- keywords = keywords.split(",")
+ keywords = ','.join([v.lower() for v in values])
+ keywords = keywords.split(',')
for keyword in keywords:
torrent_ids = filter_one_keyword(torrent_ids, keyword)
@@ -33,7 +33,7 @@ def filter_one_keyword(torrent_ids, keyword):
search torrent on keyword.
searches title,state,tracker-status,tracker,files
"""
- all_torrents = component.get("TorrentManager").torrents
+ all_torrents = component.get('TorrentManager').torrents
for torrent_id in torrent_ids:
torrent = all_torrents[torrent_id]
@@ -41,7 +41,7 @@ def filter_one_keyword(torrent_ids, keyword):
yield torrent_id
elif keyword in torrent.state.lower():
yield torrent_id
- elif torrent.trackers and keyword in torrent.trackers[0]["url"]:
+ elif torrent.trackers and keyword in torrent.trackers[0]['url']:
yield torrent_id
elif keyword in torrent_id:
yield torrent_id
@@ -50,13 +50,13 @@ def filter_one_keyword(torrent_ids, keyword):
yield torrent_id
else:
for t_file in torrent.get_files():
- if keyword in t_file["path"].lower():
+ if keyword in t_file['path'].lower():
yield torrent_id
break
def filter_by_name(torrent_ids, search_string):
- all_torrents = component.get("TorrentManager").torrents
+ all_torrents = component.get('TorrentManager').torrents
try:
search_string, match_case = search_string[0].split('::match')
except ValueError:
@@ -79,18 +79,18 @@ def filter_by_name(torrent_ids, search_string):
def tracker_error_filter(torrent_ids, values):
filtered_torrent_ids = []
- tm = component.get("TorrentManager")
+ tm = component.get('TorrentManager')
# If this is a tracker_host, then we need to filter on it
- if values[0] != "Error":
+ if values[0] != 'Error':
for torrent_id in torrent_ids:
- if values[0] == tm[torrent_id].get_status(["tracker_host"])["tracker_host"]:
+ if values[0] == tm[torrent_id].get_status(['tracker_host'])['tracker_host']:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
# Check torrent's tracker_status for 'Error:' and return those torrent_ids
for torrent_id in torrent_ids:
- if "Error:" in tm[torrent_id].get_status(["tracker_status"])["tracker_status"]:
+ if 'Error:' in tm[torrent_id].get_status(['tracker_status'])['tracker_status']:
filtered_torrent_ids.append(torrent_id)
return filtered_torrent_ids
@@ -100,26 +100,26 @@ class FilterManager(component.Component):
"""
def __init__(self, core):
- component.Component.__init__(self, "FilterManager")
- log.debug("FilterManager init..")
+ component.Component.__init__(self, 'FilterManager')
+ log.debug('FilterManager init..')
self.core = core
self.torrents = core.torrentmanager
self.registered_filters = {}
- self.register_filter("keyword", filter_keywords)
- self.register_filter("name", filter_by_name)
+ self.register_filter('keyword', filter_keywords)
+ self.register_filter('name', filter_by_name)
self.tree_fields = {}
- self.register_tree_field("state", self._init_state_tree)
+ self.register_tree_field('state', self._init_state_tree)
def _init_tracker_tree():
- return {"Error": 0}
- self.register_tree_field("tracker_host", _init_tracker_tree)
+ return {'Error': 0}
+ self.register_tree_field('tracker_host', _init_tracker_tree)
- self.register_filter("tracker_host", tracker_error_filter)
+ self.register_filter('tracker_host', tracker_error_filter)
def _init_users_tree():
- return {"": 0}
- self.register_tree_field("owner", _init_users_tree)
+ return {'': 0}
+ self.register_tree_field('owner', _init_users_tree)
def filter_torrent_ids(self, filter_dict):
"""
@@ -135,9 +135,9 @@ class FilterManager(component.Component):
filter_dict[key] = [value]
# Optimized filter for id
- if "id" in filter_dict:
- torrent_ids = list(filter_dict["id"])
- del filter_dict["id"]
+ if 'id' in filter_dict:
+ torrent_ids = list(filter_dict['id'])
+ del filter_dict['id']
else:
torrent_ids = self.torrents.get_torrent_list()
@@ -146,14 +146,14 @@ class FilterManager(component.Component):
return torrent_ids
# Special purpose, state=Active.
- if "state" in filter_dict:
+ if 'state' in filter_dict:
# We need to make sure this is a list for the logic below
- filter_dict["state"] = list(filter_dict["state"])
+ filter_dict['state'] = list(filter_dict['state'])
- if "state" in filter_dict and "Active" in filter_dict["state"]:
- filter_dict["state"].remove("Active")
- if not filter_dict["state"]:
- del filter_dict["state"]
+ if 'state' in filter_dict and 'Active' in filter_dict['state']:
+ filter_dict['state'].remove('Active')
+ if not filter_dict['state']:
+ del filter_dict['state']
torrent_ids = self.filter_state_active(torrent_ids)
if not filter_dict:
@@ -200,12 +200,12 @@ class FilterManager(component.Component):
value = status[field]
items[field][value] = items[field].get(value, 0) + 1
- if "tracker_host" in items:
- items["tracker_host"]["All"] = len(torrent_ids)
- items["tracker_host"]["Error"] = len(tracker_error_filter(torrent_ids, ("Error",)))
+ if 'tracker_host' in items:
+ items['tracker_host']['All'] = len(torrent_ids)
+ items['tracker_host']['Error'] = len(tracker_error_filter(torrent_ids, ('Error',)))
if not show_zero_hits:
- for cat in ["state", "owner", "tracker_host"]:
+ for cat in ['state', 'owner', 'tracker_host']:
if cat in tree_keys:
self._hide_state_items(items[cat])
@@ -214,17 +214,17 @@ class FilterManager(component.Component):
for field in tree_keys:
sorted_items[field] = sorted(items[field].iteritems())
- if "state" in tree_keys:
- sorted_items["state"].sort(self._sort_state_items)
+ if 'state' in tree_keys:
+ sorted_items['state'].sort(self._sort_state_items)
return sorted_items
def _init_state_tree(self):
init_state = {}
- init_state["All"] = len(self.torrents.get_torrent_list())
+ init_state['All'] = len(self.torrents.get_torrent_list())
for state in TORRENT_STATE:
init_state[state] = 0
- init_state["Active"] = len(self.filter_state_active(self.torrents.get_torrent_list()))
+ init_state['Active'] = len(self.filter_state_active(self.torrents.get_torrent_list()))
return init_state
def register_filter(self, filter_id, filter_func, filter_value=None):
@@ -242,8 +242,8 @@ class FilterManager(component.Component):
def filter_state_active(self, torrent_ids):
for torrent_id in list(torrent_ids):
- status = self.torrents[torrent_id].get_status(["download_payload_rate", "upload_payload_rate"])
- if status["download_payload_rate"] or status["upload_payload_rate"]:
+ status = self.torrents[torrent_id].get_status(['download_payload_rate', 'upload_payload_rate'])
+ if status['download_payload_rate'] or status['upload_payload_rate']:
pass
else:
torrent_ids.remove(torrent_id)
@@ -252,7 +252,7 @@ class FilterManager(component.Component):
def _hide_state_items(self, state_items):
"""For hide(show)-zero hits"""
for (value, count) in state_items.items():
- if value != "All" and count == 0:
+ if value != 'All' and count == 0:
del state_items[value]
def _sort_state_items(self, x, y):
diff --git a/deluge/core/pluginmanager.py b/deluge/core/pluginmanager.py
index 9c1e530dc..dacb7af70 100644
--- a/deluge/core/pluginmanager.py
+++ b/deluge/core/pluginmanager.py
@@ -26,13 +26,13 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
functions to access parts of the core."""
def __init__(self, core):
- component.Component.__init__(self, "CorePluginManager")
+ component.Component.__init__(self, 'CorePluginManager')
self.status_fields = {}
# 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
@@ -47,7 +47,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
def update_plugins(self):
for plugin in self.plugins:
- if hasattr(self.plugins[plugin], "update"):
+ if hasattr(self.plugins[plugin], 'update'):
try:
self.plugins[plugin].update()
except Exception as ex:
@@ -60,7 +60,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
def on_enable_plugin(result):
if result is True and name in self.plugins:
- component.get("EventManager").emit(PluginEnabledEvent(name))
+ component.get('EventManager').emit(PluginEnabledEvent(name))
return result
d.addBoth(on_enable_plugin)
@@ -73,7 +73,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
def on_disable_plugin(result):
if name not in self.plugins:
- component.get("EventManager").emit(PluginDisabledEvent(name))
+ component.get('EventManager').emit(PluginDisabledEvent(name))
return result
d.addBoth(on_disable_plugin)
return d
@@ -93,13 +93,13 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
def register_status_field(self, field, function):
"""Register a new status field. This can be used in the same way the
client requests other status information from core."""
- log.debug("Registering status field %s with PluginManager", field)
+ log.debug('Registering status field %s with PluginManager', field)
self.status_fields[field] = function
def deregister_status_field(self, field):
"""Deregisters a status field"""
- log.debug("Deregistering status field %s with PluginManager", field)
+ log.debug('Deregistering status field %s with PluginManager', field)
try:
del self.status_fields[field]
except Exception:
- log.warning("Unable to deregister status field %s", field)
+ log.warning('Unable to deregister status field %s', field)
diff --git a/deluge/core/preferencesmanager.py b/deluge/core/preferencesmanager.py
index 4bd2368e2..619f9d89d 100644
--- a/deluge/core/preferencesmanager.py
+++ b/deluge/core/preferencesmanager.py
@@ -29,119 +29,119 @@ except ImportError:
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "send_info": False,
- "info_sent": 0.0,
- "daemon_port": 58846,
- "allow_remote": False,
- "pre_allocate_storage": False,
- "download_location": deluge.common.get_default_download_dir(),
- "listen_ports": [6881, 6891],
- "listen_interface": "",
- "random_port": True,
- "listen_random_port": None,
- "listen_use_sys_port": False,
- "listen_reuse_port": True,
- "outgoing_ports": [0, 0],
- "random_outgoing_ports": True,
- "copy_torrent_file": False,
- "del_copy_torrent_file": False,
- "torrentfiles_location": deluge.common.get_default_download_dir(),
- "plugins_location": os.path.join(deluge.configmanager.get_config_dir(), "plugins"),
- "prioritize_first_last_pieces": False,
- "sequential_download": False,
- "dht": True,
- "upnp": True,
- "natpmp": True,
- "utpex": True,
- "lsd": True,
- "enc_in_policy": 1,
- "enc_out_policy": 1,
- "enc_level": 2,
- "max_connections_global": 200,
- "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
+ 'send_info': False,
+ 'info_sent': 0.0,
+ 'daemon_port': 58846,
+ 'allow_remote': False,
+ 'pre_allocate_storage': False,
+ 'download_location': deluge.common.get_default_download_dir(),
+ 'listen_ports': [6881, 6891],
+ 'listen_interface': '',
+ 'random_port': True,
+ 'listen_random_port': None,
+ 'listen_use_sys_port': False,
+ 'listen_reuse_port': True,
+ 'outgoing_ports': [0, 0],
+ 'random_outgoing_ports': True,
+ 'copy_torrent_file': False,
+ 'del_copy_torrent_file': False,
+ 'torrentfiles_location': deluge.common.get_default_download_dir(),
+ 'plugins_location': os.path.join(deluge.configmanager.get_config_dir(), 'plugins'),
+ 'prioritize_first_last_pieces': False,
+ 'sequential_download': False,
+ 'dht': True,
+ 'upnp': True,
+ 'natpmp': True,
+ 'utpex': True,
+ 'lsd': True,
+ 'enc_in_policy': 1,
+ 'enc_out_policy': 1,
+ 'enc_level': 2,
+ 'max_connections_global': 200,
+ '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_connections_per_second": 20,
- "ignore_limits_on_local_network": True,
- "max_connections_per_torrent": -1,
- "max_upload_slots_per_torrent": -1,
- "max_upload_speed_per_torrent": -1,
- "max_download_speed_per_torrent": -1,
- "enabled_plugins": [],
- "add_paused": False,
- "max_active_seeding": 5,
- "max_active_downloading": 3,
- "max_active_limit": 8,
- "dont_count_slow_torrents": False,
- "queue_new_to_top": False,
- "stop_seed_at_ratio": False,
- "remove_seed_at_ratio": False,
- "stop_seed_ratio": 2.00,
- "share_ratio_limit": 2.00,
- "seed_time_ratio_limit": 7.00,
- "seed_time_limit": 180,
- "auto_managed": True,
- "move_completed": False,
- "move_completed_path": deluge.common.get_default_download_dir(),
- "move_completed_paths_list": [],
- "download_location_paths_list": [],
- "path_chooser_show_chooser_button_on_localhost": True,
- "path_chooser_auto_complete_enabled": True,
- "path_chooser_accelerator_string": "Tab",
- "path_chooser_max_popup_rows": 20,
- "path_chooser_show_hidden_files": False,
- "new_release_check": True,
- "proxy": {
- "type": 0,
- "hostname": "",
- "username": "",
- "password": "",
- "port": 8080,
- "proxy_hostnames": True,
- "proxy_peer_connections": True,
+ 'max_connections_per_second': 20,
+ 'ignore_limits_on_local_network': True,
+ 'max_connections_per_torrent': -1,
+ 'max_upload_slots_per_torrent': -1,
+ 'max_upload_speed_per_torrent': -1,
+ 'max_download_speed_per_torrent': -1,
+ 'enabled_plugins': [],
+ 'add_paused': False,
+ 'max_active_seeding': 5,
+ 'max_active_downloading': 3,
+ 'max_active_limit': 8,
+ 'dont_count_slow_torrents': False,
+ 'queue_new_to_top': False,
+ 'stop_seed_at_ratio': False,
+ 'remove_seed_at_ratio': False,
+ 'stop_seed_ratio': 2.00,
+ 'share_ratio_limit': 2.00,
+ 'seed_time_ratio_limit': 7.00,
+ 'seed_time_limit': 180,
+ 'auto_managed': True,
+ 'move_completed': False,
+ 'move_completed_path': deluge.common.get_default_download_dir(),
+ 'move_completed_paths_list': [],
+ 'download_location_paths_list': [],
+ 'path_chooser_show_chooser_button_on_localhost': True,
+ 'path_chooser_auto_complete_enabled': True,
+ 'path_chooser_accelerator_string': 'Tab',
+ 'path_chooser_max_popup_rows': 20,
+ 'path_chooser_show_hidden_files': False,
+ 'new_release_check': True,
+ 'proxy': {
+ 'type': 0,
+ 'hostname': '',
+ 'username': '',
+ 'password': '',
+ 'port': 8080,
+ 'proxy_hostnames': True,
+ 'proxy_peer_connections': True,
},
- "i2p_proxy": {
- "hostname": "",
- "port": 0
+ 'i2p_proxy': {
+ 'hostname': '',
+ 'port': 0
},
- "peer_tos": "0x00",
- "rate_limit_ip_overhead": True,
- "anonymous_mode": False,
- "geoip_db_location": "/usr/share/GeoIP/GeoIP.dat",
- "cache_size": 512,
- "cache_expiry": 60,
- "auto_manage_prefer_seeds": False,
- "shared": False,
- "super_seeding": False,
- "priority": 0
+ 'peer_tos': '0x00',
+ 'rate_limit_ip_overhead': True,
+ 'anonymous_mode': False,
+ 'geoip_db_location': '/usr/share/GeoIP/GeoIP.dat',
+ 'cache_size': 512,
+ 'cache_expiry': 60,
+ 'auto_manage_prefer_seeds': False,
+ 'shared': False,
+ 'super_seeding': False,
+ 'priority': 0
}
class PreferencesManager(component.Component):
def __init__(self):
- component.Component.__init__(self, "PreferencesManager")
- self.config = deluge.configmanager.ConfigManager("core.conf", DEFAULT_PREFS)
- if "proxies" in self.config:
+ component.Component.__init__(self, 'PreferencesManager')
+ self.config = deluge.configmanager.ConfigManager('core.conf', DEFAULT_PREFS)
+ if 'proxies' in self.config:
log.warning("Updating config file for proxy, using 'peer' values to fill new 'proxy' setting")
- self.config["proxy"].update(self.config["proxies"]['peer'])
- log.warning("New proxy config is: %s", self.config["proxy"])
- del self.config["proxies"]
+ self.config['proxy'].update(self.config['proxies']['peer'])
+ log.warning('New proxy config is: %s', self.config['proxy'])
+ del self.config['proxies']
- self.core = component.get("Core")
- self.session = component.get("Core").session
+ self.core = component.get('Core')
+ self.session = component.get('Core').session
self.new_release_timer = None
def start(self):
# Setup listen port followed by dht to ensure both use same port.
self.__set_listen_on()
- self._on_set_dht("dht", self.config["dht"])
+ self._on_set_dht('dht', self.config['dht'])
# Set the initial preferences on start-up
for key in DEFAULT_PREFS:
# Listen port and dht already setup in correct order so skip running again.
- if key in ("dht", "random_port") or key.startswith("listen_"):
+ if key in ('dht', 'random_port') or key.startswith('listen_'):
continue
self.do_config_set_func(key, self.config[key])
@@ -153,10 +153,10 @@ class PreferencesManager(component.Component):
# Config set functions
def do_config_set_func(self, key, value):
- on_set_func = getattr(self, "_on_set_" + key, None)
+ on_set_func = getattr(self, '_on_set_' + key, None)
if on_set_func:
if log.isEnabledFor(logging.DEBUG):
- log.debug("Config key: %s set to %s..", key, value)
+ log.debug('Config key: %s set to %s..', key, value)
on_set_func(key, value)
def session_set_setting(self, key, value):
@@ -164,27 +164,27 @@ class PreferencesManager(component.Component):
self.session.apply_settings({key: value})
except AttributeError:
# Deprecated in libtorrent 1.1
- if key in ("enable_lsd", "enable_upnp", "enable_natpmp", "enable_dht"):
- start_stop = key.replace("enable", "start") if value else key.replace("enable", "stop")
+ if key in ('enable_lsd', 'enable_upnp', 'enable_natpmp', 'enable_dht'):
+ start_stop = key.replace('enable', 'start') if value else key.replace('enable', 'stop')
getattr(self.session, start_stop)()
- elif key == "dht_bootstrap_nodes":
- self.session.add_dht_router("router.bittorrent.com", 6881)
- self.session.add_dht_router("router.utorrent.com", 6881)
- self.session.add_dht_router("router.bitcomet.com", 6881)
+ elif key == 'dht_bootstrap_nodes':
+ self.session.add_dht_router('router.bittorrent.com', 6881)
+ self.session.add_dht_router('router.utorrent.com', 6881)
+ self.session.add_dht_router('router.bitcomet.com', 6881)
else:
self.session.set_settings({key: value})
def _on_config_value_change(self, key, value):
- if self.get_state() == "Started":
+ if self.get_state() == 'Started':
self.do_config_set_func(key, value)
- component.get("EventManager").emit(ConfigValueChangedEvent(key, value))
+ component.get('EventManager').emit(ConfigValueChangedEvent(key, value))
def _on_set_torrentfiles_location(self, key, value):
- if self.config["copy_torrent_file"]:
+ if self.config['copy_torrent_file']:
try:
os.makedirs(value)
except OSError as ex:
- log.debug("Unable to make directory: %s", ex)
+ log.debug('Unable to make directory: %s', ex)
def _on_set_listen_ports(self, key, value):
self.__set_listen_on()
@@ -197,35 +197,35 @@ class PreferencesManager(component.Component):
def __set_listen_on(self):
""" Set the ports and interface address to listen for incoming connections on."""
- if self.config["random_port"]:
- if not self.config["listen_random_port"]:
- self.config["listen_random_port"] = random.randrange(49152, 65525)
- listen_ports = [self.config["listen_random_port"]] * 2 # use single port range
+ if self.config['random_port']:
+ if not self.config['listen_random_port']:
+ self.config['listen_random_port'] = random.randrange(49152, 65525)
+ listen_ports = [self.config['listen_random_port']] * 2 # use single port range
else:
- self.config["listen_random_port"] = None
- listen_ports = self.config["listen_ports"]
+ self.config['listen_random_port'] = None
+ listen_ports = self.config['listen_ports']
- interface = str(self.config["listen_interface"].strip())
+ interface = str(self.config['listen_interface'].strip())
- log.debug("Listen Interface: %s, Ports: %s with use_sys_port: %s",
- interface, listen_ports, self.config["listen_use_sys_port"])
+ log.debug('Listen Interface: %s, Ports: %s with use_sys_port: %s',
+ interface, listen_ports, self.config['listen_use_sys_port'])
try:
- interfaces = ["%s:%s" % (interface, port) for port in range(listen_ports[0], listen_ports[1]+1)]
- self.session.apply_setting({"listen_system_port_fallback", self.config["listen_use_sys_port"]})
- self.session.apply_setting({"listen_interfaces", interfaces})
+ interfaces = ['%s:%s' % (interface, port) for port in range(listen_ports[0], listen_ports[1]+1)]
+ self.session.apply_setting({'listen_system_port_fallback', self.config['listen_use_sys_port']})
+ self.session.apply_setting({'listen_interfaces', interfaces})
except AttributeError:
# Deprecated in libtorrent 1.1
# If a single port range then always enable re-use port flag.
- reuse_port = True if listen_ports[0] == listen_ports[1] else self.config["listen_reuse_port"]
+ reuse_port = True if listen_ports[0] == listen_ports[1] else self.config['listen_reuse_port']
flags = ((lt.listen_on_flags_t.listen_no_system_port
- if not self.config["listen_use_sys_port"] else 0) |
+ if not self.config['listen_use_sys_port'] else 0) |
(lt.listen_on_flags_t.listen_reuse_address
if reuse_port else 0))
try:
self.session.listen_on(listen_ports[0], listen_ports[1], interface, flags)
except RuntimeError as ex:
- if ex.message == "Invalid Argument":
- log.error("Error setting listen interface (must be IP Address): %s %s-%s",
+ if ex.message == 'Invalid Argument':
+ log.error('Error setting listen interface (must be IP Address): %s %s-%s',
interface, listen_ports[0], listen_ports[1])
def _on_set_outgoing_ports(self, key, value):
@@ -235,34 +235,34 @@ class PreferencesManager(component.Component):
self.__set_outgoing_ports()
def __set_outgoing_ports(self):
- ports = [0, 0] if self.config["random_outgoing_ports"] else self.config["outgoing_ports"]
- log.debug("Outgoing ports set to %s", ports)
- self.session_set_setting("outgoing_ports", (ports[0], ports[1]))
+ ports = [0, 0] if self.config['random_outgoing_ports'] else self.config['outgoing_ports']
+ log.debug('Outgoing ports set to %s', ports)
+ self.session_set_setting('outgoing_ports', (ports[0], ports[1]))
def _on_set_peer_tos(self, key, value):
try:
- self.session_set_setting("peer_tos", chr(int(value, 16)))
+ self.session_set_setting('peer_tos', chr(int(value, 16)))
except ValueError as ex:
- log.debug("Invalid tos byte: %s", ex)
+ log.debug('Invalid tos byte: %s', ex)
return
def _on_set_dht(self, key, value):
- dht_bootstraps = "router.bittorrent.com:6881,router.utorrent.com:6881,router.bitcomet.com:6881"
- self.session_set_setting("dht_bootstrap_nodes", dht_bootstraps)
- self.session_set_setting("enable_dht", value)
+ dht_bootstraps = 'router.bittorrent.com:6881,router.utorrent.com:6881,router.bitcomet.com:6881'
+ self.session_set_setting('dht_bootstrap_nodes', dht_bootstraps)
+ self.session_set_setting('enable_dht', value)
def _on_set_upnp(self, key, value):
- self.session_set_setting("enable_upnp", value)
+ self.session_set_setting('enable_upnp', value)
def _on_set_natpmp(self, key, value):
- self.session_set_setting("enable_natpmp", value)
+ self.session_set_setting('enable_natpmp', value)
def _on_set_lsd(self, key, value):
- self.session_set_setting("enable_lsd", value)
+ self.session_set_setting('enable_lsd', value)
def _on_set_utpex(self, key, value):
if value:
- self.session.add_extension("ut_pex")
+ self.session.add_extension('ut_pex')
def _on_set_enc_in_policy(self, key, value):
self._on_set_encryption(key, value)
@@ -277,76 +277,76 @@ 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}
try:
- self.session.apply_setting("out_enc_policy", lt.enc_policy(self.config["enc_out_policy"]))
- self.session.apply_setting("in_enc_policy", lt.enc_policy(self.config["enc_in_policy"]))
- self.session.apply_setting("allowed_enc_level", lt.enc_level(pe_enc_level[self.config["enc_level"]]))
- self.session.apply_setting("prefer_rc4", True)
+ self.session.apply_setting('out_enc_policy', lt.enc_policy(self.config['enc_out_policy']))
+ self.session.apply_setting('in_enc_policy', lt.enc_policy(self.config['enc_in_policy']))
+ self.session.apply_setting('allowed_enc_level', lt.enc_level(pe_enc_level[self.config['enc_level']]))
+ self.session.apply_setting('prefer_rc4', True)
except AttributeError:
# Deprecated in libtorrent 1.1
pe_settings = lt.pe_settings()
- pe_settings.out_enc_policy = lt.enc_policy(self.config["enc_out_policy"])
- pe_settings.in_enc_policy = lt.enc_policy(self.config["enc_in_policy"])
- pe_settings.allowed_enc_level = lt.enc_level(pe_enc_level[self.config["enc_level"]])
+ pe_settings.out_enc_policy = lt.enc_policy(self.config['enc_out_policy'])
+ pe_settings.in_enc_policy = lt.enc_policy(self.config['enc_in_policy'])
+ pe_settings.allowed_enc_level = lt.enc_level(pe_enc_level[self.config['enc_level']])
pe_settings.prefer_rc4 = True
self.session.set_pe_settings(pe_settings)
pe_sess_settings = self.session.get_pe_settings()
- log.debug("encryption settings:\n\t\t\tout_policy: %s\n\t\t\
- in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s",
+ log.debug('encryption settings:\n\t\t\tout_policy: %s\n\t\t\
+ in_policy: %s\n\t\t\tlevel: %s\n\t\t\tprefer_rc4: %s',
pe_sess_settings.out_enc_policy,
pe_sess_settings.in_enc_policy,
pe_sess_settings.allowed_enc_level,
pe_sess_settings.prefer_rc4)
def _on_set_max_connections_global(self, key, value):
- self.session_set_setting("connections_limit", value)
+ self.session_set_setting('connections_limit', value)
def _on_set_max_upload_speed(self, key, value):
# We need to convert Kb/s to B/s
value = -1 if value < 0 else int(value * 1024)
- self.session_set_setting("upload_rate_limit", value)
+ self.session_set_setting('upload_rate_limit', value)
def _on_set_max_download_speed(self, key, value):
# We need to convert Kb/s to B/s
value = -1 if value < 0 else int(value * 1024)
- self.session_set_setting("download_rate_limit", value)
+ self.session_set_setting('download_rate_limit', value)
def _on_set_max_upload_slots_global(self, key, value):
- self.session_set_setting("unchoke_slots_limit", value)
+ self.session_set_setting('unchoke_slots_limit', value)
def _on_set_max_half_open_connections(self, key, value):
- self.session_set_setting("half_open_limit", value)
+ self.session_set_setting('half_open_limit', value)
def _on_set_max_connections_per_second(self, key, value):
- self.session_set_setting("connection_speed", value)
+ self.session_set_setting('connection_speed', value)
def _on_set_ignore_limits_on_local_network(self, key, value):
- self.session_set_setting("ignore_limits_on_local_network", value)
+ self.session_set_setting('ignore_limits_on_local_network', value)
def _on_set_share_ratio_limit(self, key, value):
- self.session_set_setting("share_ratio_limit", value)
+ self.session_set_setting('share_ratio_limit', value)
def _on_set_seed_time_ratio_limit(self, key, value):
- self.session_set_setting("seed_time_ratio_limit", value)
+ self.session_set_setting('seed_time_ratio_limit', value)
def _on_set_seed_time_limit(self, key, value):
# This value is stored in minutes in deluge, but libtorrent wants seconds
- self.session_set_setting("seed_time_limit", int(value * 60))
+ self.session_set_setting('seed_time_limit', int(value * 60))
def _on_set_max_active_downloading(self, key, value):
- self.session_set_setting("active_downloads", value)
+ self.session_set_setting('active_downloads', value)
def _on_set_max_active_seeding(self, key, value):
- self.session_set_setting("active_seeds", value)
+ self.session_set_setting('active_seeds', value)
def _on_set_max_active_limit(self, key, value):
- self.session_set_setting("active_limit", value)
+ self.session_set_setting('active_limit', value)
def _on_set_dont_count_slow_torrents(self, key, value):
- self.session_set_setting("dont_count_slow_torrents", value)
+ self.session_set_setting('dont_count_slow_torrents', value)
def _on_set_send_info(self, key, value):
"""sends anonymous stats home"""
- log.debug("Sending anonymous stats..")
+ log.debug('Sending anonymous stats..')
class SendInfoThread(threading.Thread):
def __init__(self, config):
@@ -357,33 +357,33 @@ class PreferencesManager(component.Component):
import time
now = time.time()
# check if we've done this within the last week or never
- if (now - self.config["info_sent"]) >= (60 * 60 * 24 * 7):
+ if (now - self.config['info_sent']) >= (60 * 60 * 24 * 7):
from urllib import quote_plus
from urllib2 import urlopen
import platform
try:
- url = "http://deluge-torrent.org/stats_get.php?processor=" + \
- platform.machine() + "&python=" + platform.python_version() \
- + "&deluge=" + deluge.common.get_version() \
- + "&os=" + platform.system() \
- + "&plugins=" + quote_plus(":".join(self.config["enabled_plugins"]))
+ url = 'http://deluge-torrent.org/stats_get.php?processor=' + \
+ platform.machine() + '&python=' + platform.python_version() \
+ + '&deluge=' + deluge.common.get_version() \
+ + '&os=' + platform.system() \
+ + '&plugins=' + quote_plus(':'.join(self.config['enabled_plugins']))
urlopen(url)
except IOError as ex:
- log.debug("Network error while trying to send info: %s", ex)
+ log.debug('Network error while trying to send info: %s', ex)
else:
- self.config["info_sent"] = now
+ self.config['info_sent'] = now
if value:
SendInfoThread(self.config).start()
def _on_set_new_release_check(self, key, value):
if value:
- log.debug("Checking for new release..")
+ log.debug('Checking for new release..')
threading.Thread(target=self.core.get_new_release).start()
if self.new_release_timer and self.new_release_timer.running:
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:
@@ -391,46 +391,46 @@ class PreferencesManager(component.Component):
def _on_set_proxy(self, key, value):
try:
- if key == "i2p_proxy":
- self.session.apply_settings("proxy_type", lt.proxy_type("i2p_proxy"))
- self.session.apply_settings("i2p_hostname", value["hostname"])
- self.session.apply_settings("i2p_port", value["port"])
+ if key == 'i2p_proxy':
+ self.session.apply_settings('proxy_type', lt.proxy_type('i2p_proxy'))
+ self.session.apply_settings('i2p_hostname', value['hostname'])
+ self.session.apply_settings('i2p_port', value['port'])
else:
- self.session.apply_settings("proxy_type", lt.proxy_type(value["type"]))
- self.session.apply_settings("proxy_hostname", value["hostname"])
- self.session.apply_settings("proxy_port", value["port"])
- self.session.apply_settings("proxy_username", value["username"])
- self.session.apply_settings("proxy_password", value["password"])
- self.session.apply_settings("proxy_hostnames", value["proxy_hostnames"])
- self.session.apply_settings("proxy_peer_connections", value["proxy_peer_connections"])
- self.session.apply_settings("proxy_tracker_connections", value["proxy_tracker_connections"])
+ self.session.apply_settings('proxy_type', lt.proxy_type(value['type']))
+ self.session.apply_settings('proxy_hostname', value['hostname'])
+ self.session.apply_settings('proxy_port', value['port'])
+ self.session.apply_settings('proxy_username', value['username'])
+ self.session.apply_settings('proxy_password', value['password'])
+ self.session.apply_settings('proxy_hostnames', value['proxy_hostnames'])
+ self.session.apply_settings('proxy_peer_connections', value['proxy_peer_connections'])
+ self.session.apply_settings('proxy_tracker_connections', value['proxy_tracker_connections'])
except AttributeError:
proxy_settings = lt.proxy_settings()
- proxy_settings.hostname = value["hostname"]
- proxy_settings.port = value["port"]
- if key == "i2p_proxy":
+ proxy_settings.hostname = value['hostname']
+ proxy_settings.port = value['port']
+ if key == 'i2p_proxy':
try:
self.session.set_i2p_proxy(proxy_settings)
except RuntimeError as ex:
- log.error("Unable to set I2P Proxy: %s", ex)
+ log.error('Unable to set I2P Proxy: %s', ex)
else:
- proxy_settings.type = lt.proxy_type(value["type"])
- proxy_settings.username = value["username"]
- proxy_settings.password = value["password"]
- proxy_settings.hostname = value["hostname"]
- proxy_settings.port = value["port"]
- proxy_settings.proxy_hostnames = value["proxy_hostnames"]
- proxy_settings.proxy_peer_connections = value["proxy_peer_connections"]
+ proxy_settings.type = lt.proxy_type(value['type'])
+ proxy_settings.username = value['username']
+ proxy_settings.password = value['password']
+ proxy_settings.hostname = value['hostname']
+ proxy_settings.port = value['port']
+ proxy_settings.proxy_hostnames = value['proxy_hostnames']
+ proxy_settings.proxy_peer_connections = value['proxy_peer_connections']
self.session.set_proxy(proxy_settings)
def _on_set_i2p_proxy(self, key, value):
self._on_set_proxy(key, value)
def _on_set_rate_limit_ip_overhead(self, key, value):
- self.session_set_setting("rate_limit_ip_overhead", value)
+ self.session_set_setting('rate_limit_ip_overhead', value)
def _on_set_anonymous_mode(self, key, value):
- self.session_set_setting("anonymous_mode", value)
+ self.session_set_setting('anonymous_mode', value)
def _on_set_geoip_db_location(self, key, geoipdb_path):
# Load the GeoIP DB for country look-ups if available
@@ -438,15 +438,15 @@ class PreferencesManager(component.Component):
try:
self.core.geoip_instance = GeoIP.open(geoipdb_path, GeoIP.GEOIP_STANDARD)
except AttributeError:
- log.warning("GeoIP Unavailable")
+ log.warning('GeoIP Unavailable')
else:
- log.warning("Unable to find GeoIP database file: %s", geoipdb_path)
+ log.warning('Unable to find GeoIP database file: %s', geoipdb_path)
def _on_set_cache_size(self, key, value):
- self.session_set_setting("cache_size", value)
+ self.session_set_setting('cache_size', value)
def _on_set_cache_expiry(self, key, value):
- self.session_set_setting("cache_expiry", value)
+ self.session_set_setting('cache_expiry', value)
def _on_auto_manage_prefer_seeds(self, key, value):
- self.session_set_setting("auto_manage_prefer_seeds", value)
+ self.session_set_setting('auto_manage_prefer_seeds', value)
diff --git a/deluge/core/rpcserver.py b/deluge/core/rpcserver.py
index 8fd6df54c..dacfdfeb3 100644
--- a/deluge/core/rpcserver.py
+++ b/deluge/core/rpcserver.py
@@ -49,7 +49,7 @@ def export(auth_level=AUTH_LEVEL_DEFAULT):
func._rpcserver_export = True
func._rpcserver_auth_level = auth_level
doc = func.__doc__
- func.__doc__ = "**RPC Exported Function** (*Auth Level: %s*)\n\n" % auth_level
+ func.__doc__ = '**RPC Exported Function** (*Auth Level: %s*)\n\n' % auth_level
if doc:
func.__doc__ += doc
@@ -75,16 +75,16 @@ def format_request(call):
"""
try:
- s = call[1] + "("
+ s = call[1] + '('
if call[2]:
- s += ", ".join([str(x) for x in call[2]])
+ s += ', '.join([str(x) for x in call[2]])
if call[3]:
if call[2]:
- s += ", "
- s += ", ".join([key + "=" + str(value) for key, value in call[3].items()])
- s += ")"
+ s += ', '
+ s += ', '.join([key + '=' + str(value) for key, value in call[3].items()])
+ s += ')'
except UnicodeEncodeError:
- return "UnicodeEncodeError, call: %s" % call
+ return 'UnicodeEncodeError, call: %s' % call
else:
return s
@@ -97,11 +97,11 @@ class ServerContextFactory(object):
This loads the servers cert/private key SSL files for use with the
SSL transport.
"""
- ssl_dir = deluge.configmanager.get_config_dir("ssl")
+ ssl_dir = deluge.configmanager.get_config_dir('ssl')
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
- ctx.use_certificate_file(os.path.join(ssl_dir, "daemon.cert"))
- ctx.use_privatekey_file(os.path.join(ssl_dir, "daemon.pkey"))
+ ctx.use_certificate_file(os.path.join(ssl_dir, 'daemon.cert'))
+ ctx.use_privatekey_file(os.path.join(ssl_dir, 'daemon.pkey'))
return ctx
@@ -118,17 +118,17 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
"""
if not isinstance(request, tuple):
- log.debug("Received invalid message: type is not tuple")
+ log.debug('Received invalid message: type is not tuple')
return
if len(request) < 1:
- log.debug("Received invalid message: there are no items")
+ log.debug('Received invalid message: there are no items')
return
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)
@@ -145,7 +145,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
try:
self.transfer_message(data)
except Exception as ex:
- log.warn("Error occurred when sending message: %s.", ex)
+ log.warn('Error occurred when sending message: %s.', ex)
log.exception(ex)
raise
@@ -154,7 +154,7 @@ 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",
+ 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] = AUTH_LEVEL_NONE
@@ -175,9 +175,9 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
if self.transport.sessionno in self.factory.interested_events:
del self.factory.interested_events[self.transport.sessionno]
- if self.factory.state == "running":
- component.get("EventManager").emit(ClientDisconnectedEvent(self.factory.session_id))
- log.info("Deluge client disconnected: %s", reason.value)
+ if self.factory.state == 'running':
+ component.get('EventManager').emit(ClientDisconnectedEvent(self.factory.session_id))
+ log.info('Deluge client disconnected: %s', reason.value)
def valid_session(self):
return self.transport.sessionno in self.factory.authorized_sessions
@@ -215,29 +215,29 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
))
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(exceptionValue), exceptionType.__name__, formated_tb)
except WrappedException:
send_error()
except Exception as ex:
- log.error("An exception occurred while sending RPC_ERROR to client: %s", ex)
+ log.error('An exception occurred while sending RPC_ERROR to client: %s', ex)
- if method == "daemon.info":
+ if method == 'daemon.info':
# This is a special case and used in the initial connection process
self.sendData((RPC_RESPONSE, request_id, deluge.common.get_version()))
return
- elif method == "daemon.login":
+ elif method == 'daemon.login':
# This is a special case and used in the initial connection process
# We need to authenticate the user here
- log.debug("RPC dispatch daemon.login")
+ log.debug('RPC dispatch daemon.login')
try:
client_version = kwargs.pop('client_version', None)
if client_version is None:
raise IncompatibleClient(deluge.common.get_version())
- ret = component.get("AuthManager").authorize(*args, **kwargs)
+ ret = component.get('AuthManager').authorize(*args, **kwargs)
if ret:
self.factory.authorized_sessions[self.transport.sessionno] = (ret, args[0])
self.factory.session_protocols[self.transport.sessionno] = self
@@ -255,8 +255,8 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
if not self.valid_session():
return
- if method == "daemon.set_event_interest":
- log.debug("RPC dispatch daemon.set_event_interest")
+ if method == 'daemon.set_event_interest':
+ log.debug('RPC dispatch daemon.set_event_interest')
# This special case is to allow clients to set which events they are
# interested in receiving.
# We are expecting a sequence from the client.
@@ -278,13 +278,13 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
send_error()
return
- log.debug("RPC dispatch %s", method)
+ log.debug('RPC dispatch %s', method)
try:
method_auth_requirement = self.factory.methods[method]._rpcserver_auth_level
auth_level = self.factory.authorized_sessions[self.transport.sessionno][0]
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!",
+ 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
@@ -296,7 +296,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
# Don't bother printing out DelugeErrors, because they are just
# for the client
if not isinstance(ex, DelugeError):
- log.exception("Exception calling RPC request: %s", ex)
+ log.exception('Exception calling RPC request: %s', ex)
else:
# Check if the return value is a deferred, since we'll need to
# wait for it to fire before sending the RPC_RESPONSE
@@ -336,13 +336,13 @@ class RPCServer(component.Component):
:type listen: bool
"""
- def __init__(self, port=58846, interface="", allow_remote=False, listen=True):
- component.Component.__init__(self, "RPCServer")
+ def __init__(self, port=58846, interface='', allow_remote=False, listen=True):
+ component.Component.__init__(self, 'RPCServer')
self.factory = Factory()
self.factory.protocol = DelugeRPCProtocol
self.factory.session_id = -1
- self.factory.state = "running"
+ self.factory.state = 'running'
# Holds the registered methods
self.factory.methods = {}
@@ -358,14 +358,14 @@ class RPCServer(component.Component):
return
if allow_remote:
- hostname = ""
+ hostname = ''
else:
- hostname = "localhost"
+ hostname = 'localhost'
if interface:
hostname = interface
- log.info("Starting DelugeRPC server %s:%s", hostname, port)
+ log.info('Starting DelugeRPC server %s:%s', hostname, port)
# Check for SSL keys and generate some if needed
check_ssl_keys()
@@ -373,7 +373,7 @@ class RPCServer(component.Component):
try:
reactor.listenSSL(port, self.factory, ServerContextFactory(), interface=hostname)
except Exception as ex:
- log.info("Daemon already running or port not available.")
+ log.info('Daemon already running or port not available.')
log.error(ex)
raise
@@ -391,11 +391,11 @@ class RPCServer(component.Component):
name = obj.__class__.__name__.lower()
for d in dir(obj):
- if d[0] == "_":
+ if d[0] == '_':
continue
if getattr(getattr(obj, d), '_rpcserver_export', False):
- log.debug("Registering method: %s", name + "." + d)
- self.factory.methods[name + "." + d] = getattr(obj, d)
+ log.debug('Registering method: %s', name + '.' + d)
+ self.factory.methods[name + '.' + d] = getattr(obj, d)
def deregister_object(self, obj):
"""
@@ -450,13 +450,13 @@ class RPCServer(component.Component):
"""
if not self.listen:
- return "localclient"
+ return 'localclient'
session_id = self.get_session_id()
if session_id > -1 and session_id in self.factory.authorized_sessions:
return self.factory.authorized_sessions[session_id][1]
else:
# No connections made yet
- return ""
+ return ''
def get_session_auth_level(self):
"""
@@ -498,11 +498,11 @@ class RPCServer(component.Component):
:param event: the event to emit
:type event: :class:`deluge.event.DelugeEvent`
"""
- log.debug("intevents: %s", self.factory.interested_events)
+ log.debug('intevents: %s', self.factory.interested_events)
# Find sessions interested in this event
for session_id, interest in self.factory.interested_events.items():
if event.name in interest:
- log.debug("Emit Event: %s %s", event.name, event.args)
+ 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)
@@ -532,20 +532,20 @@ class RPCServer(component.Component):
self.factory.session_protocols[session_id].sendData((RPC_EVENT, event.name, event.args))
def stop(self):
- self.factory.state = "stopping"
+ self.factory.state = 'stopping'
def check_ssl_keys():
"""
Check for SSL cert/key and create them if necessary
"""
- ssl_dir = deluge.configmanager.get_config_dir("ssl")
+ ssl_dir = deluge.configmanager.get_config_dir('ssl')
if not os.path.exists(ssl_dir):
# The ssl folder doesn't exist so we need to create it
os.makedirs(ssl_dir)
generate_ssl_keys()
else:
- for f in ("daemon.pkey", "daemon.cert"):
+ for f in ('daemon.pkey', 'daemon.cert'):
if not os.path.exists(os.path.join(ssl_dir, f)):
generate_ssl_keys()
break
@@ -555,7 +555,7 @@ def generate_ssl_keys():
"""
This method generates a new SSL key/cert.
"""
- digest = "sha256"
+ digest = 'sha256'
# Generate key pair
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)
@@ -563,7 +563,7 @@ def generate_ssl_keys():
# Generate cert request
req = crypto.X509Req()
subj = req.get_subject()
- setattr(subj, "CN", "Deluge Daemon")
+ setattr(subj, 'CN', 'Deluge Daemon')
req.set_pubkey(pkey)
req.sign(pkey, digest)
@@ -578,11 +578,11 @@ def generate_ssl_keys():
cert.sign(pkey, digest)
# Write out files
- ssl_dir = deluge.configmanager.get_config_dir("ssl")
- with open(os.path.join(ssl_dir, "daemon.pkey"), "w") as _file:
+ ssl_dir = deluge.configmanager.get_config_dir('ssl')
+ with open(os.path.join(ssl_dir, 'daemon.pkey'), 'w') as _file:
_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
- with open(os.path.join(ssl_dir, "daemon.cert"), "w") as _file:
+ with open(os.path.join(ssl_dir, 'daemon.cert'), 'w') as _file:
_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
# Make the files only readable by this user
- for f in ("daemon.pkey", "daemon.cert"):
+ for f in ('daemon.pkey', 'daemon.cert'):
os.chmod(os.path.join(ssl_dir, f), stat.S_IREAD | stat.S_IWRITE)
diff --git a/deluge/core/torrent.py b/deluge/core/torrent.py
index f796a0d3c..5b5ceab80 100644
--- a/deluge/core/torrent.py
+++ b/deluge/core/torrent.py
@@ -34,14 +34,14 @@ from deluge.event import TorrentFolderRenamedEvent, TorrentStateChangedEvent, To
log = logging.getLogger(__name__)
LT_TORRENT_STATE_MAP = {
- "queued_for_checking": "Checking",
- "checking_files": "Checking",
- "downloading_metadata": "Downloading",
- "downloading": "Downloading",
- "finished": "Seeding",
- "seeding": "Seeding",
- "allocating": "Allocating",
- "checking_resume_data": "Checking"
+ 'queued_for_checking': 'Checking',
+ 'checking_files': 'Checking',
+ 'downloading_metadata': 'Downloading',
+ 'downloading': 'Downloading',
+ 'finished': 'Seeding',
+ 'seeding': 'Seeding',
+ 'allocating': 'Allocating',
+ 'checking_resume_data': 'Checking'
}
@@ -57,19 +57,19 @@ def sanitize_filepath(filepath, folder=False):
def clean_filename(filename):
"""Strips whitespace and discards dotted filenames"""
filename = filename.strip()
- if filename.replace(".", "") == "":
- return ""
+ if filename.replace('.', '') == '':
+ return ''
return filename
- if "\\" in filepath or "/" in filepath:
- folderpath = filepath.replace("\\", "/").split("/")
+ if '\\' in filepath or '/' in filepath:
+ folderpath = filepath.replace('\\', '/').split('/')
folderpath = [clean_filename(x) for x in folderpath]
- newfilepath = "/".join([path for path in folderpath if path])
+ newfilepath = '/'.join([path for path in folderpath if path])
else:
newfilepath = clean_filename(filepath)
if folder is True:
- newfilepath += "/"
+ newfilepath += '/'
return newfilepath
@@ -95,10 +95,10 @@ def convert_lt_files(files):
filelist = []
for index, _file in enumerate(files):
filelist.append({
- "index": index,
- "path": _file.path.decode("utf8").replace("\\", "/"),
- "size": _file.size,
- "offset": _file.offset
+ 'index': index,
+ 'path': _file.path.decode('utf8').replace('\\', '/'),
+ 'size': _file.size,
+ 'offset': _file.offset
})
return filelist
@@ -139,34 +139,34 @@ class TorrentOptions(dict):
"""
def __init__(self):
super(TorrentOptions, self).__init__()
- config = ConfigManager("core.conf").config
+ config = ConfigManager('core.conf').config
options_conf_map = {
- "max_connections": "max_connections_per_torrent",
- "max_upload_slots": "max_upload_slots_per_torrent",
- "max_upload_speed": "max_upload_speed_per_torrent",
- "max_download_speed": "max_download_speed_per_torrent",
- "prioritize_first_last_pieces": "prioritize_first_last_pieces",
- "sequential_download": "sequential_download",
- "pre_allocate_storage": "pre_allocate_storage",
- "download_location": "download_location",
- "auto_managed": "auto_managed",
- "stop_at_ratio": "stop_seed_at_ratio",
- "stop_ratio": "stop_seed_ratio",
- "remove_at_ratio": "remove_seed_at_ratio",
- "move_completed": "move_completed",
- "move_completed_path": "move_completed_path",
- "add_paused": "add_paused",
- "shared": "shared",
- "super_seeding": "super_seeding",
- "priority": "priority",
+ 'max_connections': 'max_connections_per_torrent',
+ 'max_upload_slots': 'max_upload_slots_per_torrent',
+ 'max_upload_speed': 'max_upload_speed_per_torrent',
+ 'max_download_speed': 'max_download_speed_per_torrent',
+ 'prioritize_first_last_pieces': 'prioritize_first_last_pieces',
+ 'sequential_download': 'sequential_download',
+ 'pre_allocate_storage': 'pre_allocate_storage',
+ 'download_location': 'download_location',
+ 'auto_managed': 'auto_managed',
+ 'stop_at_ratio': 'stop_seed_at_ratio',
+ 'stop_ratio': 'stop_seed_ratio',
+ 'remove_at_ratio': 'remove_seed_at_ratio',
+ 'move_completed': 'move_completed',
+ 'move_completed_path': 'move_completed_path',
+ 'add_paused': 'add_paused',
+ 'shared': 'shared',
+ 'super_seeding': 'super_seeding',
+ 'priority': 'priority',
}
for opt_k, conf_k in options_conf_map.iteritems():
self[opt_k] = config[conf_k]
- self["file_priorities"] = []
- self["mapped_files"] = {}
- self["owner"] = ""
- self["name"] = ""
- self["seed_mode"] = False
+ self['file_priorities'] = []
+ self['mapped_files'] = {}
+ self['owner'] = ''
+ self['name'] = ''
+ self['seed_mode'] = False
class TorrentError(object):
@@ -216,11 +216,11 @@ class Torrent(object):
def __init__(self, handle, options, state=None, filename=None, magnet=None):
self.torrent_id = str(handle.info_hash())
if log.isEnabledFor(logging.DEBUG):
- log.debug("Creating torrent object %s", self.torrent_id)
+ log.debug('Creating torrent object %s', self.torrent_id)
# Get the core config
- self.config = ConfigManager("core.conf")
- self.rpcserver = component.get("RPCServer")
+ self.config = ConfigManager('core.conf')
+ self.rpcserver = component.get('RPCServer')
self.handle = handle
self.handle.resolve_countries(True)
@@ -253,7 +253,7 @@ class Torrent(object):
self.state = None
self.moving_storage = False
self.moving_storage_dest_path = None
- self.tracker_status = ""
+ self.tracker_status = ''
self.tracker_host = None
self.forcing_recheck = False
self.forcing_recheck_paused = False
@@ -267,13 +267,13 @@ class Torrent(object):
self.update_state()
if log.isEnabledFor(logging.DEBUG):
- log.debug("Torrent object created.")
+ log.debug('Torrent object created.')
def on_metadata_received(self):
"""Process the metadata received alert for this torrent"""
self.has_metadata = True
self.torrent_info = self.handle.get_torrent_info()
- if self.options["prioritize_first_last_pieces"]:
+ if self.options['prioritize_first_last_pieces']:
self.set_prioritize_first_last_pieces(True)
self.write_torrentfile()
@@ -286,13 +286,13 @@ class Torrent(object):
"""
# set_prioritize_first_last is called by set_file_priorities so only run if not in options
skip_func = []
- if "file_priorities" in options:
- self.options["prioritize_first_last_pieces"] = options["prioritize_first_last_pieces"]
- skip_func.append("prioritize_first_last_pieces")
+ if 'file_priorities' in options:
+ self.options['prioritize_first_last_pieces'] = options['prioritize_first_last_pieces']
+ skip_func.append('prioritize_first_last_pieces')
for key, value in options.items():
if key in self.options:
- options_set_func = getattr(self, "set_" + key, None)
+ options_set_func = getattr(self, 'set_' + key, None)
if options_set_func and key not in skip_func:
options_set_func(value)
else:
@@ -323,7 +323,7 @@ class Torrent(object):
elif max_connections == 1:
max_connections = 2
- self.options["max_connections"] = max_connections
+ self.options['max_connections'] = max_connections
self.handle.set_max_connections(max_connections)
def set_max_upload_slots(self, max_slots):
@@ -332,7 +332,7 @@ class Torrent(object):
Args:
max_slots (int): Maximum upload slots
"""
- self.options["max_upload_slots"] = max_slots
+ self.options['max_upload_slots'] = max_slots
self.handle.set_max_uploads(max_slots)
def set_max_upload_speed(self, m_up_speed):
@@ -341,7 +341,7 @@ class Torrent(object):
Args:
m_up_speed (float): Maximum upload speed in KiB/s.
"""
- self.options["max_upload_speed"] = m_up_speed
+ self.options['max_upload_speed'] = m_up_speed
if m_up_speed < 0:
value = -1
else:
@@ -354,7 +354,7 @@ class Torrent(object):
Args:
m_up_speed (float): Maximum download speed in KiB/s.
"""
- self.options["max_download_speed"] = m_down_speed
+ self.options['max_download_speed'] = m_down_speed
if m_down_speed < 0:
value = -1
else:
@@ -374,11 +374,11 @@ class Torrent(object):
Returns:
tuple of lists: The prioritized pieces and the torrent piece priorities.
"""
- self.options["prioritize_first_last_pieces"] = prioritize
+ self.options['prioritize_first_last_pieces'] = prioritize
if not prioritize:
# If we are turning off this option, call set_file_priorities to
# reset all the piece priorities
- self.set_file_priorities(self.options["file_priorities"])
+ self.set_file_priorities(self.options['file_priorities'])
return None, None
if not self.has_metadata:
return None, None
@@ -414,7 +414,7 @@ class Torrent(object):
Args:
set_sequencial (bool): Enable sequencial downloading.
"""
- self.options["sequential_download"] = set_sequencial
+ self.options['sequential_download'] = set_sequencial
self.handle.set_sequential_download(set_sequencial)
def set_auto_managed(self, auto_managed):
@@ -423,7 +423,7 @@ class Torrent(object):
Args:
auto_managed (bool): Enable auto managed.
"""
- self.options["auto_managed"] = auto_managed
+ self.options['auto_managed'] = auto_managed
if not (self.status.paused and not self.status.auto_managed):
self.handle.auto_managed(auto_managed)
self.update_state()
@@ -435,10 +435,10 @@ class Torrent(object):
super_seeding (bool): Enable super seeding.
"""
if self.status.is_seeding:
- self.options["super_seeding"] = super_seeding
+ self.options['super_seeding'] = super_seeding
self.handle.super_seeding(super_seeding)
else:
- self.options["super_seeding"] = False
+ self.options['super_seeding'] = False
def set_stop_ratio(self, stop_ratio):
"""The seeding ratio to stop (or remove) the torrent at.
@@ -446,7 +446,7 @@ class Torrent(object):
Args:
stop_ratio (float): The seeding ratio.
"""
- self.options["stop_ratio"] = stop_ratio
+ self.options['stop_ratio'] = stop_ratio
def set_stop_at_ratio(self, stop_at_ratio):
"""Stop the torrent when it has reached stop_ratio.
@@ -454,7 +454,7 @@ class Torrent(object):
Args:
stop_at_ratio (bool): Stop the torrent.
"""
- self.options["stop_at_ratio"] = stop_at_ratio
+ self.options['stop_at_ratio'] = stop_at_ratio
def set_remove_at_ratio(self, remove_at_ratio):
"""Remove the torrent when it has reached the stop_ratio.
@@ -462,7 +462,7 @@ class Torrent(object):
Args:
remove_at_ratio (bool): Remove the torrent.
"""
- self.options["remove_at_ratio"] = remove_at_ratio
+ self.options['remove_at_ratio'] = remove_at_ratio
def set_move_completed(self, move_completed):
"""Set whether to move the torrent when downloading has finished.
@@ -471,7 +471,7 @@ class Torrent(object):
move_completed (bool): Move the torrent.
"""
- self.options["move_completed"] = move_completed
+ self.options['move_completed'] = move_completed
def set_move_completed_path(self, move_completed_path):
"""Set the path to move torrent to when downloading has finished.
@@ -479,7 +479,7 @@ class Torrent(object):
Args:
move_completed_path (str): The move path.
"""
- self.options["move_completed_path"] = move_completed_path
+ self.options['move_completed_path'] = move_completed_path
def set_file_priorities(self, file_priorities):
"""Sets the file priotities.
@@ -490,8 +490,8 @@ class Torrent(object):
if not self.has_metadata:
return
if len(file_priorities) != self.torrent_info.num_files():
- log.debug("file_priorities len != num_files")
- self.options["file_priorities"] = self.handle.file_priorities()
+ log.debug('file_priorities len != num_files')
+ self.options['file_priorities'] = self.handle.file_priorities()
return
if log.isEnabledFor(logging.DEBUG):
@@ -499,10 +499,10 @@ class Torrent(object):
self.handle.prioritize_files(file_priorities)
- if 0 in self.options["file_priorities"]:
+ if 0 in self.options['file_priorities']:
# We have previously marked a file 'Do Not Download'
# Check to see if we have changed any 0's to >0 and change state accordingly
- for index, priority in enumerate(self.options["file_priorities"]):
+ for index, priority in enumerate(self.options['file_priorities']):
if priority == 0 and file_priorities[index] > 0:
# We have a changed 'Do Not Download' to a download priority
self.is_finished = False
@@ -511,11 +511,11 @@ class Torrent(object):
# In case values in file_priorities were faulty (old state?)
# we make sure the stored options are in sync
- self.options["file_priorities"] = self.handle.file_priorities()
+ self.options['file_priorities'] = self.handle.file_priorities()
# Set the first/last priorities if needed
- if self.options["prioritize_first_last_pieces"]:
- self.set_prioritize_first_last_pieces(self.options["prioritize_first_last_pieces"])
+ if self.options['prioritize_first_last_pieces']:
+ self.set_prioritize_first_last_pieces(self.options['prioritize_first_last_pieces'])
def set_save_path(self, download_location):
"""Deprecated, use set_download_location."""
@@ -523,7 +523,7 @@ class Torrent(object):
def set_download_location(self, download_location):
"""The location for downloading torrent data."""
- self.options["download_location"] = download_location
+ self.options['download_location'] = download_location
def set_priority(self, priority):
"""Sets the bandwidth priority of this torrent.
@@ -537,10 +537,10 @@ class Torrent(object):
ValueError: If value of priority is not in range [0..255]
"""
if 0 <= priority <= 255:
- self.options["priority"] = priority
+ self.options['priority'] = priority
return self.handle.set_priority(priority)
else:
- raise ValueError("Torrent priority, %s, is invalid, should be [0..255]", priority)
+ raise ValueError('Torrent priority, %s, is invalid, should be [0..255]', priority)
def set_owner(self, account):
"""Sets the owner of this torrent.
@@ -548,7 +548,7 @@ class Torrent(object):
Only a user with admin level auth can change this value.
"""
if self.rpcserver.get_session_auth_level() == AUTH_LEVEL_ADMIN:
- self.options["owner"] = account
+ self.options['owner'] = account
# End Options methods #
@@ -564,21 +564,21 @@ class Torrent(object):
return
if log.isEnabledFor(logging.DEBUG):
- log.debug("Setting trackers for %s: %s", self.torrent_id, trackers)
+ log.debug('Setting trackers for %s: %s', self.torrent_id, trackers)
tracker_list = []
for tracker in trackers:
- new_entry = lt.announce_entry(str(tracker["url"]))
- new_entry.tier = tracker["tier"]
+ new_entry = lt.announce_entry(str(tracker['url']))
+ new_entry.tier = tracker['tier']
tracker_list.append(new_entry)
self.handle.replace_trackers(tracker_list)
# Print out the trackers
if log.isEnabledFor(logging.DEBUG):
- log.debug("Trackers set for %s:", self.torrent_id)
+ log.debug('Trackers set for %s:', self.torrent_id)
for tracker in self.handle.trackers():
- log.debug(" [tier %s]: %s", tracker["tier"], tracker["url"])
+ log.debug(' [tier %s]: %s', tracker['tier'], tracker['url'])
# Set the tracker list in the torrent object
self.trackers = trackers
if len(trackers) > 0:
@@ -601,26 +601,26 @@ class Torrent(object):
if self.tracker_status != status:
self.tracker_status = status
- component.get("EventManager").emit(TorrentTrackerStatusEvent(self.torrent_id, self.tracker_status))
+ component.get('EventManager').emit(TorrentTrackerStatusEvent(self.torrent_id, self.tracker_status))
def merge_trackers(self, torrent_info):
"""Merges new trackers in torrent_info into torrent"""
- log.info("Adding any new trackers to torrent (%s) already in session...", self.torrent_id)
+ log.info('Adding any new trackers to torrent (%s) already in session...', self.torrent_id)
if not torrent_info:
return
# Don't merge trackers if either torrent has private flag set.
- if torrent_info.priv() or self.get_status(["private"])["private"]:
- log.info("Adding trackers aborted: Torrent has private flag set.")
+ if torrent_info.priv() or self.get_status(['private'])['private']:
+ log.info('Adding trackers aborted: Torrent has private flag set.')
else:
for tracker in torrent_info.trackers():
- self.handle.add_tracker({"url": tracker.url, "tier": tracker.tier})
+ self.handle.add_tracker({'url': tracker.url, 'tier': tracker.tier})
# Update torrent.trackers from libtorrent handle.
self.set_trackers()
def update_state(self):
"""Updates the state, based on libtorrent's torrent state"""
status = self.handle.status()
- session_paused = component.get("Core").session.is_paused()
+ session_paused = component.get('Core').session.is_paused()
old_state = self.state
self.set_status_message()
try:
@@ -630,30 +630,30 @@ class Torrent(object):
status_error = status.error
if self.forced_error:
- self.state = "Error"
+ self.state = 'Error'
self.set_status_message(self.forced_error.error_message)
elif status_error:
- self.state = "Error"
+ self.state = 'Error'
# auto-manage status will be reverted upon resuming.
self.handle.auto_managed(False)
self.set_status_message(decode_string(status_error))
elif self.moving_storage:
- self.state = "Moving"
+ self.state = 'Moving'
elif not session_paused and status.paused and status.auto_managed:
- self.state = "Queued"
+ self.state = 'Queued'
elif session_paused or status.paused:
- self.state = "Paused"
+ self.state = 'Paused'
else:
self.state = LT_TORRENT_STATE_MAP.get(str(status.state), str(status.state))
if self.state != old_state:
- component.get("EventManager").emit(TorrentStateChangedEvent(self.torrent_id, self.state))
+ 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)
+ '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)
+ log.debug('Torrent Error state message: %s', self.forced_error.error_message)
def set_status_message(self, message=None):
"""Sets the torrent status message.
@@ -665,7 +665,7 @@ class Torrent(object):
"""
if not message:
- message = "OK"
+ message = 'OK'
self.statusmsg = message
def force_error_state(self, message, restart_to_resume=True):
@@ -690,12 +690,12 @@ class Torrent(object):
return
if self.forced_error.restart_to_resume:
- log.error("Restart deluge to clear this torrent error")
+ log.error('Restart deluge to clear this torrent error')
- if not self.forced_error.was_paused and self.options["auto_managed"]:
+ if not self.forced_error.was_paused and self.options['auto_managed']:
self.handle.auto_managed(True)
self.forced_error = None
- self.set_status_message("OK")
+ self.set_status_message('OK')
if update_state:
self.update_state()
@@ -708,9 +708,9 @@ class Torrent(object):
"""
status = self.status
eta = 0
- if self.is_finished and self.options["stop_at_ratio"] and status.upload_payload_rate:
+ 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"]) -
+ 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
@@ -788,20 +788,20 @@ class Torrent(object):
client = decode_string(peer.client)
try:
- country = component.get("Core").geoip_instance.country_code_by_addr(peer.ip[0])
+ country = component.get('Core').geoip_instance.country_code_by_addr(peer.ip[0])
except AttributeError:
- country = ""
+ country = ''
else:
- country = "".join([char if char.isalpha() else " " for char in country])
+ country = ''.join([char if char.isalpha() else ' ' for char in country])
ret.append({
- "client": client,
- "country": country,
- "down_speed": peer.payload_down_speed,
- "ip": "%s:%s" % (peer.ip[0], peer.ip[1]),
- "progress": peer.progress,
- "seed": peer.flags & peer.seed,
- "up_speed": peer.payload_up_speed,
+ 'client': client,
+ 'country': country,
+ 'down_speed': peer.payload_down_speed,
+ 'ip': '%s:%s' % (peer.ip[0], peer.ip[1]),
+ 'progress': peer.progress,
+ 'seed': peer.flags & peer.seed,
+ 'up_speed': peer.payload_up_speed,
})
return ret
@@ -838,12 +838,12 @@ class Torrent(object):
tracker = self.status.current_tracker
if not tracker and self.trackers:
- tracker = self.trackers[0]["url"]
+ tracker = self.trackers[0]['url']
if tracker:
- url = urlparse(tracker.replace("udp://", "http://"))
- if hasattr(url, "hostname"):
- host = (url.hostname or "DHT")
+ url = urlparse(tracker.replace('udp://', 'http://'))
+ if hasattr(url, 'hostname'):
+ host = (url.hostname or 'DHT')
# Check if hostname is an IP address and just return it if that's the case
try:
socket.inet_aton(host)
@@ -853,15 +853,15 @@ class Torrent(object):
# This is an IP address because an exception wasn't raised
return url.hostname
- parts = host.split(".")
+ parts = host.split('.')
if len(parts) > 2:
- if parts[-2] in ("co", "com", "net", "org") or parts[-1] == "uk":
- host = ".".join(parts[-3:])
+ if parts[-2] in ('co', 'com', 'net', 'org') or parts[-1] == 'uk':
+ host = '.'.join(parts[-3:])
else:
- host = ".".join(parts[-2:])
+ host = '.'.join(parts[-2:])
self.tracker_host = host
return host
- return ""
+ return ''
def get_magnet_uri(self):
"""Returns a magnet uri for this torrent"""
@@ -878,14 +878,14 @@ class Torrent(object):
str: the name of the torrent.
"""
- if not self.options["name"]:
+ if not self.options['name']:
handle_name = self.handle.name()
if handle_name:
name = decode_string(handle_name)
else:
name = self.torrent_id
else:
- name = self.options["name"]
+ name = self.options['name']
return name
@@ -902,12 +902,12 @@ class Torrent(object):
files = [os.path.join(path, f) for f in files]
return sum(os.stat(f).st_size for f in files if os.path.exists(f))
- if self.state == "Error":
+ if self.state == 'Error':
progress = 100.0
elif self.moving_storage:
# Check if torrent has downloaded any data yet.
if self.status.total_done:
- torrent_files = [f["path"] for f in self.get_files()]
+ torrent_files = [f['path'] for f in self.get_files()]
dest_path_size = get_size(torrent_files, self.moving_storage_dest_path)
progress = dest_path_size / self.status.total_done * 100
else:
@@ -972,81 +972,81 @@ class Torrent(object):
def _create_status_funcs(self):
"""Creates the functions for getting torrent status"""
self.status_funcs = {
- "active_time": lambda: self.status.active_time,
- "seeding_time": lambda: self.status.seeding_time,
- "finished_time": lambda: self.status.finished_time,
- "all_time_download": lambda: self.status.all_time_download,
- "storage_mode": lambda: self.status.storage_mode.name.split("_")[2], # sparse or allocate
- "distributed_copies": lambda: max(0.0, self.status.distributed_copies),
- "download_payload_rate": lambda: self.status.download_payload_rate,
- "file_priorities": lambda: self.options["file_priorities"],
- "hash": lambda: self.torrent_id,
- "is_auto_managed": lambda: self.options["auto_managed"],
- "is_finished": lambda: self.is_finished,
- "max_connections": lambda: self.options["max_connections"],
- "max_download_speed": lambda: self.options["max_download_speed"],
- "max_upload_slots": lambda: self.options["max_upload_slots"],
- "max_upload_speed": lambda: self.options["max_upload_speed"],
- "message": lambda: self.statusmsg,
- "move_on_completed_path": lambda: self.options["move_completed_path"], # Depr, use move_completed_path
- "move_on_completed": lambda: self.options["move_completed"], # Deprecated, use move_completed
- "move_completed_path": lambda: self.options["move_completed_path"],
- "move_completed": lambda: self.options["move_completed"],
- "next_announce": lambda: self.status.next_announce.seconds,
- "num_peers": lambda: self.status.num_peers - self.status.num_seeds,
- "num_seeds": lambda: self.status.num_seeds,
- "owner": lambda: self.options["owner"],
- "paused": lambda: self.status.paused,
- "prioritize_first_last": lambda: self.options["prioritize_first_last_pieces"],
- "sequential_download": lambda: self.options["sequential_download"],
- "progress": self.get_progress,
- "shared": lambda: self.options["shared"],
- "remove_at_ratio": lambda: self.options["remove_at_ratio"],
- "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
+ 'active_time': lambda: self.status.active_time,
+ 'seeding_time': lambda: self.status.seeding_time,
+ 'finished_time': lambda: self.status.finished_time,
+ 'all_time_download': lambda: self.status.all_time_download,
+ 'storage_mode': lambda: self.status.storage_mode.name.split('_')[2], # sparse or allocate
+ 'distributed_copies': lambda: max(0.0, self.status.distributed_copies),
+ 'download_payload_rate': lambda: self.status.download_payload_rate,
+ 'file_priorities': lambda: self.options['file_priorities'],
+ 'hash': lambda: self.torrent_id,
+ 'is_auto_managed': lambda: self.options['auto_managed'],
+ 'is_finished': lambda: self.is_finished,
+ 'max_connections': lambda: self.options['max_connections'],
+ 'max_download_speed': lambda: self.options['max_download_speed'],
+ 'max_upload_slots': lambda: self.options['max_upload_slots'],
+ 'max_upload_speed': lambda: self.options['max_upload_speed'],
+ 'message': lambda: self.statusmsg,
+ 'move_on_completed_path': lambda: self.options['move_completed_path'], # Depr, use move_completed_path
+ 'move_on_completed': lambda: self.options['move_completed'], # Deprecated, use move_completed
+ 'move_completed_path': lambda: self.options['move_completed_path'],
+ 'move_completed': lambda: self.options['move_completed'],
+ 'next_announce': lambda: self.status.next_announce.seconds,
+ 'num_peers': lambda: self.status.num_peers - self.status.num_seeds,
+ 'num_seeds': lambda: self.status.num_seeds,
+ 'owner': lambda: self.options['owner'],
+ 'paused': lambda: self.status.paused,
+ 'prioritize_first_last': lambda: self.options['prioritize_first_last_pieces'],
+ 'sequential_download': lambda: self.options['sequential_download'],
+ 'progress': self.get_progress,
+ 'shared': lambda: self.options['shared'],
+ 'remove_at_ratio': lambda: self.options['remove_at_ratio'],
+ '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),
- "seed_rank": lambda: self.status.seed_rank,
- "state": lambda: self.state,
- "stop_at_ratio": lambda: self.options["stop_at_ratio"],
- "stop_ratio": lambda: self.options["stop_ratio"],
- "time_added": lambda: self.status.added_time,
- "total_done": lambda: self.status.total_done,
- "total_payload_download": lambda: self.status.total_payload_download,
- "total_payload_upload": lambda: self.status.total_payload_upload,
- "total_peers": lambda: self.status.num_incomplete,
- "total_seeds": lambda: self.status.num_complete,
- "total_uploaded": lambda: self.status.all_time_upload,
- "total_wanted": lambda: self.status.total_wanted,
- "total_remaining": lambda: self.status.total_wanted - self.status.total_wanted_done,
- "tracker": lambda: self.status.current_tracker,
- "tracker_host": self.get_tracker_host,
- "trackers": lambda: self.trackers,
- "tracker_status": lambda: self.tracker_status,
- "upload_payload_rate": lambda: self.status.upload_payload_rate,
- "comment": lambda: decode_string(self.torrent_info.comment()) if self.has_metadata else "",
- "num_files": lambda: self.torrent_info.num_files() if self.has_metadata else 0,
- "num_pieces": lambda: self.torrent_info.num_pieces() if self.has_metadata else 0,
- "piece_length": lambda: self.torrent_info.piece_length() if self.has_metadata else 0,
- "private": lambda: self.torrent_info.priv() if self.has_metadata else False,
- "total_size": lambda: self.torrent_info.total_size() if self.has_metadata else 0,
- "eta": self.get_eta,
- "file_progress": self.get_file_progress,
- "files": self.get_files,
- "orig_files": self.get_orig_files,
- "is_seed": lambda: self.status.is_seeding,
- "peers": self.get_peers,
- "queue": lambda: self.status.queue_position,
- "ratio": self.get_ratio,
- "completed_time": lambda: self.status.completed_time,
- "last_seen_complete": lambda: self.status.last_seen_complete,
- "name": self.get_name,
- "pieces": self._get_pieces_info,
- "seed_mode": lambda: self.status.seed_mode,
- "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,
- "priority": lambda: self.status.priority,
+ 'seed_rank': lambda: self.status.seed_rank,
+ 'state': lambda: self.state,
+ 'stop_at_ratio': lambda: self.options['stop_at_ratio'],
+ 'stop_ratio': lambda: self.options['stop_ratio'],
+ 'time_added': lambda: self.status.added_time,
+ 'total_done': lambda: self.status.total_done,
+ 'total_payload_download': lambda: self.status.total_payload_download,
+ 'total_payload_upload': lambda: self.status.total_payload_upload,
+ 'total_peers': lambda: self.status.num_incomplete,
+ 'total_seeds': lambda: self.status.num_complete,
+ 'total_uploaded': lambda: self.status.all_time_upload,
+ 'total_wanted': lambda: self.status.total_wanted,
+ 'total_remaining': lambda: self.status.total_wanted - self.status.total_wanted_done,
+ 'tracker': lambda: self.status.current_tracker,
+ 'tracker_host': self.get_tracker_host,
+ 'trackers': lambda: self.trackers,
+ 'tracker_status': lambda: self.tracker_status,
+ 'upload_payload_rate': lambda: self.status.upload_payload_rate,
+ 'comment': lambda: decode_string(self.torrent_info.comment()) if self.has_metadata else '',
+ 'num_files': lambda: self.torrent_info.num_files() if self.has_metadata else 0,
+ 'num_pieces': lambda: self.torrent_info.num_pieces() if self.has_metadata else 0,
+ 'piece_length': lambda: self.torrent_info.piece_length() if self.has_metadata else 0,
+ 'private': lambda: self.torrent_info.priv() if self.has_metadata else False,
+ 'total_size': lambda: self.torrent_info.total_size() if self.has_metadata else 0,
+ 'eta': self.get_eta,
+ 'file_progress': self.get_file_progress,
+ 'files': self.get_files,
+ 'orig_files': self.get_orig_files,
+ 'is_seed': lambda: self.status.is_seeding,
+ 'peers': self.get_peers,
+ 'queue': lambda: self.status.queue_position,
+ 'ratio': self.get_ratio,
+ 'completed_time': lambda: self.status.completed_time,
+ 'last_seen_complete': lambda: self.status.last_seen_complete,
+ 'name': self.get_name,
+ 'pieces': self._get_pieces_info,
+ 'seed_mode': lambda: self.status.seed_mode,
+ '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,
+ 'priority': lambda: self.status.priority,
}
def pause(self):
@@ -1058,7 +1058,7 @@ class Torrent(object):
"""
# Turn off auto-management so the torrent will not be unpaused by lt queueing
self.handle.auto_managed(False)
- if self.state == "Error":
+ if self.state == 'Error':
return False
elif self.status.paused:
# This torrent was probably paused due to being auto managed by lt
@@ -1066,37 +1066,37 @@ class Torrent(object):
# show it as 'Paused'. We need to emit a torrent_paused signal because
# the torrent_paused alert from libtorrent will not be generated.
self.update_state()
- component.get("EventManager").emit(TorrentStateChangedEvent(self.torrent_id, "Paused"))
+ component.get('EventManager').emit(TorrentStateChangedEvent(self.torrent_id, 'Paused'))
else:
try:
self.handle.pause()
except RuntimeError as ex:
- log.debug("Unable to pause torrent: %s", ex)
+ log.debug('Unable to pause torrent: %s', ex)
return False
return True
def resume(self):
"""Resumes this torrent."""
if self.status.paused and self.status.auto_managed:
- log.debug("Resume not possible for auto-managed torrent!")
+ log.debug('Resume not possible for auto-managed torrent!')
elif self.forced_error and self.forced_error.was_paused:
log.debug("Resume skipped for error'd torrent as it was originally paused.")
- elif (self.status.is_finished and self.options["stop_at_ratio"] and
- self.get_ratio() >= self.options["stop_ratio"]):
+ elif (self.status.is_finished and self.options['stop_at_ratio'] and
+ self.get_ratio() >= self.options['stop_ratio']):
log.debug("Resume skipped for torrent as it has reached 'stop_seed_ratio'.")
else:
# Check if torrent was originally being auto-managed.
- if self.options["auto_managed"]:
+ if self.options['auto_managed']:
self.handle.auto_managed(True)
try:
self.handle.resume()
except RuntimeError as ex:
- log.debug("Unable to resume torrent: %s", ex)
+ log.debug('Unable to resume torrent: %s', ex)
# Clear torrent error state.
if self.forced_error and not self.forced_error.restart_to_resume:
self.clear_forced_error_state()
- elif self.state == "Error" and not self.forced_error:
+ elif self.state == 'Error' and not self.forced_error:
self.handle.clear_error()
def connect_peer(self, peer_ip, peer_port):
@@ -1112,7 +1112,7 @@ class Torrent(object):
try:
self.handle.connect_peer((peer_ip, peer_port), 0)
except RuntimeError as ex:
- log.debug("Unable to connect to peer: %s", ex)
+ log.debug('Unable to connect to peer: %s', ex)
return False
return True
@@ -1132,8 +1132,8 @@ 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",
+ 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
@@ -1145,7 +1145,7 @@ class Torrent(object):
except TypeError:
self.handle.move_storage(utf8_encoded(dest), flags=1)
except RuntimeError as ex:
- log.error("Error calling libtorrent move_storage: %s", ex)
+ log.error('Error calling libtorrent move_storage: %s', ex)
return False
self.moving_storage = True
self.moving_storage_dest_path = dest
@@ -1164,12 +1164,12 @@ class Torrent(object):
"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("Requesting save_resume_data for torrent: %s", self.torrent_id)
+ log.debug('Requesting save_resume_data for torrent: %s', self.torrent_id)
flags = lt.save_resume_flags_t.flush_disk_cache if flush_disk_cache else 0
# 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"))
+ component.get('TorrentManager').waiting_on_resume_data[self.torrent_id].errback(
+ UserWarning('Skipped creating resume_data while in Error state'))
else:
self.handle.save_resume_data(flags)
@@ -1183,48 +1183,48 @@ class Torrent(object):
def write_file(filepath, filedump):
"""Write out the torrent file"""
- log.debug("Writing torrent file to: %s", filepath)
+ log.debug('Writing torrent file to: %s', filepath)
try:
- with open(filepath, "wb") as save_file:
+ with open(filepath, 'wb') as save_file:
save_file.write(filedump)
except IOError as ex:
- log.error("Unable to save torrent file to: %s", ex)
+ log.error('Unable to save torrent file to: %s', ex)
- filepath = os.path.join(get_config_dir(), "state", self.torrent_id + ".torrent")
+ filepath = os.path.join(get_config_dir(), 'state', self.torrent_id + '.torrent')
# Regenerate the file priorities
self.set_file_priorities([])
if filedump is None:
metadata = lt.bdecode(self.torrent_info.metadata())
- torrent_file = {"info": metadata}
+ torrent_file = {'info': metadata}
filedump = lt.bencode(torrent_file)
write_file(filepath, filedump)
# If the user has requested a copy of the torrent be saved elsewhere we need to do that.
- if self.config["copy_torrent_file"]:
+ if self.config['copy_torrent_file']:
if not self.filename:
- self.filename = self.get_name() + ".torrent"
- filepath = os.path.join(self.config["torrentfiles_location"], self.filename)
+ self.filename = self.get_name() + '.torrent'
+ filepath = os.path.join(self.config['torrentfiles_location'], self.filename)
write_file(filepath, filedump)
def delete_torrentfile(self, delete_copies=False):
"""Deletes the .torrent file in the state directory in config"""
- torrent_files = [os.path.join(get_config_dir(), "state", self.torrent_id + ".torrent")]
+ torrent_files = [os.path.join(get_config_dir(), 'state', self.torrent_id + '.torrent')]
if delete_copies:
- torrent_files.append(os.path.join(self.config["torrentfiles_location"], self.filename))
+ torrent_files.append(os.path.join(self.config['torrentfiles_location'], self.filename))
for torrent_file in torrent_files:
- log.debug("Deleting torrent file: %s", torrent_file)
+ log.debug('Deleting torrent file: %s', torrent_file)
try:
os.remove(torrent_file)
except OSError as ex:
- log.warning("Unable to delete the torrent file: %s", ex)
+ log.warning('Unable to delete the torrent file: %s', ex)
def force_reannounce(self):
"""Force a tracker reannounce"""
try:
self.handle.force_reannounce()
except RuntimeError as ex:
- log.debug("Unable to force reannounce: %s", ex)
+ log.debug('Unable to force reannounce: %s', ex)
return False
return True
@@ -1237,7 +1237,7 @@ class Torrent(object):
try:
self.handle.scrape_tracker()
except RuntimeError as ex:
- log.debug("Unable to scrape tracker: %s", ex)
+ log.debug('Unable to scrape tracker: %s', ex)
return False
return True
@@ -1254,7 +1254,7 @@ class Torrent(object):
self.handle.resume()
self.forcing_recheck = True
except RuntimeError as ex:
- log.debug("Unable to force recheck: %s", ex)
+ log.debug('Unable to force recheck: %s', ex)
self.forcing_recheck = False
return self.forcing_recheck
@@ -1285,7 +1285,7 @@ class Torrent(object):
Returns:
twisted.internet.defer.Deferred: A deferred which fires when the rename is complete
"""
- log.debug("Attempting to rename folder: %s to %s", folder, new_folder)
+ log.debug('Attempting to rename folder: %s to %s', folder, new_folder)
# Empty string means remove the dir and move its content to the parent
if len(new_folder) > 0:
@@ -1298,24 +1298,24 @@ class Torrent(object):
wait_on_folder = {}
self.waiting_on_folder_rename.append(wait_on_folder)
for _file in self.get_files():
- if _file["path"].startswith(folder):
+ 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"]
+ wait_on_folder[_file['index']] = Deferred().addBoth(
+ on_file_rename_complete, wait_on_folder, _file['index']
)
- new_path = _file["path"].replace(folder, new_folder, 1)
+ new_path = _file['path'].replace(folder, new_folder, 1)
try:
- self.handle.rename_file(_file["index"], new_path)
+ self.handle.rename_file(_file['index'], new_path)
except TypeError:
- self.handle.rename_file(_file["index"], utf8_encoded(new_path))
+ self.handle.rename_file(_file['index'], utf8_encoded(new_path))
def on_folder_rename_complete(dummy_result, torrent, folder, new_folder):
"""Folder rename complete"""
- component.get("EventManager").emit(TorrentFolderRenamedEvent(torrent.torrent_id, folder, new_folder))
+ component.get('EventManager').emit(TorrentFolderRenamedEvent(torrent.torrent_id, folder, new_folder))
# Empty folders are removed after libtorrent folder renames
self.remove_empty_folders(folder)
torrent.waiting_on_folder_rename = [_dir for _dir in torrent.waiting_on_folder_rename if _dir]
- component.get("TorrentManager").save_resume_data((self.torrent_id,))
+ component.get('TorrentManager').save_resume_data((self.torrent_id,))
d = DeferredList(wait_on_folder.values())
d.addBoth(on_folder_rename_complete, self, folder, new_folder)
@@ -1330,24 +1330,24 @@ class Torrent(object):
folder (str): The folder to recursively check
"""
# Removes leading slashes that can cause join to ignore download_location
- download_location = self.options["download_location"]
- folder_full_path = os.path.normpath(os.path.join(download_location, folder.lstrip("\\/")))
+ download_location = self.options['download_location']
+ folder_full_path = os.path.normpath(os.path.join(download_location, folder.lstrip('\\/')))
try:
if not os.listdir(folder_full_path):
os.removedirs(folder_full_path)
- log.debug("Removed Empty Folder %s", folder_full_path)
+ log.debug('Removed Empty Folder %s', folder_full_path)
else:
for root, dirs, dummy_files in os.walk(folder_full_path, topdown=False):
for name in dirs:
try:
os.removedirs(os.path.join(root, name))
- log.debug("Removed Empty Folder %s", os.path.join(root, name))
+ log.debug('Removed Empty Folder %s', os.path.join(root, name))
except OSError as ex:
log.debug(ex)
except OSError as ex:
- log.debug("Cannot Remove Folder: %s", ex)
+ log.debug('Cannot Remove Folder: %s', ex)
def cleanup_prev_status(self):
"""Checks the validity of the keys in the prev_status dict.
diff --git a/deluge/core/torrentmanager.py b/deluge/core/torrentmanager.py
index 6f5458f2d..2ec5ffa55 100644
--- a/deluge/core/torrentmanager.py
+++ b/deluge/core/torrentmanager.py
@@ -46,7 +46,7 @@ class TorrentState: # pylint: disable=old-style-class
torrent_id=None,
filename=None,
trackers=None,
- storage_mode="sparse",
+ storage_mode='sparse',
paused=False,
save_path=None,
max_connections=-1,
@@ -72,7 +72,7 @@ class TorrentState: # pylint: disable=old-style-class
name=None):
# Build the class atrribute list from args
for key, value in locals().items():
- if key == "self":
+ if key == 'self':
continue
setattr(self, key, value)
@@ -96,21 +96,21 @@ class TorrentManager(component.Component):
"""
def __init__(self):
- component.Component.__init__(self, "TorrentManager", interval=5,
- depend=["CorePluginManager", "AlertManager"])
- log.debug("TorrentManager init...")
+ component.Component.__init__(self, 'TorrentManager', interval=5,
+ depend=['CorePluginManager', 'AlertManager'])
+ log.debug('TorrentManager init...')
# Set the libtorrent session
- self.session = component.get("Core").session
+ self.session = component.get('Core').session
# Set the alertmanager
- self.alerts = component.get("AlertManager")
+ self.alerts = component.get('AlertManager')
# Get the core config
- self.config = ConfigManager("core.conf")
+ self.config = ConfigManager('core.conf')
# Make sure the state folder has been created
- self.state_dir = os.path.join(get_config_dir(), "state")
+ self.state_dir = os.path.join(get_config_dir(), 'state')
if not os.path.exists(self.state_dir):
os.makedirs(self.state_dir)
- self.temp_file = os.path.join(self.state_dir, ".safe_state_check")
+ self.temp_file = os.path.join(self.state_dir, '.safe_state_check')
# Create the torrents dict { torrent_id: Torrent }
self.torrents = {}
@@ -134,38 +134,38 @@ class TorrentManager(component.Component):
self.last_state_update_alert_ts = 0
# Register set functions
- self.config.register_set_function("max_connections_per_torrent",
+ self.config.register_set_function('max_connections_per_torrent',
self.on_set_max_connections_per_torrent)
- self.config.register_set_function("max_upload_slots_per_torrent",
+ self.config.register_set_function('max_upload_slots_per_torrent',
self.on_set_max_upload_slots_per_torrent)
- self.config.register_set_function("max_upload_speed_per_torrent",
+ self.config.register_set_function('max_upload_speed_per_torrent',
self.on_set_max_upload_speed_per_torrent)
- self.config.register_set_function("max_download_speed_per_torrent",
+ self.config.register_set_function('max_download_speed_per_torrent',
self.on_set_max_download_speed_per_torrent)
# Register alert functions
- self.alerts.register_handler("torrent_finished_alert", self.on_alert_torrent_finished)
- self.alerts.register_handler("torrent_paused_alert", self.on_alert_torrent_paused)
- self.alerts.register_handler("torrent_checked_alert", self.on_alert_torrent_checked)
- self.alerts.register_handler("tracker_reply_alert", self.on_alert_tracker_reply)
- self.alerts.register_handler("tracker_announce_alert", self.on_alert_tracker_announce)
- self.alerts.register_handler("tracker_warning_alert", self.on_alert_tracker_warning)
- self.alerts.register_handler("tracker_error_alert", self.on_alert_tracker_error)
- self.alerts.register_handler("storage_moved_alert", self.on_alert_storage_moved)
- self.alerts.register_handler("storage_moved_failed_alert", self.on_alert_storage_moved_failed)
- self.alerts.register_handler("torrent_resumed_alert", self.on_alert_torrent_resumed)
- self.alerts.register_handler("state_changed_alert", self.on_alert_state_changed)
- self.alerts.register_handler("save_resume_data_alert", self.on_alert_save_resume_data)
- self.alerts.register_handler("save_resume_data_failed_alert", self.on_alert_save_resume_data_failed)
- self.alerts.register_handler("file_renamed_alert", self.on_alert_file_renamed)
- self.alerts.register_handler("metadata_received_alert", self.on_alert_metadata_received)
- self.alerts.register_handler("file_error_alert", self.on_alert_file_error)
- self.alerts.register_handler("file_completed_alert", self.on_alert_file_completed)
- self.alerts.register_handler("state_update_alert", self.on_alert_state_update)
- self.alerts.register_handler("external_ip_alert", self.on_alert_external_ip)
- self.alerts.register_handler("performance_alert", self.on_alert_performance)
- self.alerts.register_handler("fastresume_rejected_alert", self.on_alert_fastresume_rejected)
- self.alerts.register_handler("add_torrent_alert", self.on_add_torrent_alert)
+ self.alerts.register_handler('torrent_finished_alert', self.on_alert_torrent_finished)
+ self.alerts.register_handler('torrent_paused_alert', self.on_alert_torrent_paused)
+ self.alerts.register_handler('torrent_checked_alert', self.on_alert_torrent_checked)
+ self.alerts.register_handler('tracker_reply_alert', self.on_alert_tracker_reply)
+ self.alerts.register_handler('tracker_announce_alert', self.on_alert_tracker_announce)
+ self.alerts.register_handler('tracker_warning_alert', self.on_alert_tracker_warning)
+ self.alerts.register_handler('tracker_error_alert', self.on_alert_tracker_error)
+ self.alerts.register_handler('storage_moved_alert', self.on_alert_storage_moved)
+ self.alerts.register_handler('storage_moved_failed_alert', self.on_alert_storage_moved_failed)
+ self.alerts.register_handler('torrent_resumed_alert', self.on_alert_torrent_resumed)
+ self.alerts.register_handler('state_changed_alert', self.on_alert_state_changed)
+ self.alerts.register_handler('save_resume_data_alert', self.on_alert_save_resume_data)
+ self.alerts.register_handler('save_resume_data_failed_alert', self.on_alert_save_resume_data_failed)
+ self.alerts.register_handler('file_renamed_alert', self.on_alert_file_renamed)
+ self.alerts.register_handler('metadata_received_alert', self.on_alert_metadata_received)
+ self.alerts.register_handler('file_error_alert', self.on_alert_file_error)
+ self.alerts.register_handler('file_completed_alert', self.on_alert_file_completed)
+ self.alerts.register_handler('state_update_alert', self.on_alert_state_update)
+ self.alerts.register_handler('external_ip_alert', self.on_alert_external_ip)
+ self.alerts.register_handler('performance_alert', self.on_alert_performance)
+ self.alerts.register_handler('fastresume_rejected_alert', self.on_alert_fastresume_rejected)
+ self.alerts.register_handler('add_torrent_alert', self.on_add_torrent_alert)
# Define timers
self.save_state_timer = LoopingCall(self.save_state)
@@ -178,24 +178,24 @@ class TorrentManager(component.Component):
def archive_file(filename):
"""Archives the file in 'archive' sub-directory with timestamp appended"""
filepath = os.path.join(self.state_dir, filename)
- filepath_bak = filepath + ".bak"
- archive_dir = os.path.join(get_config_dir(), "archive")
+ filepath_bak = filepath + '.bak'
+ archive_dir = os.path.join(get_config_dir(), 'archive')
if not os.path.exists(archive_dir):
os.makedirs(archive_dir)
for _filepath in (filepath, filepath_bak):
timestamp = datetime.datetime.now().replace(microsecond=0).isoformat().replace(':', '-')
- archive_filepath = os.path.join(archive_dir, filename + "-" + timestamp)
+ archive_filepath = os.path.join(archive_dir, filename + '-' + timestamp)
try:
shutil.copy2(_filepath, archive_filepath)
except IOError:
- log.error("Unable to archive: %s", filename)
+ log.error('Unable to archive: %s', filename)
else:
- log.info("Archive of %s successful: %s", filename, archive_filepath)
+ log.info('Archive of %s successful: %s', filename, archive_filepath)
- log.warning("Potential bad shutdown of Deluge detected, archiving torrent state files...")
- archive_file("torrents.state")
- archive_file("torrents.fastresume")
+ log.warning('Potential bad shutdown of Deluge detected, archiving torrent state files...')
+ archive_file('torrents.state')
+ archive_file('torrents.fastresume')
else:
with open(self.temp_file, 'a'):
os.utime(self.temp_file, None)
@@ -233,15 +233,15 @@ class TorrentManager(component.Component):
def update(self):
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"):
+ if torrent.options['stop_at_ratio'] and torrent.state not in (
+ '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
- if not torrent.options["stop_at_ratio"]:
+ if not torrent.options['stop_at_ratio']:
continue
- if torrent.get_ratio() >= torrent.options["stop_ratio"] and torrent.is_finished:
- if torrent.options["remove_at_ratio"]:
+ if torrent.get_ratio() >= torrent.options['stop_ratio'] and torrent.is_finished:
+ if torrent.options['remove_at_ratio']:
self.remove(torrent_id)
break
if not torrent.handle.status().paused:
@@ -267,13 +267,13 @@ class TorrentManager(component.Component):
"""
torrent_ids = self.torrents.keys()
- if component.get("RPCServer").get_session_auth_level() == AUTH_LEVEL_ADMIN:
+ if component.get('RPCServer').get_session_auth_level() == AUTH_LEVEL_ADMIN:
return torrent_ids
- current_user = component.get("RPCServer").get_session_user()
+ current_user = component.get('RPCServer').get_session_user()
for torrent_id in torrent_ids[:]:
- torrent_status = self.torrents[torrent_id].get_status(["owner", "shared"])
- if torrent_status["owner"] != current_user and not torrent_status["shared"]:
+ torrent_status = self.torrents[torrent_id].get_status(['owner', 'shared'])
+ if torrent_status['owner'] != current_user and not torrent_status['shared']:
torrent_ids.pop(torrent_ids.index(torrent_id))
return torrent_ids
@@ -289,11 +289,11 @@ class TorrentManager(component.Component):
"""
# Get the torrent data from the torrent file
if log.isEnabledFor(logging.DEBUG):
- log.debug("Attempting to extract torrent_info from %s", filepath)
+ log.debug('Attempting to extract torrent_info from %s', filepath)
try:
torrent_info = lt.torrent_info(filepath)
except RuntimeError as ex:
- log.warning("Unable to open torrent file %s: %s", filepath, ex)
+ log.warning('Unable to open torrent file %s: %s', filepath, ex)
else:
return torrent_info
@@ -319,39 +319,39 @@ class TorrentManager(component.Component):
"""
if not torrent_info and not filedump and not magnet:
- raise AddTorrentError("You must specify a valid torrent_info, torrent state or magnet.")
+ raise AddTorrentError('You must specify a valid torrent_info, torrent state or magnet.')
if filedump:
try:
torrent_info = lt.torrent_info(lt.bdecode(filedump))
except RuntimeError as ex:
- raise AddTorrentError("Unable to add torrent, decoding filedump failed: %s" % ex)
+ raise AddTorrentError('Unable to add torrent, decoding filedump failed: %s' % ex)
add_torrent_params = {}
if torrent_info:
- add_torrent_params["ti"] = torrent_info
+ add_torrent_params['ti'] = torrent_info
name = torrent_info.name()
if not name:
- name = torrent_info.file_at(0).path.replace("\\", "/", 1).split("/", 1)[0]
- add_torrent_params["name"] = name
+ name = torrent_info.file_at(0).path.replace('\\', '/', 1).split('/', 1)[0]
+ add_torrent_params['name'] = name
torrent_id = str(torrent_info.info_hash())
elif magnet:
magnet = utf8_encoded(magnet)
magnet_info = get_magnet_info(magnet)
if magnet_info:
- add_torrent_params["url"] = magnet
- add_torrent_params["name"] = magnet_info["name"]
- torrent_id = magnet_info["info_hash"]
+ add_torrent_params['url'] = magnet
+ add_torrent_params['name'] = magnet_info['name']
+ torrent_id = magnet_info['info_hash']
else:
- raise AddTorrentError("Unable to add magnet, invalid magnet info: %s" % magnet)
+ raise AddTorrentError('Unable to add magnet, invalid magnet info: %s' % magnet)
# Check for existing torrent in session.
if torrent_id in self.get_torrent_list():
# Attempt merge trackers before returning.
self.torrents[torrent_id].merge_trackers(torrent_info)
- raise AddTorrentError("Torrent already in session (%s)." % torrent_id)
+ raise AddTorrentError('Torrent already in session (%s).' % torrent_id)
elif torrent_id in self.torrents_loading:
- raise AddTorrentError("Torrent already being added (%s)." % torrent_id)
+ raise AddTorrentError('Torrent already being added (%s).' % torrent_id)
# Load default options and update if needed.
_options = TorrentOptions()
@@ -360,63 +360,63 @@ class TorrentManager(component.Component):
options = _options
# Check for renamed files and if so, rename them in the torrent_info before adding.
- if options["mapped_files"] and torrent_info:
- for index, fname in options["mapped_files"].items():
+ if options['mapped_files'] and torrent_info:
+ for index, fname in options['mapped_files'].items():
fname = sanitize_filepath(decode_string(fname))
- log.debug("renaming file index %s to %s", index, fname)
+ log.debug('renaming file index %s to %s', index, fname)
try:
torrent_info.rename_file(index, fname)
except TypeError:
torrent_info.rename_file(index, utf8_encoded(fname))
- add_torrent_params["ti"] = torrent_info
+ add_torrent_params['ti'] = torrent_info
- if not options["owner"]:
- options["owner"] = component.get("RPCServer").get_session_user()
- if not component.get("AuthManager").has_account(options["owner"]):
- options["owner"] = "localclient"
+ if not options['owner']:
+ options['owner'] = component.get('RPCServer').get_session_user()
+ if not component.get('AuthManager').has_account(options['owner']):
+ options['owner'] = 'localclient'
if log.isEnabledFor(logging.DEBUG):
- log.debug("options: %s", options)
+ log.debug('options: %s', options)
# Fill in the rest of the add_torrent_params dictionary.
- add_torrent_params["save_path"] = utf8_encoded(options["download_location"])
- if options["name"]:
- add_torrent_params["name"] = options["name"]
- if options["pre_allocate_storage"]:
- add_torrent_params["storage_mode"] = lt.storage_mode_t.storage_mode_allocate
+ add_torrent_params['save_path'] = utf8_encoded(options['download_location'])
+ if options['name']:
+ add_torrent_params['name'] = options['name']
+ if options['pre_allocate_storage']:
+ add_torrent_params['storage_mode'] = lt.storage_mode_t.storage_mode_allocate
if resume_data:
- add_torrent_params["resume_data"] = resume_data
+ add_torrent_params['resume_data'] = resume_data
default_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)
# Set flags: enable duplicate_is_error & override_resume_data, disable auto_managed.
- add_torrent_params["flags"] = ((default_flags |
+ add_torrent_params['flags'] = ((default_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
+ if options['seed_mode']:
+ add_torrent_params['flags'] |= lt.add_torrent_params_flags_t.flag_seed_mode
d = Deferred()
try:
self.torrents_loading[torrent_id] = (d, options, state, filename, magnet, resume_data, filedump, save_state)
self.session.async_add_torrent(add_torrent_params)
except RuntimeError as ex:
- raise AddTorrentError("Unable to add torrent to session: %s" % ex)
+ raise AddTorrentError('Unable to add torrent to session: %s' % ex)
return d
def on_add_torrent_alert(self, alert):
"""Alert handler for libtorrent add_torrent_alert"""
if not alert.handle.is_valid():
- log.warn("Torrent handle is invalid!")
+ log.warn('Torrent handle is invalid!')
return
try:
torrent_id = str(alert.handle.info_hash())
except RuntimeError as ex:
- log.warn("Failed to get torrent id from handle: %s", ex)
+ log.warn('Failed to get torrent id from handle: %s', ex)
return
d, options, state, filename, magnet, resume_data, filedump, save_state = self.torrents_loading.pop(torrent_id)
@@ -431,25 +431,25 @@ class TorrentManager(component.Component):
# Add to queued torrents set.
self.queued_torrents.add(torrent.torrent_id)
- if self.config["queue_new_to_top"]:
+ if self.config['queue_new_to_top']:
self.queue_top(torrent.torrent_id)
# Resume the torrent if needed.
- if not options["add_paused"]:
+ if not options['add_paused']:
torrent.resume()
# Emit torrent_added signal.
from_state = state is not None
- component.get("EventManager").emit(TorrentAddedEvent(torrent.torrent_id, from_state))
+ component.get('EventManager').emit(TorrentAddedEvent(torrent.torrent_id, from_state))
if log.isEnabledFor(logging.DEBUG):
- log.debug("Torrent added: %s", str(alert.handle.info_hash()))
+ log.debug('Torrent added: %s', str(alert.handle.info_hash()))
if log.isEnabledFor(logging.INFO):
- name_and_owner = torrent.get_status(["name", "owner"])
+ 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")
+ name_and_owner['name'],
+ name_and_owner['owner'],
+ from_state and 'loaded' or 'added')
# Write the .torrent file to the state directory.
if filedump:
@@ -485,22 +485,22 @@ class TorrentManager(component.Component):
except KeyError:
raise InvalidTorrentError("torrent_id '%s' not in session." % torrent_id)
- torrent_name = torrent.get_status(["name"])["name"]
+ torrent_name = torrent.get_status(['name'])['name']
# Emit the signal to the clients
- component.get("EventManager").emit(PreTorrentRemovedEvent(torrent_id))
+ component.get('EventManager').emit(PreTorrentRemovedEvent(torrent_id))
try:
self.session.remove_torrent(torrent.handle, 1 if remove_data else 0)
except RuntimeError as ex:
- log.warning("Error removing torrent: %s", ex)
+ log.warning('Error removing torrent: %s', ex)
return False
# Remove fastresume data if it is exists
self.resume_data.pop(torrent_id, None)
# Remove the .torrent file in the state and copy location, if user requested.
- delete_copies = self.config["copy_torrent_file"] and self.config["del_copy_torrent_file"]
+ delete_copies = self.config['copy_torrent_file'] and self.config['del_copy_torrent_file']
torrent.delete_torrentfile(delete_copies)
# Remove from set if it wasn't finished
@@ -518,8 +518,8 @@ class TorrentManager(component.Component):
self.save_state()
# Emit the signal to the clients
- component.get("EventManager").emit(TorrentRemovedEvent(torrent_id))
- log.info("Torrent %s removed by user: %s", torrent_name, component.get("RPCServer").get_session_user())
+ component.get('EventManager').emit(TorrentRemovedEvent(torrent_id))
+ log.info('Torrent %s removed by user: %s', torrent_name, component.get('RPCServer').get_session_user())
return True
def fixup_state(self, state):
@@ -540,7 +540,7 @@ class TorrentManager(component.Component):
for t_state in state.torrents:
setattr(t_state, attr, getattr(t_state_tmp, attr, None))
except AttributeError as ex:
- log.error("Unable to update state file to a compatible version: %s", ex)
+ log.error('Unable to update state file to a compatible version: %s', ex)
return state
def open_state(self):
@@ -550,17 +550,17 @@ class TorrentManager(component.Component):
TorrentManagerState: The TorrentManager state.
"""
- torrents_state = os.path.join(self.state_dir, "torrents.state")
- for filepath in (torrents_state, torrents_state + ".bak"):
- log.info("Loading torrent state: %s", filepath)
+ torrents_state = os.path.join(self.state_dir, 'torrents.state')
+ for filepath in (torrents_state, torrents_state + '.bak'):
+ log.info('Loading torrent state: %s', filepath)
try:
- with open(filepath, "rb") as _file:
+ with open(filepath, 'rb') as _file:
state = cPickle.load(_file)
except (IOError, EOFError, cPickle.UnpicklingError) as ex:
- log.warning("Unable to load %s: %s", filepath, ex)
+ log.warning('Unable to load %s: %s', filepath, ex)
state = None
else:
- log.info("Successfully loaded %s", filepath)
+ log.info('Successfully loaded %s', filepath)
break
if state is None:
@@ -579,7 +579,7 @@ class TorrentManager(component.Component):
state = self.fixup_state(state)
# Reorder the state.torrents list to add torrents in the correct queue order.
- state.torrents.sort(key=operator.attrgetter("queue"), reverse=self.config["queue_new_to_top"])
+ state.torrents.sort(key=operator.attrgetter('queue'), reverse=self.config['queue_new_to_top'])
resume_data = self.load_resume_data_file()
deferreds = []
@@ -592,14 +592,14 @@ class TorrentManager(component.Component):
except AttributeError:
pass
# Manually update unmatched attributes
- options["download_location"] = t_state.save_path
- options["pre_allocate_storage"] = t_state.storage_mode == "allocate"
- options["prioritize_first_last_pieces"] = t_state.prioritize_first_last
- options["add_paused"] = t_state.paused
+ options['download_location'] = t_state.save_path
+ options['pre_allocate_storage'] = t_state.storage_mode == 'allocate'
+ options['prioritize_first_last_pieces'] = t_state.prioritize_first_last
+ options['add_paused'] = t_state.paused
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
@@ -614,8 +614,8 @@ class TorrentManager(component.Component):
deferred_list = DeferredList(deferreds, consumeErrors=False)
def on_complete(result):
- log.info("Finished loading %d torrents in %s", len(state.torrents), str(datetime.datetime.now() - start))
- component.get("EventManager").emit(SessionStartedEvent())
+ log.info('Finished loading %d torrents in %s', len(state.torrents), str(datetime.datetime.now() - start))
+ component.get('EventManager').emit(SessionStartedEvent())
deferred_list.addCallback(on_complete)
def create_state(self):
@@ -632,7 +632,7 @@ class TorrentManager(component.Component):
paused = torrent.handle.is_paused()
elif torrent.forced_error:
paused = torrent.forced_error.was_paused
- elif torrent.state == "Paused":
+ elif torrent.state == 'Paused':
paused = True
else:
paused = False
@@ -641,30 +641,30 @@ class TorrentManager(component.Component):
torrent.torrent_id,
torrent.filename,
torrent.trackers,
- torrent.get_status(["storage_mode"])["storage_mode"],
+ torrent.get_status(['storage_mode'])['storage_mode'],
paused,
- torrent.options["download_location"],
- torrent.options["max_connections"],
- torrent.options["max_upload_slots"],
- torrent.options["max_upload_speed"],
- torrent.options["max_download_speed"],
- torrent.options["prioritize_first_last_pieces"],
- torrent.options["sequential_download"],
- torrent.options["file_priorities"],
+ torrent.options['download_location'],
+ torrent.options['max_connections'],
+ torrent.options['max_upload_slots'],
+ torrent.options['max_upload_speed'],
+ torrent.options['max_download_speed'],
+ torrent.options['prioritize_first_last_pieces'],
+ torrent.options['sequential_download'],
+ torrent.options['file_priorities'],
torrent.get_queue_position(),
- torrent.options["auto_managed"],
+ torrent.options['auto_managed'],
torrent.is_finished,
- torrent.options["stop_ratio"],
- torrent.options["stop_at_ratio"],
- torrent.options["remove_at_ratio"],
- torrent.options["move_completed"],
- torrent.options["move_completed_path"],
+ torrent.options['stop_ratio'],
+ torrent.options['stop_at_ratio'],
+ torrent.options['remove_at_ratio'],
+ torrent.options['move_completed'],
+ torrent.options['move_completed_path'],
torrent.magnet,
- torrent.options["owner"],
- torrent.options["shared"],
- torrent.options["super_seeding"],
- torrent.options["priority"],
- torrent.options["name"]
+ torrent.options['owner'],
+ torrent.options['shared'],
+ torrent.options['super_seeding'],
+ torrent.options['priority'],
+ torrent.options['name']
)
state.torrents.append(torrent_state)
return state
@@ -692,41 +692,41 @@ class TorrentManager(component.Component):
"""Save the state of the TorrentManager to the torrents.state file."""
state = self.create_state()
if not state.torrents:
- log.debug("Skipping saving state with no torrents loaded")
+ log.debug('Skipping saving state with no torrents loaded')
return
- filename = "torrents.state"
+ filename = 'torrents.state'
filepath = os.path.join(self.state_dir, filename)
- filepath_bak = filepath + ".bak"
- filepath_tmp = filepath + ".tmp"
+ filepath_bak = filepath + '.bak'
+ filepath_tmp = filepath + '.tmp'
try:
- log.debug("Creating the temporary file: %s", filepath_tmp)
- with open(filepath_tmp, "wb", 0) as _file:
+ log.debug('Creating the temporary file: %s', filepath_tmp)
+ with open(filepath_tmp, 'wb', 0) as _file:
cPickle.dump(state, _file)
_file.flush()
os.fsync(_file.fileno())
except (OSError, cPickle.PicklingError) as ex:
- log.error("Unable to save %s: %s", filename, ex)
+ log.error('Unable to save %s: %s', filename, ex)
return
try:
- log.debug("Creating backup of %s at: %s", filename, filepath_bak)
+ log.debug('Creating backup of %s at: %s', filename, filepath_bak)
if os.path.isfile(filepath_bak):
os.remove(filepath_bak)
if os.path.isfile(filepath):
os.rename(filepath, filepath_bak)
except OSError as ex:
- log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex)
+ log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
return
try:
- log.debug("Saving %s to: %s", filename, filepath)
+ log.debug('Saving %s to: %s', filename, filepath)
os.rename(filepath_tmp, filepath)
except OSError as ex:
- log.error("Failed to set new state file %s: %s", filepath, ex)
+ log.error('Failed to set new state file %s: %s', filepath, ex)
if os.path.isfile(filepath_bak):
- log.info("Restoring backup of state from: %s", filepath_bak)
+ log.info('Restoring backup of state from: %s', filepath_bak)
os.rename(filepath_bak, filepath)
def save_resume_data(self, torrent_ids=None, flush_disk_cache=False):
@@ -781,22 +781,22 @@ class TorrentManager(component.Component):
dict: A dict of torrents and their resume_data.
"""
- filename = "torrents.fastresume"
+ filename = 'torrents.fastresume'
filepath = os.path.join(self.state_dir, filename)
- filepath_bak = filepath + ".bak"
+ filepath_bak = filepath + '.bak'
old_data_filepath = os.path.join(get_config_dir(), filename)
for _filepath in (filepath, filepath_bak, old_data_filepath):
- log.info("Opening %s for load: %s", filename, _filepath)
+ log.info('Opening %s for load: %s', filename, _filepath)
try:
- with open(_filepath, "rb") as _file:
+ with open(_filepath, 'rb') as _file:
resume_data = lt.bdecode(_file.read())
except (IOError, EOFError, RuntimeError) as ex:
if self.torrents:
- log.warning("Unable to load %s: %s", _filepath, ex)
+ log.warning('Unable to load %s: %s', _filepath, ex)
resume_data = None
else:
- log.info("Successfully loaded %s: %s", filename, _filepath)
+ log.info('Successfully loaded %s: %s', filename, _filepath)
break
# If the libtorrent bdecode doesn't happen properly, it will return None
# so we need to make sure we return a {}
@@ -836,38 +836,38 @@ class TorrentManager(component.Component):
if not self.resume_data:
return True
- filename = "torrents.fastresume"
+ filename = 'torrents.fastresume'
filepath = os.path.join(self.state_dir, filename)
- filepath_bak = filepath + ".bak"
- filepath_tmp = filepath + ".tmp"
+ filepath_bak = filepath + '.bak'
+ filepath_tmp = filepath + '.tmp'
try:
- log.debug("Creating the temporary file: %s", filepath_tmp)
- with open(filepath_tmp, "wb", 0) as _file:
+ log.debug('Creating the temporary file: %s', filepath_tmp)
+ with open(filepath_tmp, 'wb', 0) as _file:
_file.write(lt.bencode(self.resume_data))
_file.flush()
os.fsync(_file.fileno())
except (OSError, EOFError) as ex:
- log.error("Unable to save %s: %s", filename, ex)
+ log.error('Unable to save %s: %s', filename, ex)
return False
try:
- log.debug("Creating backup of %s at: %s", filename, filepath_bak)
+ log.debug('Creating backup of %s at: %s', filename, filepath_bak)
if os.path.isfile(filepath_bak):
os.remove(filepath_bak)
if os.path.isfile(filepath):
os.rename(filepath, filepath_bak)
except OSError as ex:
- log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex)
+ log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
return False
try:
- log.debug("Saving %s to: %s", filename, filepath)
+ log.debug('Saving %s to: %s', filename, filepath)
os.rename(filepath_tmp, filepath)
except OSError as ex:
- log.error("Failed to set new file %s: %s", filepath, ex)
+ log.error('Failed to set new file %s: %s', filepath, ex)
if os.path.isfile(filepath_bak):
- log.info("Restoring backup from: %s", filepath_bak)
+ log.info('Restoring backup from: %s', filepath_bak)
os.rename(filepath_bak, filepath)
else:
# Sync the rename operations for the directory
@@ -920,58 +920,58 @@ class TorrentManager(component.Component):
def on_set_max_connections_per_torrent(self, key, value):
"""Sets the per-torrent connection limit"""
- log.debug("max_connections_per_torrent set to %s...", value)
+ log.debug('max_connections_per_torrent set to %s...', value)
for key in self.torrents:
self.torrents[key].set_max_connections(value)
def on_set_max_upload_slots_per_torrent(self, key, value):
"""Sets the per-torrent upload slot limit"""
- log.debug("max_upload_slots_per_torrent set to %s...", value)
+ log.debug('max_upload_slots_per_torrent set to %s...', value)
for key in self.torrents:
self.torrents[key].set_max_upload_slots(value)
def on_set_max_upload_speed_per_torrent(self, key, value):
"""Sets the per-torrent upload speed limit"""
- log.debug("max_upload_speed_per_torrent set to %s...", value)
+ log.debug('max_upload_speed_per_torrent set to %s...', value)
for key in self.torrents:
self.torrents[key].set_max_upload_speed(value)
def on_set_max_download_speed_per_torrent(self, key, value):
"""Sets the per-torrent download speed limit"""
- log.debug("max_download_speed_per_torrent set to %s...", value)
+ log.debug('max_download_speed_per_torrent set to %s...', value)
for key in self.torrents:
self.torrents[key].set_max_download_speed(value)
# --- Alert handlers ---
def on_alert_torrent_finished(self, alert):
"""Alert handler for libtorrent torrent_finished_alert"""
- log.debug("on_alert_torrent_finished")
+ log.debug('on_alert_torrent_finished')
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
except (RuntimeError, KeyError):
return
- log.debug("Finished %s ", torrent_id)
+ log.debug('Finished %s ', torrent_id)
# If total_download is 0, do not move, it's likely the torrent wasn't downloaded, but just added.
# Get fresh data from libtorrent, the cache isn't always up to date
- total_download = torrent.get_status(["total_payload_download"], update=True)["total_payload_download"]
+ total_download = torrent.get_status(['total_payload_download'], update=True)['total_payload_download']
if log.isEnabledFor(logging.DEBUG):
- 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:
# Move completed download to completed folder if needed
- if torrent.options["move_completed"] and \
- torrent.options["download_location"] != torrent.options["move_completed_path"]:
+ if torrent.options['move_completed'] and \
+ torrent.options['download_location'] != torrent.options['move_completed_path']:
self.waiting_on_finish_moving.append(torrent_id)
- torrent.move_storage(torrent.options["move_completed_path"])
+ torrent.move_storage(torrent.options['move_completed_path'])
else:
torrent.is_finished = True
- component.get("EventManager").emit(TorrentFinishedEvent(torrent_id))
+ component.get('EventManager').emit(TorrentFinishedEvent(torrent_id))
else:
torrent.is_finished = True
@@ -994,7 +994,7 @@ class TorrentManager(component.Component):
def on_alert_torrent_paused(self, alert):
"""Alert handler for libtorrent torrent_paused_alert"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_torrent_paused")
+ log.debug('on_alert_torrent_paused')
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1008,7 +1008,7 @@ class TorrentManager(component.Component):
def on_alert_torrent_checked(self, alert):
"""Alert handler for libtorrent torrent_checked_alert"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_torrent_checked")
+ log.debug('on_alert_torrent_checked')
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
@@ -1025,14 +1025,14 @@ class TorrentManager(component.Component):
def on_alert_tracker_reply(self, alert):
"""Alert handler for libtorrent tracker_reply_alert"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_tracker_reply: %s", decode_string(alert.message()))
+ log.debug('on_alert_tracker_reply: %s', decode_string(alert.message()))
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
return
# Set the tracker status for the torrent
- torrent.set_tracker_status("Announce OK")
+ torrent.set_tracker_status('Announce OK')
# Check for peer information from the tracker, if none then send a scrape request.
if alert.handle.status().num_complete == -1 or alert.handle.status().num_incomplete == -1:
@@ -1041,24 +1041,24 @@ class TorrentManager(component.Component):
def on_alert_tracker_announce(self, alert):
"""Alert handler for libtorrent tracker_announce_alert"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_tracker_announce")
+ log.debug('on_alert_tracker_announce')
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
return
# Set the tracker status for the torrent
- torrent.set_tracker_status("Announce Sent")
+ torrent.set_tracker_status('Announce Sent')
def on_alert_tracker_warning(self, alert):
"""Alert handler for libtorrent tracker_warning_alert"""
- log.debug("on_alert_tracker_warning")
+ log.debug('on_alert_tracker_warning')
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
return
# Set the tracker status for the torrent
- torrent.set_tracker_status("Warning: %s" % decode_string(alert.message()))
+ torrent.set_tracker_status('Warning: %s' % decode_string(alert.message()))
def on_alert_tracker_error(self, alert):
"""Alert handler for libtorrent tracker_error_alert"""
@@ -1071,17 +1071,17 @@ class TorrentManager(component.Component):
# cannot be replaced by a.e.message because the code is included in the string (for non-'-1').
if not error_message:
error_message = decode_string(alert.error.message())
- log.debug("Tracker Error Alert: %s [%s]", decode_string(alert.message()), error_message)
+ log.debug('Tracker Error Alert: %s [%s]', decode_string(alert.message()), error_message)
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
return
- torrent.set_tracker_status("Error: " + error_message)
+ torrent.set_tracker_status('Error: ' + error_message)
def on_alert_storage_moved(self, alert):
"""Alert handler for libtorrent storage_moved_alert"""
- log.debug("on_alert_storage_moved")
+ log.debug('on_alert_storage_moved')
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1100,11 +1100,11 @@ class TorrentManager(component.Component):
if torrent_id in self.waiting_on_finish_moving:
self.waiting_on_finish_moving.remove(torrent_id)
torrent.is_finished = True
- component.get("EventManager").emit(TorrentFinishedEvent(torrent_id))
+ component.get('EventManager').emit(TorrentFinishedEvent(torrent_id))
def on_alert_storage_moved_failed(self, alert):
"""Alert handler for libtorrent storage_moved_failed_alert"""
- log.warning("on_alert_storage_moved_failed: %s", decode_string(alert.message()))
+ log.warning('on_alert_storage_moved_failed: %s', decode_string(alert.message()))
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1113,23 +1113,23 @@ class TorrentManager(component.Component):
# Set an Error message and pause the torrent
alert_msg = decode_string(alert.message()).split(':', 1)[1].strip()
torrent.moving_storage = False
- torrent.force_error_state("Failed to move download folder: %s" % alert_msg)
+ torrent.force_error_state('Failed to move download folder: %s' % alert_msg)
if torrent_id in self.waiting_on_finish_moving:
self.waiting_on_finish_moving.remove(torrent_id)
torrent.is_finished = True
- component.get("EventManager").emit(TorrentFinishedEvent(torrent_id))
+ component.get('EventManager').emit(TorrentFinishedEvent(torrent_id))
def on_alert_torrent_resumed(self, alert):
"""Alert handler for libtorrent torrent_resumed_alert"""
- log.debug("on_alert_torrent_resumed")
+ log.debug('on_alert_torrent_resumed')
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
except (RuntimeError, KeyError):
return
torrent.update_state()
- component.get("EventManager").emit(TorrentResumedEvent(torrent_id))
+ component.get('EventManager').emit(TorrentResumedEvent(torrent_id))
def on_alert_state_changed(self, alert):
"""Alert handler for libtorrent state_changed_alert.
@@ -1139,7 +1139,7 @@ class TorrentManager(component.Component):
"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_state_changed")
+ log.debug('on_alert_state_changed')
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1155,7 +1155,7 @@ class TorrentManager(component.Component):
def on_alert_save_resume_data(self, alert):
"""Alert handler for libtorrent save_resume_data_alert"""
if log.isEnabledFor(logging.DEBUG):
- log.debug("on_alert_save_resume_data")
+ log.debug('on_alert_save_resume_data')
try:
torrent_id = str(alert.handle.info_hash())
except RuntimeError:
@@ -1169,7 +1169,7 @@ class TorrentManager(component.Component):
def on_alert_save_resume_data_failed(self, alert):
"""Alert handler for libtorrent save_resume_data_failed_alert"""
- log.debug("on_alert_save_resume_data_failed: %s", decode_string(alert.message()))
+ log.debug('on_alert_save_resume_data_failed: %s', decode_string(alert.message()))
try:
torrent_id = str(alert.handle.info_hash())
except RuntimeError:
@@ -1181,7 +1181,7 @@ class TorrentManager(component.Component):
def on_alert_fastresume_rejected(self, alert):
"""Alert handler for libtorrent fastresume_rejected_alert"""
alert_msg = decode_string(alert.message())
- log.error("on_alert_fastresume_rejected: %s", alert_msg)
+ log.error('on_alert_fastresume_rejected: %s', alert_msg)
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1189,12 +1189,12 @@ class TorrentManager(component.Component):
return
if alert.error.value() == 134:
- if not os.path.isdir(torrent.options["download_location"]):
- error_msg = "Unable to locate Download Folder!"
+ if not os.path.isdir(torrent.options['download_location']):
+ error_msg = 'Unable to locate Download Folder!'
else:
- error_msg = "Missing or invalid torrent data!"
+ error_msg = 'Missing or invalid torrent data!'
else:
- error_msg = "Problem with resume data: %s" % alert_msg.split(":", 1)[1].strip()
+ error_msg = 'Problem with resume data: %s' % alert_msg.split(':', 1)[1].strip()
torrent.force_error_state(error_msg, restart_to_resume=True)
def on_alert_file_renamed(self, alert):
@@ -1204,13 +1204,13 @@ class TorrentManager(component.Component):
TorrentFileRenamedEvent: Files in the torrent have been renamed.
"""
- log.debug("on_alert_file_renamed")
+ log.debug('on_alert_file_renamed')
try:
new_name = decode_string(alert.new_name)
except AttributeError:
# Deprecated in libtorrent 1.1
new_name = decode_string(alert.name)
- log.debug("index: %s name: %s", alert.index, new_name)
+ log.debug('index: %s name: %s', alert.index, new_name)
try:
torrent_id = str(alert.handle.info_hash())
torrent = self.torrents[torrent_id]
@@ -1224,12 +1224,12 @@ class TorrentManager(component.Component):
break
else:
# This is just a regular file rename so send the signal
- component.get("EventManager").emit(TorrentFileRenamedEvent(torrent_id, alert.index, new_name))
+ component.get('EventManager').emit(TorrentFileRenamedEvent(torrent_id, alert.index, new_name))
self.save_resume_data((torrent_id,))
def on_alert_metadata_received(self, alert):
"""Alert handler for libtorrent metadata_received_alert"""
- log.debug("on_alert_metadata_received")
+ log.debug('on_alert_metadata_received')
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
@@ -1238,7 +1238,7 @@ class TorrentManager(component.Component):
def on_alert_file_error(self, alert):
"""Alert handler for libtorrent file_error_alert"""
- log.debug("on_alert_file_error: %s", decode_string(alert.message()))
+ log.debug('on_alert_file_error: %s', decode_string(alert.message()))
try:
torrent = self.torrents[str(alert.handle.info_hash())]
except (RuntimeError, KeyError):
@@ -1252,13 +1252,13 @@ class TorrentManager(component.Component):
TorrentFileCompletedEvent: When an individual file completes downloading.
"""
- log.debug("file_completed_alert: %s", decode_string(alert.message()))
+ log.debug('file_completed_alert: %s', decode_string(alert.message()))
try:
torrent_id = str(alert.handle.info_hash())
except RuntimeError:
return
if torrent_id in self.torrents:
- component.get("EventManager").emit(TorrentFileCompletedEvent(torrent_id, alert.index))
+ component.get('EventManager').emit(TorrentFileCompletedEvent(torrent_id, alert.index))
def on_alert_state_update(self, alert):
"""Alert handler for libtorrent state_update_alert
@@ -1267,7 +1267,7 @@ class TorrentManager(component.Component):
of all torrents that changed since last time this was posted.
"""
- log.debug("on_status_notification: %s", decode_string(alert.message()))
+ log.debug('on_status_notification: %s', decode_string(alert.message()))
self.last_state_update_alert_ts = time.time()
for t_status in alert.status:
@@ -1291,24 +1291,24 @@ class TorrentManager(component.Component):
"""
external_ip = decode_string(alert.message()).split(' ')[-1]
- log.info("on_alert_external_ip: %s", external_ip)
- component.get("EventManager").emit(ExternalIPEvent(external_ip))
+ log.info('on_alert_external_ip: %s', external_ip)
+ component.get('EventManager').emit(ExternalIPEvent(external_ip))
def on_alert_performance(self, alert):
"""Alert handler for libtorrent performance_alert"""
- log.warning("on_alert_performance: %s, %s", decode_string(alert.message()), alert.warning_code)
+ log.warning('on_alert_performance: %s, %s', decode_string(alert.message()), alert.warning_code)
if alert.warning_code == lt.performance_warning_t.send_buffer_watermark_too_low:
max_send_buffer_watermark = 3 * 1024 * 1024 # 3MiB
settings = self.session.get_settings()
- send_buffer_watermark = settings["send_buffer_watermark"]
+ send_buffer_watermark = settings['send_buffer_watermark']
# If send buffer is too small, try increasing its size by 512KiB (up to max_send_buffer_watermark)
if send_buffer_watermark < max_send_buffer_watermark:
value = send_buffer_watermark + (500 * 1024)
- log.info("Increasing send_buffer_watermark from %s to %s Bytes", send_buffer_watermark, value)
- component.get("Core").apply_session_setting("send_buffer_watermark", value)
+ log.info('Increasing send_buffer_watermark from %s to %s Bytes', send_buffer_watermark, value)
+ component.get('Core').apply_session_setting('send_buffer_watermark', value)
else:
- log.warning("send_buffer_watermark reached maximum value: %s Bytes", max_send_buffer_watermark)
+ log.warning('send_buffer_watermark reached maximum value: %s Bytes', max_send_buffer_watermark)
def separate_keys(self, keys, torrent_ids):
"""Separates the input keys into torrent class keys and plugins keys"""
diff --git a/deluge/decorators.py b/deluge/decorators.py
index 002d465de..d954b300f 100644
--- a/deluge/decorators.py
+++ b/deluge/decorators.py
@@ -89,7 +89,7 @@ def _overrides(stack, method, explicit_base_classes=None):
if explicit_base_classes:
# One or more base classes are explicitly given, check only those classes
override_classes = re.search(r'\s*@overrides\((.+)\)\s*', stack[1][4][0]).group(1)
- override_classes = [c.strip() for c in override_classes.split(",")]
+ override_classes = [c.strip() for c in override_classes.split(',')]
check_classes = override_classes
for c in base_classes + check_classes:
@@ -108,9 +108,9 @@ def _overrides(stack, method, explicit_base_classes=None):
for cls in check_classes:
if not hasattr(classes[cls], method.__name__):
raise Exception("Function override '%s' not found in superclass: '%s'\n%s"
- % (method.__name__, cls, "File: %s:%s" % (stack[1][1], stack[1][2])))
+ % (method.__name__, cls, 'File: %s:%s' % (stack[1][1], stack[1][2])))
if not any(hasattr(classes[cls], method.__name__) for cls in check_classes):
raise Exception("Function override '%s' not found in any superclass: '%s'\n%s"
- % (method.__name__, check_classes, "File: %s:%s" % (stack[1][1], stack[1][2])))
+ % (method.__name__, check_classes, 'File: %s:%s' % (stack[1][1], stack[1][2])))
return method
diff --git a/deluge/error.py b/deluge/error.py
index f0fb6d80c..94b15e466 100644
--- a/deluge/error.py
+++ b/deluge/error.py
@@ -49,7 +49,7 @@ class WrappedException(DelugeError):
self.traceback = traceback
def __str__(self):
- return "%s\n%s" % (self.message, self.traceback)
+ return '%s\n%s' % (self.message, self.traceback)
class _ClientSideRecreateError(DelugeError):
@@ -60,8 +60,8 @@ 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" % \
+ msg = 'Your deluge client is not compatible with the daemon. '\
+ 'Please upgrade your client to %(daemon_version)s' % \
dict(daemon_version=self.daemon_version)
super(IncompatibleClient, self).__init__(message=msg)
@@ -69,7 +69,7 @@ class IncompatibleClient(_ClientSideRecreateError):
class NotAuthorizedError(_ClientSideRecreateError):
def __init__(self, current_level, required_level):
- msg = "Auth level too low: %(current_level)s < %(required_level)s" % \
+ msg = 'Auth level too low: %(current_level)s < %(required_level)s' % \
dict(current_level=current_level, required_level=required_level)
super(NotAuthorizedError, self).__init__(message=msg)
self.current_level = current_level
diff --git a/deluge/event.py b/deluge/event.py
index 4a143266b..2701825b0 100644
--- a/deluge/event.py
+++ b/deluge/event.py
@@ -24,7 +24,7 @@ class DelugeEventMetaClass(type):
"""
def __init__(self, name, bases, dct): # pylint: disable=bad-mcs-method-argument
super(DelugeEventMetaClass, self).__init__(name, bases, dct)
- if name != "DelugeEvent":
+ if name != 'DelugeEvent':
known_events[name] = self
@@ -44,7 +44,7 @@ class DelugeEvent(object):
return self.__class__.__name__
def _get_args(self):
- if not hasattr(self, "_args"):
+ if not hasattr(self, '_args'):
return []
return self._args
diff --git a/deluge/httpdownloader.py b/deluge/httpdownloader.py
index b245c6121..5492100b9 100644
--- a/deluge/httpdownloader.py
+++ b/deluge/httpdownloader.py
@@ -49,7 +49,7 @@ class HTTPDownloader(client.HTTPDownloader):
self.force_filename = force_filename
self.allow_compression = allow_compression
self.code = None
- agent = "Deluge/%s (http://deluge-torrent.org)" % get_version()
+ agent = 'Deluge/%s (http://deluge-torrent.org)' % get_version()
client.HTTPDownloader.__init__(self, url, filename, headers=headers, agent=agent)
def gotStatus(self, version, status, message): # NOQA
@@ -58,19 +58,19 @@ class HTTPDownloader(client.HTTPDownloader):
def gotHeaders(self, headers): # NOQA
if self.code == http.OK:
- if "content-length" in headers:
- self.total_length = int(headers["content-length"][0])
+ if 'content-length' in headers:
+ self.total_length = int(headers['content-length'][0])
else:
self.total_length = 0
- if self.allow_compression and "content-encoding" in headers and \
- headers["content-encoding"][0] in ("gzip", "x-gzip", "deflate"):
+ if self.allow_compression and 'content-encoding' in headers and \
+ headers['content-encoding'][0] in ('gzip', 'x-gzip', 'deflate'):
# Adding 32 to the wbits enables gzip & zlib decoding (with automatic header detection)
# Adding 16 just enables gzip decoding (no zlib)
self.decoder = zlib.decompressobj(zlib.MAX_WBITS + 32)
- if "content-disposition" in headers and not self.force_filename:
- new_file_name = str(headers["content-disposition"][0]).split(";")[1].split("=")[1]
+ if 'content-disposition' in headers and not self.force_filename:
+ new_file_name = str(headers['content-disposition'][0]).split(';')[1].split('=')[1]
new_file_name = sanitise_filename(new_file_name)
new_file_name = os.path.join(os.path.split(self.value)[0], new_file_name)
@@ -79,14 +79,14 @@ class HTTPDownloader(client.HTTPDownloader):
fileext = os.path.splitext(new_file_name)[1]
while os.path.isfile(new_file_name):
# Increment filename if already exists
- new_file_name = "%s-%s%s" % (fileroot, count, fileext)
+ new_file_name = '%s-%s%s' % (fileroot, count, fileext)
count += 1
self.fileName = new_file_name
self.value = new_file_name
elif self.code in (http.MOVED_PERMANENTLY, http.FOUND, http.SEE_OTHER, http.TEMPORARY_REDIRECT):
- location = headers["location"][0]
+ location = headers['location'][0]
error = PageRedirect(self.code, location=location)
self.noPage(Failure(error))
@@ -133,7 +133,7 @@ def sanitise_filename(filename):
filename = os.path.basename(filename)
filename = filename.strip()
- if filename.startswith(".") or ";" in filename or "|" in filename:
+ if filename.startswith('.') or ';' in filename or '|' in filename:
# Dodgy server, log it
log.warning("Potentially malicious server: trying to write to file '%s'", filename)
@@ -172,11 +172,11 @@ def _download_file(url, filename, callback=None, headers=None, force_filename=Fa
if allow_compression:
if not headers:
headers = {}
- headers["accept-encoding"] = "deflate, gzip, x-gzip"
+ headers['accept-encoding'] = 'deflate, gzip, x-gzip'
# In Twisted 13.1.0 _parse() function replaced by _URI class.
# In Twisted 15.0.0 _URI class renamed to URI.
- if hasattr(client, "_parse"):
+ if hasattr(client, '_parse'):
scheme, host, port, dummy_path = client._parse(url)
else:
try:
@@ -190,7 +190,7 @@ def _download_file(url, filename, callback=None, headers=None, force_filename=Fa
port = uri.port
factory = HTTPDownloader(url, filename, callback, headers, force_filename, allow_compression)
- if scheme == "https":
+ if scheme == 'https':
from twisted.internet import ssl
# ClientTLSOptions in Twisted >= 14, see ticket #2765 for details on this addition.
try:
@@ -241,12 +241,12 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
"""
def on_download_success(result):
- log.debug("Download success!")
+ log.debug('Download success!')
return result
def on_download_fail(failure):
if failure.check(PageRedirect) and handle_redirects:
- new_url = urljoin(url, failure.getErrorMessage().split(" to ")[1])
+ 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)
diff --git a/deluge/log.py b/deluge/log.py
index d58600bea..d80c82a91 100644
--- a/deluge/log.py
+++ b/deluge/log.py
@@ -21,14 +21,14 @@ from twisted.python.log import PythonLoggingObserver
from deluge import common
-__all__ = ("setup_logger", "set_logger_level", "get_plugin_logger", "LOG")
+__all__ = ('setup_logger', 'set_logger_level', 'get_plugin_logger', 'LOG')
LoggingLoggerClass = logging.getLoggerClass()
-if "dev" in common.get_version():
- DEFAULT_LOGGING_FORMAT = "%%(asctime)s.%%(msecs)03.0f [%%(levelname)-8s][%%(name)-%ds:%%(lineno)-4d] %%(message)s"
+if 'dev' in common.get_version():
+ DEFAULT_LOGGING_FORMAT = '%%(asctime)s.%%(msecs)03.0f [%%(levelname)-8s][%%(name)-%ds:%%(lineno)-4d] %%(message)s'
else:
- DEFAULT_LOGGING_FORMAT = "%%(asctime)s [%%(levelname)-8s][%%(name)-%ds:%%(lineno)-4d] %%(message)s"
+ DEFAULT_LOGGING_FORMAT = '%%(asctime)s [%%(levelname)-8s][%%(name)-%ds:%%(lineno)-4d] %%(message)s'
MAX_LOGGER_NAME_LENGTH = 10
@@ -44,7 +44,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
@@ -83,12 +83,12 @@ class Logging(LoggingLoggerClass):
def findCaller(self): # NOQA
f = logging.currentframe().f_back
- rv = "(unknown file)", 0, "(unknown function)"
- while hasattr(f, "f_code"):
+ rv = '(unknown file)', 0, '(unknown function)'
+ 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)
@@ -96,18 +96,18 @@ class Logging(LoggingLoggerClass):
return rv
levels = {
- "info": logging.INFO,
- "warn": logging.WARNING,
- "warning": logging.WARNING,
- "error": logging.ERROR,
- "none": logging.CRITICAL,
- "debug": logging.DEBUG,
- "trace": 5,
- "garbage": 1
+ 'info': logging.INFO,
+ 'warn': logging.WARNING,
+ 'warning': logging.WARNING,
+ 'error': logging.ERROR,
+ 'none': logging.CRITICAL,
+ 'debug': logging.DEBUG,
+ 'trace': 5,
+ 'garbage': 1
}
-def setup_logger(level="error", filename=None, filemode="w", logrotate=None,
+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
@@ -125,8 +125,8 @@ def setup_logger(level="error", filename=None, filemode="w", logrotate=None,
"""
if logging.getLoggerClass() is not Logging:
logging.setLoggerClass(Logging)
- logging.addLevelName(5, "TRACE")
- logging.addLevelName(1, "GARBAGE")
+ logging.addLevelName(5, 'TRACE')
+ logging.addLevelName(1, 'GARBAGE')
level = levels.get(level, logging.ERROR)
@@ -135,13 +135,13 @@ 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":
+ elif filename and filemode == 'w':
handler_cls = logging.FileHandler
if not common.windows_check():
- handler_cls = getattr(logging.handlers, "WatchedFileHandler", logging.FileHandler)
- handler = handler_cls(filename, mode=filemode, encoding="utf-8")
+ handler_cls = getattr(logging.handlers, 'WatchedFileHandler', logging.FileHandler)
+ handler = handler_cls(filename, mode=filemode, encoding='utf-8')
else:
handler = logging.StreamHandler(stream=output_stream)
@@ -149,7 +149,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)
@@ -182,9 +182,9 @@ class TwistedLoggingObserver(PythonLoggingObserver):
def emit(self, event_dict):
log = logging.getLogger(__name__)
- if "log_failure" in event_dict:
- fmt = "%(log_namespace)s \n%(log_failure)s"
- getattr(LoggingLoggerClass, event_dict["log_level"].name)(log, fmt % (event_dict))
+ if 'log_failure' in event_dict:
+ fmt = '%(log_namespace)s \n%(log_failure)s'
+ getattr(LoggingLoggerClass, event_dict['log_level'].name)(log, fmt % (event_dict))
else:
PythonLoggingObserver.emit(self, event_dict)
@@ -208,17 +208,17 @@ def tweak_logging_levels():
the command line.
"""
from deluge import configmanager
- logging_config_file = os.path.join(configmanager.get_config_dir(), "logging.conf")
+ logging_config_file = os.path.join(configmanager.get_config_dir(), 'logging.conf')
if not os.path.isfile(logging_config_file):
return
log = logging.getLogger(__name__)
- log.warn("logging.conf found! tweaking logging levels from %s",
+ log.warn('logging.conf found! tweaking logging levels from %s',
logging_config_file)
- with open(logging_config_file, "r") as _file:
+ with open(logging_config_file, 'r') as _file:
for line in _file:
- if line.strip().startswith("#"):
+ if line.strip().startswith('#'):
continue
- name, level = line.strip().split(":")
+ name, level = line.strip().split(':')
if level not in levels:
continue
@@ -236,7 +236,7 @@ def set_logger_level(level, logger_name=None):
tweak the root logger level.
"""
- logging.getLogger(logger_name).setLevel(levels.get(level, "error"))
+ logging.getLogger(logger_name).setLevel(levels.get(level, 'error'))
def get_plugin_logger(logger_name):
@@ -246,14 +246,14 @@ def get_plugin_logger(logger_name):
module_stack = stack.pop(0) # The module that called the log function
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__", "")
+ caller_module_name = getattr(caller_module, '__name__', '')
warnings.warn_explicit(DEPRECATION_WARNING, DeprecationWarning,
module_stack[1], module_stack[2],
caller_module_name)
- if "deluge.plugins." in logger_name:
+ if 'deluge.plugins.' in logger_name:
return logging.getLogger(logger_name)
- return logging.getLogger("deluge.plugin.%s" % logger_name)
+ return logging.getLogger('deluge.plugin.%s' % logger_name)
DEPRECATION_WARNING = """You seem to be using old style logging on your code, ie:
@@ -282,13 +282,13 @@ Triggering code:"""
class _BackwardsCompatibleLOG(object):
def __getattribute__(self, name):
import warnings
- logger_name = "deluge"
+ logger_name = 'deluge'
stack = inspect.stack()
stack.pop(0) # The logging call from this module
module_stack = stack.pop(0) # The module that called the log function
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__", "")
+ caller_module_name = getattr(caller_module, '__name__', '')
warnings.warn_explicit(DEPRECATION_WARNING, DeprecationWarning,
module_stack[1], module_stack[2],
caller_module_name)
@@ -297,16 +297,16 @@ class _BackwardsCompatibleLOG(object):
module = inspect.getmodule(member[0])
if not module:
continue
- if module.__name__ in ("deluge.plugins.pluginbase",
- "deluge.plugins.init"):
- logger_name += ".plugin.%s" % caller_module_name
+ 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)
break
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 9ad03175b..20d4482fc 100644
--- a/deluge/maketorrent.py
+++ b/deluge/maketorrent.py
@@ -46,7 +46,7 @@ class TorrentMetadata(object):
def __init__(self):
self.__data_path = None
self.__piece_size = 0
- self.__comment = ""
+ self.__comment = ''
self.__private = False
self.__trackers = []
self.__webseeds = []
@@ -65,37 +65,37 @@ class TorrentMetadata(object):
"""
if not self.data_path:
- raise InvalidPath("Need to set a data_path!")
+ raise InvalidPath('Need to set a data_path!')
torrent = {
- "info": {}
+ 'info': {}
}
if self.comment:
- torrent["comment"] = self.comment.encode("UTF-8")
+ torrent['comment'] = self.comment.encode('UTF-8')
if self.private:
- torrent["info"]["private"] = True
+ torrent['info']['private'] = True
if self.trackers:
- torrent["announce"] = self.trackers[0][0]
- torrent["announce-list"] = self.trackers
+ torrent['announce'] = self.trackers[0][0]
+ torrent['announce-list'] = self.trackers
else:
- torrent["announce"] = ""
+ torrent['announce'] = ''
if self.webseeds:
httpseeds = []
webseeds = []
for w in self.webseeds:
- if w.endswith(".php"):
+ if w.endswith('.php'):
httpseeds.append(w)
else:
webseeds.append(w)
if httpseeds:
- torrent["httpseeds"] = httpseeds
+ torrent['httpseeds'] = httpseeds
if webseeds:
- torrent["url-list"] = webseeds
+ torrent['url-list'] = webseeds
datasize = get_path_size(self.data_path)
@@ -112,11 +112,11 @@ class TorrentMetadata(object):
if datasize % piece_size:
num_pieces += 1
- torrent["info"]["piece length"] = piece_size
+ torrent['info']['piece length'] = piece_size
# Create the info
if os.path.isdir(self.data_path):
- torrent["info"]["name"] = os.path.split(self.data_path)[1]
+ torrent['info']['name'] = os.path.split(self.data_path)[1]
files = []
padding_count = 0
# Collect a list of file paths and add padding files if necessary
@@ -124,8 +124,8 @@ class TorrentMetadata(object):
for index, filename in enumerate(filenames):
size = get_path_size(os.path.join(self.data_path, dirpath, filename))
p = dirpath[len(self.data_path):]
- p = p.lstrip("/")
- p = p.split("/")
+ p = p.lstrip('/')
+ p = p.split('/')
if p[0]:
p += [filename]
else:
@@ -136,7 +136,7 @@ class TorrentMetadata(object):
left = size % piece_size
if left:
p = list(p)
- p[-1] = "_____padding_file_" + str(padding_count)
+ p[-1] = '_____padding_file_' + str(padding_count)
files.append((piece_size - left, p))
padding_count += 1
@@ -147,17 +147,17 @@ class TorrentMetadata(object):
fs = []
pieces = []
# Create the piece hashes
- buf = ""
+ buf = ''
for size, path in files:
- path = [s.decode(sys.getfilesystemencoding()).encode("UTF-8") for s in path]
- fs.append({"length": size, "path": path})
- if path[-1].startswith("_____padding_file_"):
- buf += "\0" * size
+ path = [s.decode(sys.getfilesystemencoding()).encode('UTF-8') for s in path]
+ fs.append({'length': size, 'path': path})
+ if path[-1].startswith('_____padding_file_'):
+ buf += '\0' * size
pieces.append(sha(buf).digest())
- buf = ""
- fs[-1]["attr"] = "p"
+ buf = ''
+ fs[-1]['attr'] = 'p'
else:
- with open(os.path.join(self.data_path, *path), "rb") as _file:
+ with open(os.path.join(self.data_path, *path), 'rb') as _file:
r = _file.read(piece_size - len(buf))
while r:
buf += r
@@ -166,7 +166,7 @@ class TorrentMetadata(object):
# Run the progress function if necessary
if progress:
progress(len(pieces), num_pieces)
- buf = ""
+ buf = ''
else:
break
r = _file.read(piece_size - len(buf))
@@ -175,17 +175,17 @@ class TorrentMetadata(object):
pieces.append(sha(buf).digest())
if progress:
progress(len(pieces), num_pieces)
- buf = ""
+ buf = ''
- torrent["info"]["pieces"] = "".join(pieces)
- torrent["info"]["files"] = fs
+ torrent['info']['pieces'] = ''.join(pieces)
+ torrent['info']['files'] = fs
elif os.path.isfile(self.data_path):
- torrent["info"]["name"] = os.path.split(self.data_path)[1]
- torrent["info"]["length"] = get_path_size(self.data_path)
+ torrent['info']['name'] = os.path.split(self.data_path)[1]
+ torrent['info']['length'] = get_path_size(self.data_path)
pieces = []
- with open(self.data_path, "rb") as _file:
+ with open(self.data_path, 'rb') as _file:
r = _file.read(piece_size)
while r:
pieces.append(sha(r).digest())
@@ -194,10 +194,10 @@ class TorrentMetadata(object):
r = _file.read(piece_size)
- torrent["info"]["pieces"] = "".join(pieces)
+ torrent['info']['pieces'] = ''.join(pieces)
# Write out the torrent file
- with open(torrent_path, "wb") as _file:
+ with open(torrent_path, 'wb') as _file:
_file.write(bencode(torrent))
def get_data_path(self):
@@ -228,7 +228,7 @@ class TorrentMetadata(object):
if os.path.exists(path) and (os.path.isdir(path) or os.path.isfile(path)):
self.__data_path = os.path.abspath(path)
else:
- raise InvalidPath("No such file or directory: %s" % path)
+ raise InvalidPath('No such file or directory: %s' % path)
def get_piece_size(self):
"""The size of the pieces.
@@ -254,7 +254,7 @@ class TorrentMetadata(object):
"""
if size % 16 and size:
- raise InvalidPieceSize("Piece size must be a multiple of 16 KiB")
+ raise InvalidPieceSize('Piece size must be a multiple of 16 KiB')
self.__piece_size = size
def get_comment(self):
diff --git a/deluge/metafile.py b/deluge/metafile.py
index 8586205cd..a77ff4739 100644
--- a/deluge/metafile.py
+++ b/deluge/metafile.py
@@ -47,10 +47,10 @@ def get_filesystem_encoding():
def decode_from_filesystem(path):
encoding = get_filesystem_encoding()
if encoding is None:
- assert isinstance(path, unicode), "Path should be unicode not %s" % type(path)
+ assert isinstance(path, unicode), 'Path should be unicode not %s' % type(path)
decoded_path = path
else:
- assert isinstance(path, str), "Path should be str not %s" % type(path)
+ assert isinstance(path, str), 'Path should be str not %s' % type(path)
decoded_path = path.decode(encoding)
return decoded_path
@@ -65,7 +65,7 @@ class RemoteFileProgress(object):
self.session_id = session_id
def __call__(self, piece_count, num_pieces):
- component.get("RPCServer").emit_event_for_session_id(
+ component.get('RPCServer').emit_event_for_session_id(
self.session_id, CreateTorrentProgressEvent(piece_count, num_pieces)
)
@@ -86,11 +86,11 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
f = target
if progress is None:
- session_id = component.get("RPCServer").get_session_id()
+ session_id = component.get('RPCServer').get_session_id()
if not session_id:
progress = dummy
else:
- progress = RemoteFileProgress(component.get("RPCServer").get_session_id())
+ progress = RemoteFileProgress(component.get('RPCServer').get_session_id())
info = makeinfo(path, piece_length, progress, name, content_type, private)
@@ -99,18 +99,18 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
data['info'] = info
if title:
- data['title'] = title.encode("utf8")
+ data['title'] = title.encode('utf8')
if comment:
- data['comment'] = comment.encode("utf8")
+ data['comment'] = comment.encode('utf8')
if safe:
- data['safe'] = safe.encode("utf8")
+ data['safe'] = safe.encode('utf8')
httpseeds = []
url_list = []
if webseeds:
for webseed in webseeds:
- if webseed.endswith(".php"):
+ if webseed.endswith('.php'):
httpseeds.append(webseed)
else:
url_list.append(webseed)
@@ -120,12 +120,12 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
if httpseeds:
data['httpseeds'] = httpseeds
if created_by:
- data['created by'] = created_by.encode("utf8")
+ data['created by'] = created_by.encode('utf8')
if trackers and (len(trackers[0]) > 1 or len(trackers) > 1):
data['announce-list'] = trackers
- data["encoding"] = "UTF-8"
+ data['encoding'] = 'UTF-8'
h.write(bencode(data))
h.close()
diff --git a/deluge/path_chooser_common.py b/deluge/path_chooser_common.py
index 8c0f0d54f..31a2664ce 100644
--- a/deluge/path_chooser_common.py
+++ b/deluge/path_chooser_common.py
@@ -41,9 +41,9 @@ def get_completion_paths(args):
:rtype: list
"""
- args["paths"] = []
- path_value = args["completion_text"]
- hidden_files = args["show_hidden_files"]
+ args['paths'] = []
+ path_value = args['completion_text']
+ hidden_files = args['show_hidden_files']
def get_subdirs(dirname):
try:
@@ -78,5 +78,5 @@ def get_completion_paths(args):
p += os.path.sep
matching_dirs.append(p)
- args["paths"] = sorted(matching_dirs)
+ args['paths'] = sorted(matching_dirs)
return args
diff --git a/deluge/pluginmanagerbase.py b/deluge/pluginmanagerbase.py
index 25f1d6e0d..549493cdd 100644
--- a/deluge/pluginmanagerbase.py
+++ b/deluge/pluginmanagerbase.py
@@ -24,15 +24,15 @@ import deluge.configmanager
log = logging.getLogger(__name__)
METADATA_KEYS = [
- "Name",
- "License",
- "Author",
- "Home-page",
- "Summary",
- "Platform",
- "Version",
- "Author-email",
- "Description",
+ 'Name',
+ 'License',
+ 'Author',
+ 'Home-page',
+ 'Summary',
+ 'Platform',
+ 'Version',
+ 'Author-email',
+ 'Description',
]
DEPRECATION_WARNING = """
@@ -50,13 +50,13 @@ class PluginManagerBase(object):
"""PluginManagerBase is a base class for PluginManagers to inherit"""
def __init__(self, config_file, entry_name):
- log.debug("Plugin manager init..")
+ log.debug('Plugin manager init..')
self.config = deluge.configmanager.ConfigManager(config_file)
# Create the plugins folder if it doesn't exist
- if not os.path.exists(os.path.join(deluge.configmanager.get_config_dir(), "plugins")):
- os.mkdir(os.path.join(deluge.configmanager.get_config_dir(), "plugins"))
+ if not os.path.exists(os.path.join(deluge.configmanager.get_config_dir(), 'plugins')):
+ os.mkdir(os.path.join(deluge.configmanager.get_config_dir(), 'plugins'))
# This is the entry we want to load..
self.entry_name = entry_name
@@ -69,7 +69,7 @@ class PluginManagerBase(object):
def enable_plugins(self):
# Load plugins that are enabled in the config.
- for name in self.config["enabled_plugins"]:
+ for name in self.config['enabled_plugins']:
self.enable_plugin(name)
def disable_plugins(self):
@@ -91,9 +91,9 @@ class PluginManagerBase(object):
def scan_for_plugins(self):
"""Scans for available plugins"""
- base_plugin_dir = deluge.common.resource_filename("deluge", "plugins")
+ base_plugin_dir = deluge.common.resource_filename('deluge', 'plugins')
pkg_resources.working_set.add_entry(base_plugin_dir)
- user_plugin_dir = os.path.join(deluge.configmanager.get_config_dir(), "plugins")
+ user_plugin_dir = os.path.join(deluge.configmanager.get_config_dir(), 'plugins')
plugins_dirs = [base_plugin_dir]
for dirname in os.listdir(base_plugin_dir):
@@ -107,7 +107,7 @@ class PluginManagerBase(object):
self.available_plugins = []
for name in self.pkg_env:
- log.debug("Found plugin: %s %s at %s",
+ 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)
@@ -125,14 +125,14 @@ class PluginManagerBase(object):
"""
if plugin_name not in self.available_plugins:
- log.warning("Cannot enable non-existant plugin %s", plugin_name)
+ log.warning('Cannot enable non-existant plugin %s', plugin_name)
return defer.succeed(False)
if plugin_name in self.plugins:
- log.warning("Cannot enable already enabled plugin %s", plugin_name)
+ log.warning('Cannot enable already enabled plugin %s', plugin_name)
return defer.succeed(True)
- plugin_name = plugin_name.replace(" ", "-")
+ plugin_name = plugin_name.replace(' ', '-')
egg = self.pkg_env[plugin_name][0]
egg.activate()
return_d = defer.succeed(True)
@@ -141,12 +141,12 @@ class PluginManagerBase(object):
entry_point = egg.get_entry_info(self.entry_name, name)
try:
cls = entry_point.load()
- instance = cls(plugin_name.replace("-", "_"))
+ instance = cls(plugin_name.replace('-', '_'))
except component.ComponentAlreadyRegistered as ex:
log.error(ex)
return defer.succeed(False)
except Exception as ex:
- log.error("Unable to instantiate plugin %r from %r!", name, egg.location)
+ log.error('Unable to instantiate plugin %r from %r!', name, egg.location)
log.exception(ex)
continue
try:
@@ -156,25 +156,25 @@ class PluginManagerBase(object):
log.exception(ex)
return_d = defer.fail(False)
- if not instance.__module__.startswith("deluge.plugins."):
+ if not instance.__module__.startswith('deluge.plugins.'):
import warnings
warnings.warn_explicit(
DEPRECATION_WARNING % name,
DeprecationWarning,
instance.__module__, 0
)
- if self._component_state == "Started":
+ if self._component_state == 'Started':
def on_enabled(result, instance):
return component.start([instance.plugin._component_name])
return_d.addCallback(on_enabled, instance)
def on_started(result, instance):
- plugin_name_space = plugin_name.replace("-", " ")
+ plugin_name_space = plugin_name.replace('-', ' ')
self.plugins[plugin_name_space] = instance
- if plugin_name_space not in self.config["enabled_plugins"]:
- log.debug("Adding %s to enabled_plugins list in config", plugin_name_space)
- self.config["enabled_plugins"].append(plugin_name_space)
- log.info("Plugin %s enabled..", plugin_name_space)
+ if plugin_name_space not in self.config['enabled_plugins']:
+ log.debug('Adding %s to enabled_plugins list in config', plugin_name_space)
+ self.config['enabled_plugins'].append(plugin_name_space)
+ log.info('Plugin %s enabled..', plugin_name_space)
return True
def on_started_error(result, instance):
@@ -218,13 +218,13 @@ class PluginManagerBase(object):
try:
component.deregister(self.plugins[name].plugin)
del self.plugins[name]
- self.config["enabled_plugins"].remove(name)
+ self.config['enabled_plugins'].remove(name)
except Exception as ex:
log.error("Unable to disable plugin '%s'!", name)
log.exception(ex)
ret = False
else:
- log.info("Plugin %s disabled..", name)
+ log.info('Plugin %s disabled..', name)
return ret
d.addBoth(on_disabled)
@@ -233,25 +233,25 @@ class PluginManagerBase(object):
def get_plugin_info(self, name):
"""Returns a dictionary of plugin info from the metadata"""
info = {}.fromkeys(METADATA_KEYS)
- last_header = ""
+ last_header = ''
cont_lines = []
# Missing plugin info
if not self.pkg_env[name]:
log.warn("Failed to retrive info for plugin '%s'", name)
for k in info:
- info[k] = "not available"
+ info[k] = 'not available'
return info
- for line in self.pkg_env[name][0].get_metadata("PKG-INFO").splitlines():
+ for line in self.pkg_env[name][0].get_metadata('PKG-INFO').splitlines():
if not line:
continue
- if line[0] in ' \t' and (len(line.split(":", 1)) == 1 or line.split(":", 1)[0] not in info.keys()):
+ if line[0] in ' \t' and (len(line.split(':', 1)) == 1 or line.split(':', 1)[0] not in info.keys()):
# This is a continuation
cont_lines.append(line.strip())
else:
if cont_lines:
- info[last_header] = "\n".join(cont_lines).strip()
+ info[last_header] = '\n'.join(cont_lines).strip()
cont_lines = []
- if line.split(":", 1)[0] in info.keys():
- last_header = line.split(":", 1)[0]
- info[last_header] = line.split(":", 1)[1].strip()
+ if line.split(':', 1)[0] in info.keys():
+ last_header = line.split(':', 1)[0]
+ info[last_header] = line.split(':', 1)[1].strip()
return info
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/common.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/common.py
index 8053d53bb..bae33ab2a 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/common.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/common.py
@@ -18,4 +18,4 @@ import pkg_resources
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.autoadd", os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.autoadd', os.path.join('data', filename))
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
index 8902dd018..5427e7afe 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/core.py
@@ -33,35 +33,35 @@ log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "watchdirs": {},
- "next_id": 1
+ 'watchdirs': {},
+ 'next_id': 1
}
OPTIONS_AVAILABLE = { # option: builtin
- "enabled": False,
- "path": False,
- "append_extension": False,
- "copy_torrent": False,
- "delete_copy_torrent_toggle": False,
- "abspath": False,
- "download_location": True,
- "max_download_speed": True,
- "max_upload_speed": True,
- "max_connections": True,
- "max_upload_slots": True,
- "prioritize_first_last": True,
- "auto_managed": True,
- "stop_at_ratio": True,
- "stop_ratio": True,
- "remove_at_ratio": True,
- "move_completed": True,
- "move_completed_path": True,
- "label": False,
- "add_paused": True,
- "queue_to_top": False,
- "owner": True,
- "seed_mode": True
+ 'enabled': False,
+ 'path': False,
+ 'append_extension': False,
+ 'copy_torrent': False,
+ 'delete_copy_torrent_toggle': False,
+ 'abspath': False,
+ 'download_location': True,
+ 'max_download_speed': True,
+ 'max_upload_speed': True,
+ 'max_connections': True,
+ 'max_upload_slots': True,
+ 'prioritize_first_last': True,
+ 'auto_managed': True,
+ 'stop_at_ratio': True,
+ 'stop_ratio': True,
+ 'remove_at_ratio': True,
+ 'move_completed': True,
+ 'move_completed_path': True,
+ 'label': False,
+ 'add_paused': True,
+ 'queue_to_top': False,
+ 'owner': True,
+ 'seed_mode': True
}
MAX_NUM_ATTEMPTS = 10
@@ -82,13 +82,13 @@ class Core(CorePluginBase):
def enable(self):
# reduce typing, assigning some values to self...
- self.config = deluge.configmanager.ConfigManager("autoadd.conf", DEFAULT_PREFS)
+ self.config = deluge.configmanager.ConfigManager('autoadd.conf', DEFAULT_PREFS)
self.config.run_converter((0, 1), 2, self.__migrate_config_1_to_2)
self.config.save()
- self.watchdirs = self.config["watchdirs"]
+ self.watchdirs = self.config['watchdirs']
- component.get("EventManager").register_event_handler(
- "PreTorrentRemovedEvent", self.__on_pre_torrent_removed
+ component.get('EventManager').register_event_handler(
+ 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed
)
# Dict of Filename:Attempts
@@ -100,13 +100,13 @@ class Core(CorePluginBase):
def enable_looping(self):
# Enable all looping calls for enabled watchdirs here
for watchdir_id, watchdir in self.watchdirs.iteritems():
- if watchdir["enabled"]:
+ if watchdir['enabled']:
self.enable_watchdir(watchdir_id)
def disable(self):
# disable all running looping calls
- component.get("EventManager").deregister_event_handler(
- "PreTorrentRemovedEvent", self.__on_pre_torrent_removed
+ component.get('EventManager').deregister_event_handler(
+ 'PreTorrentRemovedEvent', self.__on_pre_torrent_removed
)
for loopingcall in self.update_timers.itervalues():
loopingcall.stop()
@@ -121,45 +121,45 @@ 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"])
+ 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.iteritems():
- if options["abspath"] == w["abspath"] and watchdir_id != w_id:
- raise Exception("Path is already being watched.")
+ if options['abspath'] == w['abspath'] and watchdir_id != w_id:
+ raise Exception('Path is already being watched.')
for key in options:
if key not in OPTIONS_AVAILABLE:
- if key not in [key2 + "_toggle" for key2 in OPTIONS_AVAILABLE.iterkeys()]:
- raise Exception("autoadd: Invalid options key:%s" % key)
+ if key not in [key2 + '_toggle' for key2 in OPTIONS_AVAILABLE.iterkeys()]:
+ raise Exception('autoadd: Invalid options key:%s' % key)
# disable the watch loop if it was active
if watchdir_id in self.update_timers:
self.disable_watchdir(watchdir_id)
self.watchdirs[watchdir_id].update(options)
# re-enable watch loop if appropriate
- if self.watchdirs[watchdir_id]["enabled"]:
+ if self.watchdirs[watchdir_id]['enabled']:
self.enable_watchdir(watchdir_id)
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
def load_torrent(self, filename, magnet):
try:
- log.debug("Attempting to open %s for add.", filename)
+ log.debug('Attempting to open %s for add.', filename)
if magnet:
- with open(filename, "r") as _file:
+ with open(filename, 'r') as _file:
filedump = _file.read()
else:
- with open(filename, "rb") as _file:
+ with open(filename, 'rb') as _file:
filedump = _file.read()
if not filedump:
- raise RuntimeError("Torrent is 0 bytes!")
+ raise RuntimeError('Torrent is 0 bytes!')
except IOError as ex:
- log.warning("Unable to open %s: %s", filename, ex)
+ log.warning('Unable to open %s: %s', filename, ex)
raise ex
# Get the info to see if any exceptions are raised
@@ -169,16 +169,16 @@ class Core(CorePluginBase):
return base64.encodestring(filedump)
def split_magnets(self, filename):
- log.debug("Attempting to open %s for splitting magnets.", filename)
+ log.debug('Attempting to open %s for splitting magnets.', filename)
magnets = []
try:
- with open(filename, "r") as _file:
+ with open(filename, 'r') as _file:
for line in _file:
line = line.strip()
if line:
magnets.append(line)
except IOError as ex:
- log.warning("Unable to open %s: %s", filename, ex)
+ log.warning('Unable to open %s: %s', filename, ex)
if len(magnets) < 2:
return []
@@ -186,79 +186,79 @@ class Core(CorePluginBase):
n = 0
path = filename.rsplit(os.sep, 1)[0]
for magnet in magnets:
- for part in magnet.split("&"):
- if part.startswith("dn="):
- mname = os.sep.join([path, part[3:] + ".magnet"])
+ for part in magnet.split('&'):
+ if part.startswith('dn='):
+ mname = os.sep.join([path, part[3:] + '.magnet'])
break
else:
- mname = ".".join([filename, str(n), "magnet"])
+ mname = '.'.join([filename, str(n), 'magnet'])
n += 1
try:
- with open(mname, "w") as _mfile:
+ with open(mname, 'w') as _mfile:
_mfile.write(magnet)
except IOError as ex:
- log.warning("Unable to open %s: %s", mname, ex)
+ log.warning('Unable to open %s: %s', mname, ex)
return magnets
def update_watchdir(self, watchdir_id):
"""Check the watch folder for new torrents to add."""
- log.trace("Updating watchdir id: %s", watchdir_id)
+ log.trace('Updating watchdir id: %s', watchdir_id)
watchdir_id = str(watchdir_id)
watchdir = self.watchdirs[watchdir_id]
- if not watchdir["enabled"]:
+ 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.",
+ log.debug('Watchdir id %s is not enabled. Disabling it.',
watchdir_id)
self.disable_watchdir(watchdir_id)
return
- if not os.path.isdir(watchdir["abspath"]):
- log.warning("Invalid AutoAdd folder: %s", watchdir["abspath"])
+ if not os.path.isdir(watchdir['abspath']):
+ log.warning('Invalid AutoAdd folder: %s', watchdir['abspath'])
self.disable_watchdir(watchdir_id)
return
# Generate options dict for watchdir
opts = {}
- if "stop_at_ratio_toggle" in watchdir:
- watchdir["stop_ratio_toggle"] = watchdir["stop_at_ratio_toggle"]
+ if 'stop_at_ratio_toggle' in watchdir:
+ watchdir['stop_ratio_toggle'] = watchdir['stop_at_ratio_toggle']
# We default to True when reading _toggle values, so a config
# without them is valid, and applies all its settings.
for option, value in watchdir.iteritems():
if OPTIONS_AVAILABLE.get(option):
- if watchdir.get(option + "_toggle", True) or option in ["owner", "seed_mode"]:
+ if watchdir.get(option + '_toggle', True) or option in ['owner', 'seed_mode']:
opts[option] = value
# Check for .magnet files containing multiple magnet links and
# create a new .magnet file for each of them.
- for filename in os.listdir(watchdir["abspath"]):
+ for filename in os.listdir(watchdir['abspath']):
try:
- filepath = os.path.join(watchdir["abspath"], filename)
+ filepath = os.path.join(watchdir['abspath'], filename)
except UnicodeDecodeError as ex:
- log.error("Unable to auto add torrent due to improper filename encoding: %s", ex)
+ log.error('Unable to auto add torrent due to improper filename encoding: %s', ex)
continue
if os.path.isdir(filepath):
# Skip directories
continue
- elif os.path.splitext(filename)[1] == ".magnet" and self.split_magnets(filepath):
+ elif os.path.splitext(filename)[1] == '.magnet' and self.split_magnets(filepath):
os.remove(filepath)
- for filename in os.listdir(watchdir["abspath"]):
+ for filename in os.listdir(watchdir['abspath']):
try:
- filepath = os.path.join(watchdir["abspath"], filename)
+ filepath = os.path.join(watchdir['abspath'], filename)
except UnicodeDecodeError as ex:
- log.error("Unable to auto add torrent due to improper filename encoding: %s", ex)
+ log.error('Unable to auto add torrent due to improper filename encoding: %s', ex)
continue
if os.path.isdir(filepath):
# Skip directories
continue
else:
ext = os.path.splitext(filename)[1].lower()
- if ext == ".torrent":
+ if ext == '.torrent':
magnet = False
- elif ext == ".magnet":
+ elif ext == '.magnet':
magnet = True
else:
- log.debug("File checked for auto-loading is invalid: %s", filename)
+ log.debug('File checked for auto-loading is invalid: %s', filename)
continue
try:
filedump = self.load_torrent(filepath, magnet)
@@ -266,15 +266,15 @@ class Core(CorePluginBase):
# If the torrent is invalid, we keep track of it so that we
# can try again on the next pass. This is because some
# torrents may not be fully saved during the pass.
- log.debug("Torrent is invalid: %s", ex)
+ log.debug('Torrent is invalid: %s', ex)
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
+ 'Maximum attempts reached while trying to add the '
+ 'torrent file with the path %s', filepath
)
- os.rename(filepath, filepath + ".invalid")
+ os.rename(filepath, filepath + '.invalid')
del self.invalid_torrents[filename]
else:
self.invalid_torrents[filename] = 1
@@ -282,37 +282,37 @@ class Core(CorePluginBase):
# The torrent looks good, so lets add it to the session.
if magnet:
- torrent_id = component.get("Core").add_torrent_magnet(filedump, opts)
+ torrent_id = component.get('Core').add_torrent_magnet(filedump, opts)
else:
- torrent_id = component.get("Core").add_torrent_file(filename, filedump, opts)
+ torrent_id = component.get('Core').add_torrent_file(filename, filedump, opts)
# If the torrent added successfully, set the extra options.
if torrent_id:
- if "Label" in component.get("CorePluginManager").get_enabled_plugins():
- if watchdir.get("label_toggle", True) and watchdir.get("label"):
- label = component.get("CorePlugin.Label")
- if not watchdir["label"] in label.get_labels():
- label.add(watchdir["label"])
- label.set_torrent(torrent_id, watchdir["label"])
- if watchdir.get("queue_to_top_toggle", True) and "queue_to_top" in watchdir:
- if watchdir["queue_to_top"]:
- component.get("TorrentManager").queue_top(torrent_id)
+ if 'Label' in component.get('CorePluginManager').get_enabled_plugins():
+ if watchdir.get('label_toggle', True) and watchdir.get('label'):
+ label = component.get('CorePlugin.Label')
+ if not watchdir['label'] in label.get_labels():
+ label.add(watchdir['label'])
+ label.set_torrent(torrent_id, watchdir['label'])
+ if watchdir.get('queue_to_top_toggle', True) and 'queue_to_top' in watchdir:
+ if watchdir['queue_to_top']:
+ component.get('TorrentManager').queue_top(torrent_id)
else:
- component.get("TorrentManager").queue_bottom(torrent_id)
+ component.get('TorrentManager').queue_bottom(torrent_id)
else:
# torrent handle is invalid and so is the magnet link
if magnet:
- log.debug("invalid magnet link")
- os.rename(filepath, filepath + ".invalid")
+ log.debug('invalid magnet link')
+ os.rename(filepath, filepath + '.invalid')
continue
# Rename, copy or delete the torrent once added to deluge.
- if watchdir.get("append_extension_toggle"):
- if not watchdir.get("append_extension"):
- watchdir["append_extension"] = ".added"
- os.rename(filepath, filepath + watchdir["append_extension"])
- elif watchdir.get("copy_torrent_toggle"):
- copy_torrent_path = watchdir["copy_torrent"]
+ if watchdir.get('append_extension_toggle'):
+ if not watchdir.get('append_extension'):
+ watchdir['append_extension'] = '.added'
+ os.rename(filepath, filepath + watchdir['append_extension'])
+ 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)
@@ -325,7 +325,7 @@ class Core(CorePluginBase):
"""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)
+ self.watchdirs[watchdir_id]['path'], failure)
@export
def enable_watchdir(self, watchdir_id):
@@ -337,10 +337,10 @@ class Core(CorePluginBase):
self.on_update_watchdir_error, w_id
)
# Update the config
- if not self.watchdirs[w_id]["enabled"]:
- self.watchdirs[w_id]["enabled"] = True
+ if not self.watchdirs[w_id]['enabled']:
+ self.watchdirs[w_id]['enabled'] = True
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
@export
def disable_watchdir(self, watchdir_id):
@@ -351,10 +351,10 @@ class Core(CorePluginBase):
self.update_timers[w_id].stop()
del self.update_timers[w_id]
# Update the config
- if self.watchdirs[w_id]["enabled"]:
- self.watchdirs[w_id]["enabled"] = False
+ if self.watchdirs[w_id]['enabled']:
+ self.watchdirs[w_id]['enabled'] = False
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
@export
def set_config(self, config):
@@ -363,7 +363,7 @@ class Core(CorePluginBase):
for key in config:
self.config[key] = config[key]
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
@export
def get_config(self):
@@ -372,28 +372,28 @@ class Core(CorePluginBase):
@export
def get_watchdirs(self):
- rpcserver = component.get("RPCServer")
+ rpcserver = component.get('RPCServer')
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 = {}
for watchdir_id, watchdir in self.watchdirs.iteritems():
- if watchdir.get("owner", "localclient") == session_user:
+ if watchdir.get('owner', 'localclient') == session_user:
watchdirs[watchdir_id] = watchdir
- log.debug("Current logged in user %s is not an ADMIN, send only "
- "his watchdirs: %s", session_user, watchdirs.keys())
+ log.debug('Current logged in user %s is not an ADMIN, send only '
+ 'his watchdirs: %s', session_user, watchdirs.keys())
return watchdirs
def _make_unicode(self, options):
opts = {}
for key in options:
if isinstance(options[key], str):
- options[key] = unicode(options[key], "utf8")
+ options[key] = unicode(options[key], 'utf8')
opts[key] = options[key]
return opts
@@ -403,58 +403,58 @@ class Core(CorePluginBase):
if options is None:
options = {}
options = self._make_unicode(options)
- abswatchdir = os.path.abspath(options["path"])
- check_input(os.path.isdir(abswatchdir), _("Path does not exist."))
+ abswatchdir = os.path.abspath(options['path'])
+ 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.itervalues()]:
- raise Exception("Path is already being watched.")
- options.setdefault("enabled", False)
- options["abspath"] = abswatchdir
- watchdir_id = self.config["next_id"]
+ if abswatchdir in [wd['abspath'] for wd in self.watchdirs.itervalues()]:
+ raise Exception('Path is already being watched.')
+ options.setdefault('enabled', False)
+ options['abspath'] = abswatchdir
+ watchdir_id = self.config['next_id']
self.watchdirs[str(watchdir_id)] = options
- if options.get("enabled"):
+ if options.get('enabled'):
self.enable_watchdir(watchdir_id)
- self.config["next_id"] = watchdir_id + 1
+ self.config['next_id'] = watchdir_id + 1
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
return watchdir_id
@export
def remove(self, watchdir_id):
"""Remove a watch folder."""
watchdir_id = str(watchdir_id)
- check_input(watchdir_id in self.watchdirs, "Unknown Watchdir: %s" % self.watchdirs)
- if self.watchdirs[watchdir_id]["enabled"]:
+ check_input(watchdir_id in self.watchdirs, 'Unknown Watchdir: %s' % self.watchdirs)
+ if self.watchdirs[watchdir_id]['enabled']:
self.disable_watchdir(watchdir_id)
del self.watchdirs[watchdir_id]
self.config.save()
- component.get("EventManager").emit(AutoaddOptionsChangedEvent())
+ component.get('EventManager').emit(AutoaddOptionsChangedEvent())
def __migrate_config_1_to_2(self, config):
- for watchdir_id in config["watchdirs"].iterkeys():
- config["watchdirs"][watchdir_id]["owner"] = "localclient"
+ for watchdir_id in config['watchdirs'].iterkeys():
+ config['watchdirs'][watchdir_id]['owner'] = 'localclient'
return config
def __on_pre_torrent_removed(self, torrent_id):
try:
- torrent = component.get("TorrentManager")[torrent_id]
+ 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",
+ 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.itervalues():
- if not watchdir.get("copy_torrent_toggle", False):
+ if not watchdir.get('copy_torrent_toggle', False):
# This watchlist does copy torrents
continue
- elif not watchdir.get("delete_copy_torrent_toggle", False):
+ elif not watchdir.get('delete_copy_torrent_toggle', False):
# This watchlist is not set to delete finished torrents
continue
- copy_torrent_path = watchdir["copy_torrent"]
+ copy_torrent_path = watchdir['copy_torrent']
torrent_fname_path = os.path.join(copy_torrent_path, torrent_fname)
if os.path.isfile(torrent_fname_path):
try:
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
index 9a569ed73..96a769eef 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/gtkui.py
@@ -34,10 +34,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"]
+ 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']
def __init__(self):
self.accounts = gtk.ListStore(str)
@@ -47,16 +47,16 @@ class OptionsDialog(object):
def show(self, options=None, watchdir_id=None):
if options is None:
options = {}
- self.glade = gtk.glade.XML(get_resource("autoadd_options.glade"))
+ self.glade = gtk.glade.XML(get_resource('autoadd_options.glade'))
self.glade.signal_autoconnect({
- "on_opts_add": self.on_add,
- "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_opts_add': self.on_add,
+ '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
})
- self.dialog = self.glade.get_widget("options_dialog")
- self.dialog.set_transient_for(component.get("Preferences").pref_dialog)
+ self.dialog = self.glade.get_widget('options_dialog')
+ self.dialog.set_transient_for(component.get('Preferences').pref_dialog)
if watchdir_id:
# We have an existing watchdir_id, we are editing
@@ -108,10 +108,10 @@ class OptionsDialog(object):
for spin_id in self.spin_ids + self.spin_int_ids:
self.glade.get_widget(spin_id).set_value(options.get(spin_id, 0))
- self.glade.get_widget(spin_id + "_toggle").set_active(options.get(spin_id + "_toggle", False))
+ self.glade.get_widget(spin_id + '_toggle').set_active(options.get(spin_id + '_toggle', False))
for chk_id in self.chk_ids:
self.glade.get_widget(chk_id).set_active(bool(options.get(chk_id, True)))
- self.glade.get_widget(chk_id + "_toggle").set_active(options.get(chk_id + "_toggle", False))
+ self.glade.get_widget(chk_id + '_toggle').set_active(options.get(chk_id + '_toggle', False))
if not options.get('add_paused', True):
self.glade.get_widget('isnt_add_paused').set_active(True)
if not options.get('queue_to_top', True):
@@ -121,59 +121,59 @@ class OptionsDialog(object):
for field in ['move_completed_path', 'path', 'download_location',
'copy_torrent']:
if client.is_localhost():
- self.glade.get_widget(field + "_chooser").set_current_folder(
- options.get(field, os.path.expanduser("~"))
+ self.glade.get_widget(field + '_chooser').set_current_folder(
+ options.get(field, os.path.expanduser('~'))
)
- self.glade.get_widget(field + "_chooser").show()
- self.glade.get_widget(field + "_entry").hide()
+ self.glade.get_widget(field + '_chooser').show()
+ self.glade.get_widget(field + '_entry').hide()
else:
- self.glade.get_widget(field + "_entry").set_text(
- options.get(field, "")
+ self.glade.get_widget(field + '_entry').set_text(
+ options.get(field, '')
)
- self.glade.get_widget(field + "_entry").show()
- self.glade.get_widget(field + "_chooser").hide()
+ self.glade.get_widget(field + '_entry').show()
+ self.glade.get_widget(field + '_chooser').hide()
self.set_sensitive()
def on_core_config(config):
if client.is_localhost():
self.glade.get_widget('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"]):
+ if options.get('move_completed_toggle', config['move_completed']):
self.glade.get_widget('move_completed_toggle').set_active(True)
self.glade.get_widget('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"]):
+ if options.get('copy_torrent_toggle', config['copy_torrent_file']):
self.glade.get_widget('copy_torrent_toggle').set_active(True)
self.glade.get_widget('copy_torrent_chooser').set_current_folder(
- options.get('copy_torrent', config["torrentfiles_location"])
+ options.get('copy_torrent', config['torrentfiles_location'])
)
else:
self.glade.get_widget('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"]):
+ if options.get('move_completed_toggle', config['move_completed']):
self.glade.get_widget('move_completed_toggle').set_active(
options.get('move_completed_toggle', False)
)
self.glade.get_widget('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"]):
+ if options.get('copy_torrent_toggle', config['copy_torrent_file']):
self.glade.get_widget('copy_torrent_toggle').set_active(True)
self.glade.get_widget('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"]):
+ if options.get('delete_copy_torrent_toggle', config['del_copy_torrent_file']):
self.glade.get_widget('delete_copy_torrent_toggle').set_active(True)
if not options:
client.core.get_config().addCallback(on_core_config)
def on_accounts(accounts, owner):
- log.debug("Got Accounts")
+ log.debug('Got Accounts')
selected_iter = None
for account in accounts:
acc_iter = self.accounts.append()
@@ -185,14 +185,14 @@ class OptionsDialog(object):
self.glade.get_widget('OwnerCombobox').set_active_iter(selected_iter)
def on_accounts_failure(failure):
- log.debug("Failed to get accounts!!! %s", failure)
+ log.debug('Failed to get accounts!!! %s', failure)
acc_iter = self.accounts.append()
self.accounts.set_value(acc_iter, 0, client.get_auth_user())
self.glade.get_widget('OwnerCombobox').set_active(0)
self.glade.get_widget('OwnerCombobox').set_sensitive(False)
def on_labels(labels):
- log.debug("Got Labels: %s", labels)
+ log.debug('Got Labels: %s', labels)
for label in labels:
self.labels.set_value(self.labels.append(), 0, label)
label_widget = self.glade.get_widget('label')
@@ -228,10 +228,10 @@ class OptionsDialog(object):
'max_upload_slots', 'add_paused', 'auto_managed',
'stop_at_ratio', 'queue_to_top', 'copy_torrent']
for maintoggle in maintoggles:
- self.on_toggle_toggled(self.glade.get_widget(maintoggle + "_toggle"))
+ self.on_toggle_toggled(self.glade.get_widget(maintoggle + '_toggle'))
def on_toggle_toggled(self, tb):
- toggle = str(tb.name).replace("_toggle", "")
+ toggle = str(tb.name).replace('_toggle', '')
isactive = tb.get_active()
if toggle == 'download_location':
self.glade.get_widget('download_location_chooser').set_sensitive(isactive)
@@ -279,10 +279,10 @@ class OptionsDialog(object):
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()
+ dialogs.ErrorDialog(_('Incompatible Option'), str(ex), self.dialog).run()
def on_error_show(self, result):
- d = dialogs.ErrorDialog(_("Error"), result.value.exception_msg, self.dialog)
+ d = dialogs.ErrorDialog(_('Error'), result.value.exception_msg, self.dialog)
result.cleanFailure()
d.run()
@@ -294,7 +294,7 @@ class OptionsDialog(object):
options = self.generate_opts()
client.autoadd.add(options).addCallbacks(self.on_added, self.on_error_show)
except IncompatibleOption as ex:
- dialogs.ErrorDialog(_("Incompatible Option"), str(ex), self.dialog).run()
+ dialogs.ErrorDialog(_('Incompatible Option'), str(ex), self.dialog).run()
def on_cancel(self, event=None):
self.dialog.destroy()
@@ -332,13 +332,13 @@ class OptionsDialog(object):
for spin_id in self.spin_ids:
options[spin_id] = self.glade.get_widget(spin_id).get_value()
- options[spin_id + "_toggle"] = self.glade.get_widget(spin_id + "_toggle").get_active()
+ options[spin_id + '_toggle'] = self.glade.get_widget(spin_id + '_toggle').get_active()
for spin_int_id in self.spin_int_ids:
options[spin_int_id] = self.glade.get_widget(spin_int_id).get_value_as_int()
- options[spin_int_id + "_toggle"] = self.glade.get_widget(spin_int_id + "_toggle").get_active()
+ options[spin_int_id + '_toggle'] = self.glade.get_widget(spin_int_id + '_toggle').get_active()
for chk_id in self.chk_ids:
options[chk_id] = self.glade.get_widget(chk_id).get_active()
- options[chk_id + "_toggle"] = self.glade.get_widget(chk_id + "_toggle").get_active()
+ options[chk_id + '_toggle'] = self.glade.get_widget(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"
@@ -349,27 +349,27 @@ class OptionsDialog(object):
class GtkUI(GtkPluginBase):
def enable(self):
- self.glade = gtk.glade.XML(get_resource("config.glade"))
+ self.glade = gtk.glade.XML(get_resource('config.glade'))
self.glade.signal_autoconnect({
- "on_add_button_clicked": self.on_add_button_clicked,
- "on_edit_button_clicked": self.on_edit_button_clicked,
- "on_remove_button_clicked": self.on_remove_button_clicked
+ 'on_add_button_clicked': self.on_add_button_clicked,
+ 'on_edit_button_clicked': self.on_edit_button_clicked,
+ 'on_remove_button_clicked': self.on_remove_button_clicked
})
self.opts_dialog = OptionsDialog()
- component.get("PluginManager").register_hook(
- "on_apply_prefs", self.on_apply_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_show_prefs', self.on_show_prefs
)
client.register_event_handler(
- "AutoaddOptionsChangedEvent", self.on_options_changed_event
+ 'AutoaddOptionsChangedEvent', self.on_options_changed_event
)
self.watchdirs = {}
- vbox = self.glade.get_widget("watchdirs_vbox")
+ vbox = self.glade.get_widget('watchdirs_vbox')
sw = gtk.ScrolledWindow()
sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
@@ -379,24 +379,24 @@ class GtkUI(GtkPluginBase):
self.store = self.create_model()
self.treeView = gtk.TreeView(self.store)
- self.treeView.connect("cursor-changed", self.on_listitem_activated)
- self.treeView.connect("row-activated", self.on_edit_button_clicked)
+ self.treeView.connect('cursor-changed', self.on_listitem_activated)
+ self.treeView.connect('row-activated', self.on_edit_button_clicked)
self.treeView.set_rules_hint(True)
self.create_columns(self.treeView)
sw.add(self.treeView)
sw.show_all()
- component.get("Preferences").add_page(
- _("AutoAdd"), self.glade.get_widget("prefs_box")
+ component.get('Preferences').add_page(
+ _('AutoAdd'), self.glade.get_widget('prefs_box')
)
def disable(self):
- component.get("Preferences").remove_page(_("AutoAdd"))
- component.get("PluginManager").deregister_hook(
- "on_apply_prefs", self.on_apply_prefs
+ component.get('Preferences').remove_page(_('AutoAdd'))
+ 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_show_prefs', self.on_show_prefs
)
def create_model(self):
@@ -411,7 +411,7 @@ class GtkUI(GtkPluginBase):
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)
@@ -420,7 +420,7 @@ class GtkUI(GtkPluginBase):
treeview.set_tooltip_cell(tt, None, None, renderer_toggle)
renderertext = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Owner"), renderertext, text=2)
+ column = gtk.TreeViewColumn(_('Owner'), renderertext, text=2)
column.set_sort_column_id(2)
treeview.append_column(column)
tt2 = gtk.Tooltip()
@@ -428,7 +428,7 @@ class GtkUI(GtkPluginBase):
treeview.set_has_tooltip(True)
renderertext = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Path"), renderertext, text=3)
+ column = gtk.TreeViewColumn(_('Path'), renderertext, text=3)
column.set_sort_column_id(3)
treeview.append_column(column)
tt2 = gtk.Tooltip()
@@ -455,7 +455,7 @@ class GtkUI(GtkPluginBase):
tree, tree_id = self.treeView.get_selection().get_selected()
watchdir_id = str(self.store.get_value(tree_id, 0))
if watchdir_id:
- if col and col.get_title() == _("Active"):
+ if col and col.get_title() == _('Active'):
if self.watchdirs[watchdir_id]['enabled']:
client.autoadd.disable_watchdir(watchdir_id)
else:
@@ -473,7 +473,7 @@ class GtkUI(GtkPluginBase):
self.glade.get_widget('remove_button').set_sensitive(False)
def on_apply_prefs(self):
- log.debug("applying prefs for AutoAdd")
+ log.debug('applying prefs for AutoAdd')
for watchdir_id, watchdir in self.watchdirs.iteritems():
client.autoadd.set_options(watchdir_id, watchdir)
@@ -485,7 +485,7 @@ class GtkUI(GtkPluginBase):
def cb_get_config(self, watchdirs):
"""callback for on show_prefs"""
- log.trace("Got whatchdirs from core: %s", watchdirs)
+ log.trace('Got whatchdirs from core: %s', watchdirs)
self.watchdirs = watchdirs or {}
self.store.clear()
for watchdir_id, watchdir in self.watchdirs.iteritems():
diff --git a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/webui.py b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/webui.py
index c9a9e53a2..750bf007d 100644
--- a/deluge/plugins/AutoAdd/deluge/plugins/autoadd/webui.py
+++ b/deluge/plugins/AutoAdd/deluge/plugins/autoadd/webui.py
@@ -23,7 +23,7 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("autoadd.js")]
+ scripts = [get_resource('autoadd.js')]
def enable(self):
pass
diff --git a/deluge/plugins/AutoAdd/setup.py b/deluge/plugins/AutoAdd/setup.py
index 68f4bfd68..7d18adef6 100644
--- a/deluge/plugins/AutoAdd/setup.py
+++ b/deluge/plugins/AutoAdd/setup.py
@@ -15,15 +15,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "AutoAdd"
-__author__ = "Chase Sterling, Pedro Algarvio"
-__author_email__ = "chase.sterling@gmail.com, pedro@algarvio.me"
-__version__ = "1.05"
-__url__ = "http://dev.deluge-torrent.org/wiki/Plugins/AutoAdd"
-__license__ = "GPLv3"
-__description__ = "Monitors folders for .torrent files."
+__plugin_name__ = 'AutoAdd'
+__author__ = 'Chase Sterling, Pedro Algarvio'
+__author_email__ = 'chase.sterling@gmail.com, pedro@algarvio.me'
+__version__ = '1.05'
+__url__ = 'http://dev.deluge-torrent.org/wiki/Plugins/AutoAdd'
+__license__ = 'GPLv3'
+__description__ = 'Monitors folders for .torrent files.'
__long_description__ = """"""
-__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -35,7 +35,7 @@ setup(
license=__license__,
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
index b806cb53f..e9017060d 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/common.py
@@ -15,8 +15,8 @@ import pkg_resources
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.blocklist",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.blocklist',
+ os.path.join('data', filename))
def raises_errors_as(error):
@@ -56,7 +56,7 @@ def remove_zeros(ip):
000.000.000.003 -> 0.0.0.3
"""
- return ".".join([part.lstrip("0").zfill(1) for part in ip.split(".")])
+ return '.'.join([part.lstrip('0').zfill(1) for part in ip.split('.')])
class BadIP(Exception):
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
index edc5fca9e..84eb6840b 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/core.py
@@ -39,16 +39,16 @@ from .readers import ReaderParseError
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "url": "",
- "load_on_start": False,
- "check_after_days": 4,
- "list_compression": "",
- "list_type": "",
- "last_update": 0.0,
- "list_size": 0,
- "timeout": 180,
- "try_times": 3,
- "whitelisted": [],
+ 'url': '',
+ 'load_on_start': False,
+ 'check_after_days': 4,
+ 'list_compression': '',
+ 'list_type': '',
+ 'last_update': 0.0,
+ 'list_size': 0,
+ 'timeout': 180,
+ 'try_times': 3,
+ 'whitelisted': [],
}
# Constants
@@ -70,26 +70,26 @@ class Core(CorePluginBase):
self.num_blocked = 0
self.file_progress = 0.0
- self.core = component.get("Core")
- self.config = deluge.configmanager.ConfigManager("blocklist.conf", DEFAULT_PREFS)
- if "whitelisted" not in self.config:
- self.config["whitelisted"] = []
+ self.core = component.get('Core')
+ self.config = deluge.configmanager.ConfigManager('blocklist.conf', DEFAULT_PREFS)
+ if 'whitelisted' not in self.config:
+ self.config['whitelisted'] = []
- self.reader = create_reader(self.config["list_type"], self.config["list_compression"])
+ self.reader = create_reader(self.config['list_type'], self.config['list_compression'])
- if not isinstance(self.config["last_update"], float):
- self.config.config["last_update"] = 0.0
+ if not isinstance(self.config['last_update'], float):
+ self.config.config['last_update'] = 0.0
update_now = False
- if self.config["load_on_start"]:
+ if self.config['load_on_start']:
self.pause_session()
- if self.config["last_update"]:
- last_update = datetime.fromtimestamp(self.config["last_update"])
- check_period = timedelta(days=self.config["check_after_days"])
- if not self.config["last_update"] or last_update + check_period < datetime.now():
+ if self.config['last_update']:
+ last_update = datetime.fromtimestamp(self.config['last_update'])
+ check_period = timedelta(days=self.config['check_after_days'])
+ if not self.config['last_update'] or last_update + check_period < datetime.now():
update_now = True
else:
- d = self.import_list(deluge.configmanager.get_config_dir("blocklist.cache"))
+ d = self.import_list(deluge.configmanager.get_config_dir('blocklist.cache'))
d.addCallbacks(self.on_import_complete, self.on_import_error)
if self.need_to_resume_session:
d.addBoth(self.resume_session)
@@ -97,16 +97,16 @@ class Core(CorePluginBase):
# This function is called every 'check_after_days' days, to download
# and import a new list if needed.
self.update_timer = LoopingCall(self.check_import)
- if self.config["check_after_days"] > 0:
+ 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")
+ 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')
@@ -125,7 +125,7 @@ class Core(CorePluginBase):
Deferred: A Deferred which fires when the blocklist has been imported.
"""
- if not self.config["url"]:
+ if not self.config['url']:
return
# Reset variables
@@ -136,7 +136,7 @@ class Core(CorePluginBase):
self.up_to_date = False
if force:
self.reader = None
- self.is_url = is_url(self.config["url"])
+ self.is_url = is_url(self.config['url'])
# Start callback chain
if self.is_url:
@@ -144,7 +144,7 @@ class Core(CorePluginBase):
d.addCallbacks(self.on_download_complete, self.on_download_error)
d.addCallback(self.import_list)
else:
- d = self.import_list(self.config["url"])
+ d = self.import_list(self.config['url'])
d.addCallbacks(self.on_import_complete, self.on_import_error)
if self.need_to_resume_session:
d.addBoth(self.resume_session)
@@ -176,7 +176,7 @@ class Core(CorePluginBase):
update = set(config[key])
diff = saved.symmetric_difference(update)
if diff:
- log.debug("Whitelist changed. Updating...")
+ log.debug('Whitelist changed. Updating...')
added = update.intersection(diff)
removed = saved.intersection(diff)
if added:
@@ -187,10 +187,10 @@ class Core(CorePluginBase):
ip.address, ip.address, ALLOW_RANGE
)
saved.add(ip.address)
- log.debug("Added %s to whitelisted", ip)
+ log.debug('Added %s to whitelisted', ip)
self.num_whited += 1
except BadIP as ex:
- log.error("Bad IP: %s", ex)
+ log.error('Bad IP: %s', ex)
continue
if removed:
needs_blocklist_import = True
@@ -198,37 +198,37 @@ class Core(CorePluginBase):
try:
ip = IP.parse(ip)
saved.remove(ip.address)
- log.debug("Removed %s from whitelisted", ip)
+ log.debug('Removed %s from whitelisted', ip)
except BadIP as ex:
- log.error("Bad IP: %s", ex)
+ log.error('Bad IP: %s', ex)
continue
self.config[key] = list(saved)
continue
- elif key == "check_after_days":
+ elif key == 'check_after_days':
if self.config[key] != config[key]:
self.config[key] = config[key]
update_now = False
- if self.config["last_update"]:
- last_update = datetime.fromtimestamp(self.config["last_update"])
- check_period = timedelta(days=self.config["check_after_days"])
- if not self.config["last_update"] or last_update + check_period < datetime.now():
+ if self.config['last_update']:
+ last_update = datetime.fromtimestamp(self.config['last_update'])
+ check_period = timedelta(days=self.config['check_after_days'])
+ if not self.config['last_update'] or last_update + check_period < datetime.now():
update_now = True
if self.update_timer.running:
self.update_timer.stop()
- if self.config["check_after_days"] > 0:
+ 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 "
+ log.debug('IP addresses were removed from the whitelist. Since we '
"don't know if they were blocked before. Re-import "
- "current blocklist and re-add whitelisted.")
+ 'current blocklist and re-add whitelisted.')
self.has_imported = False
- d = self.import_list(deluge.configmanager.get_config_dir("blocklist.cache"))
+ d = self.import_list(deluge.configmanager.get_config_dir('blocklist.cache'))
d.addCallbacks(self.on_import_complete, self.on_import_error)
@export
@@ -241,23 +241,23 @@ class Core(CorePluginBase):
"""
status = {}
if self.is_downloading:
- status["state"] = "Downloading"
+ status['state'] = 'Downloading'
elif self.is_importing:
- status["state"] = "Importing"
+ status['state'] = 'Importing'
else:
- status["state"] = "Idle"
-
- status["up_to_date"] = self.up_to_date
- status["num_whited"] = self.num_whited
- status["num_blocked"] = self.num_blocked
- status["file_progress"] = self.file_progress
- status["file_url"] = self.config["url"]
- status["file_size"] = self.config["list_size"]
- status["file_date"] = self.config["last_update"]
- status["file_type"] = self.config["list_type"]
- status["whitelisted"] = self.config["whitelisted"]
- if self.config["list_compression"]:
- status["file_type"] += " (%s)" % self.config["list_compression"]
+ status['state'] = 'Idle'
+
+ status['up_to_date'] = self.up_to_date
+ status['num_whited'] = self.num_whited
+ status['num_blocked'] = self.num_blocked
+ status['file_progress'] = self.file_progress
+ status['file_url'] = self.config['url']
+ status['file_size'] = self.config['list_size']
+ status['file_date'] = self.config['last_update']
+ status['file_type'] = self.config['list_type']
+ status['whitelisted'] = self.config['whitelisted']
+ if self.config['list_compression']:
+ status['file_type'] += ' (%s)' % self.config['list_compression']
return status
####
@@ -272,9 +272,9 @@ class Core(CorePluginBase):
str: Path of blocklist.
"""
- log.debug("Updating blocklist info: %s", blocklist)
- self.config["last_update"] = time.time()
- self.config["list_size"] = os.path.getsize(blocklist)
+ log.debug('Updating blocklist info: %s', blocklist)
+ self.config['last_update'] = time.time()
+ self.config['list_size'] = os.path.getsize(blocklist)
self.filename = blocklist
return blocklist
@@ -299,20 +299,20 @@ class Core(CorePluginBase):
self.file_progress = fp
import socket
- socket.setdefaulttimeout(self.config["timeout"])
+ socket.setdefaulttimeout(self.config['timeout'])
if not url:
- url = self.config["url"]
+ url = self.config['url']
headers = {}
- if self.config["last_update"] and not self.force_download:
- headers['If-Modified-Since'] = formatdate(self.config["last_update"], usegmt=True)
+ if self.config['last_update'] and not self.force_download:
+ headers['If-Modified-Since'] = formatdate(self.config['last_update'], usegmt=True)
- log.debug("Attempting to download blocklist %s", url)
- log.debug("Sending headers: %s", headers)
+ log.debug('Attempting to download blocklist %s', url)
+ log.debug('Sending headers: %s', headers)
self.is_downloading = True
return download_file(
- url, deluge.configmanager.get_config_dir("blocklist.download"),
+ url, deluge.configmanager.get_config_dir('blocklist.download'),
on_retrieve_data, headers
)
@@ -326,7 +326,7 @@ class Core(CorePluginBase):
Deferred: a Deferred which fires when clean up is done.
"""
- log.debug("Blocklist download complete: %s", blocklist)
+ log.debug('Blocklist download complete: %s', blocklist)
self.is_downloading = False
return threads.deferToThread(self.update_info, blocklist)
@@ -345,21 +345,21 @@ class Core(CorePluginBase):
d = f
if f.check(error.PageRedirect):
# Handle redirect errors
- location = urljoin(self.config["url"], error_msg.split(" to ")[1])
- if "Moved Permanently" in error_msg:
- log.debug("Setting blocklist url to %s", location)
- self.config["url"] = location
+ location = urljoin(self.config['url'], error_msg.split(' to ')[1])
+ if 'Moved Permanently' in error_msg:
+ log.debug('Setting blocklist url to %s', location)
+ self.config['url'] = location
d = self.download_list(location)
d.addCallbacks(self.on_download_complete, self.on_download_error)
else:
- if "Not Modified" in error_msg:
- log.debug("Blocklist is up-to-date!")
+ if 'Not Modified' in error_msg:
+ log.debug('Blocklist is up-to-date!')
self.up_to_date = True
- blocklist = deluge.configmanager.get_config_dir("blocklist.cache")
+ blocklist = deluge.configmanager.get_config_dir('blocklist.cache')
d = threads.deferToThread(self.update_info, blocklist)
else:
- log.warning("Blocklist download failed: %s", error_msg)
- if self.failed_attempts < self.config["try_times"]:
+ log.warning('Blocklist download failed: %s', error_msg)
+ if self.failed_attempts < self.config['try_times']:
log.debug("Let's try again")
self.failed_attempts += 1
d = self.download_list()
@@ -376,7 +376,7 @@ class Core(CorePluginBase):
Deferred: A Deferred that fires when the blocklist has been imported.
"""
- log.trace("on import_list")
+ log.trace('on import_list')
def on_read_ip_range(start, end):
"""Add ip range to blocklist"""
@@ -388,19 +388,19 @@ class Core(CorePluginBase):
"""Add any whitelisted IP's and add the blocklist to session"""
# White listing happens last because the last rules added have
# priority
- log.info("Added %d ranges to ipfilter as blocked", self.num_blocked)
- for ip in self.config["whitelisted"]:
+ log.info('Added %d ranges to ipfilter as blocked', self.num_blocked)
+ for ip in self.config['whitelisted']:
ip = IP.parse(ip)
self.blocklist.add_rule(ip.address, ip.address, ALLOW_RANGE)
self.num_whited += 1
- log.trace("Added %s to the ipfiler as white-listed", ip.address)
- log.info("Added %d ranges to ipfilter as white-listed", self.num_whited)
+ log.trace('Added %s to the ipfiler as white-listed', ip.address)
+ log.info('Added %d ranges to ipfilter as white-listed', self.num_whited)
self.core.session.set_ip_filter(self.blocklist)
return result
# TODO: double check logic
if self.up_to_date and self.has_imported:
- log.debug("Latest blocklist is already imported")
+ log.debug('Latest blocklist is already imported')
return defer.succeed(blocklist)
self.is_importing = True
@@ -416,12 +416,12 @@ class Core(CorePluginBase):
self.auto_detected = True
def on_reader_failure(failure):
- log.error("Failed to read!!!!!!")
+ log.error('Failed to read!!!!!!')
log.exception(failure)
- log.debug("Importing using reader: %s", self.reader)
- log.debug("Reader type: %s compression: %s", self.config["list_type"], self.config["list_compression"])
- log.debug("Clearing current ip filtering")
+ log.debug('Importing using reader: %s', self.reader)
+ log.debug('Reader type: %s compression: %s', self.config['list_type'], self.config['list_compression'])
+ log.debug('Clearing current ip filtering')
# self.blocklist.add_rule("0.0.0.0", "255.255.255.255", ALLOW_RANGE)
d = threads.deferToThread(self.reader(blocklist).read, on_read_ip_range)
d.addCallback(on_finish_read).addErrback(on_reader_failure)
@@ -438,18 +438,18 @@ class Core(CorePluginBase):
Deferred: A Deferred that fires when clean up is done.
"""
- log.trace("on_import_list_complete")
+ log.trace('on_import_list_complete')
d = blocklist
self.is_importing = False
self.has_imported = True
- log.debug("Blocklist import complete!")
- cache = deluge.configmanager.get_config_dir("blocklist.cache")
+ log.debug('Blocklist import complete!')
+ cache = deluge.configmanager.get_config_dir('blocklist.cache')
if blocklist != cache:
if self.is_url:
- log.debug("Moving %s to %s", blocklist, cache)
+ log.debug('Moving %s to %s', blocklist, cache)
d = threads.deferToThread(shutil.move, blocklist, cache)
else:
- log.debug("Copying %s to %s", blocklist, cache)
+ log.debug('Copying %s to %s', blocklist, cache)
d = threads.deferToThread(shutil.copy, blocklist, cache)
return d
@@ -463,21 +463,21 @@ class Core(CorePluginBase):
Deferred or Failure: A Deferred if recovery was possible else original Failure.
"""
- log.trace("on_import_error: %s", f)
+ log.trace('on_import_error: %s', f)
d = f
self.is_importing = False
try_again = False
- cache = deluge.configmanager.get_config_dir("blocklist.cache")
+ cache = deluge.configmanager.get_config_dir('blocklist.cache')
if f.check(ReaderParseError) and not self.auto_detected:
# Invalid / corrupt list, let's detect it
- log.warning("Invalid / corrupt blocklist")
+ log.warning('Invalid / corrupt blocklist')
self.reader = None
blocklist = None
try_again = True
elif self.filename != cache and os.path.exists(cache):
# If we have a backup and we haven't already used it
- log.warning("Error reading blocklist: %s", f.getErrorMessage())
+ log.warning('Error reading blocklist: %s', f.getErrorMessage())
blocklist = cache
try_again = True
@@ -497,14 +497,14 @@ class Core(CorePluginBase):
UnknownFormatError: If the format cannot be detected.
"""
- self.config["list_compression"] = detect_compression(blocklist)
- self.config["list_type"] = detect_format(blocklist, self.config["list_compression"])
- log.debug("Auto-detected type: %s compression: %s", self.config["list_type"], self.config["list_compression"])
- if not self.config["list_type"]:
- self.config["list_compression"] = ""
+ self.config['list_compression'] = detect_compression(blocklist)
+ self.config['list_type'] = detect_format(blocklist, self.config['list_compression'])
+ log.debug('Auto-detected type: %s compression: %s', self.config['list_type'], self.config['list_compression'])
+ if not self.config['list_type']:
+ self.config['list_compression'] = ''
raise UnknownFormatError
else:
- self.reader = create_reader(self.config["list_type"], self.config["list_compression"])
+ self.reader = create_reader(self.config['list_type'], self.config['list_compression'])
def pause_session(self):
self.need_to_resume_session = not self.core.session.is_paused()
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
index f39ac7b06..09de39dbc 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/detect.py
@@ -11,21 +11,21 @@ from .decompressers import BZipped2, GZipped, Zipped
from .readers import EmuleReader, PeerGuardianReader, SafePeerReader
COMPRESSION_TYPES = {
- "PK": "Zip",
- "\x1f\x8b": "GZip",
- "BZ": "BZip2"
+ 'PK': 'Zip',
+ '\x1f\x8b': 'GZip',
+ 'BZ': 'BZip2'
}
DECOMPRESSERS = {
- "Zip": Zipped,
- "GZip": GZipped,
- "BZip2": BZipped2
+ 'Zip': Zipped,
+ 'GZip': GZipped,
+ 'BZip2': BZipped2
}
READERS = {
- "Emule": EmuleReader,
- "SafePeer": SafePeerReader,
- "PeerGuardian": PeerGuardianReader
+ 'Emule': EmuleReader,
+ 'SafePeer': SafePeerReader,
+ 'PeerGuardian': PeerGuardianReader
}
@@ -34,13 +34,13 @@ class UnknownFormatError(Exception):
def detect_compression(filename):
- with open(filename, "rb") as _file:
+ with open(filename, 'rb') as _file:
magic_number = _file.read(2)
- return COMPRESSION_TYPES.get(magic_number, "")
+ return COMPRESSION_TYPES.get(magic_number, '')
-def detect_format(filename, compression=""):
- file_format = ""
+def detect_format(filename, compression=''):
+ file_format = ''
for reader in READERS:
if create_reader(reader, compression)(filename).is_valid():
file_format = reader
@@ -48,7 +48,7 @@ def detect_format(filename, compression=""):
return file_format
-def create_reader(file_format, compression=""):
+def create_reader(file_format, compression=''):
reader = READERS.get(file_format)
if reader and compression:
decompressor = DECOMPRESSERS.get(compression)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
index 9304112b8..c88f05d83 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/gtkui.py
@@ -25,102 +25,102 @@ log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
- log.debug("Blocklist GtkUI enable..")
- self.plugin = component.get("PluginManager")
+ log.debug('Blocklist GtkUI enable..')
+ self.plugin = component.get('PluginManager')
self.load_preferences_page()
- self.status_item = component.get("StatusBar").add_item(
- image=common.get_resource("blocklist16.png"),
- text="",
+ self.status_item = component.get('StatusBar').add_item(
+ 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
- self.plugin.register_hook("on_apply_prefs", self._on_apply_prefs)
- self.plugin.register_hook("on_show_prefs", self._on_show_prefs)
+ self.plugin.register_hook('on_apply_prefs', self._on_apply_prefs)
+ self.plugin.register_hook('on_show_prefs', self._on_show_prefs)
def disable(self):
- log.debug("Blocklist GtkUI disable..")
+ log.debug('Blocklist GtkUI disable..')
# Remove the preferences page
- self.plugin.remove_preferences_page(_("Blocklist"))
+ self.plugin.remove_preferences_page(_('Blocklist'))
# Remove status item
- component.get("StatusBar").remove_item(self.status_item)
+ component.get('StatusBar').remove_item(self.status_item)
del self.status_item
# Deregister the hooks
- self.plugin.deregister_hook("on_apply_prefs", self._on_apply_prefs)
- self.plugin.deregister_hook("on_show_prefs", self._on_show_prefs)
+ self.plugin.deregister_hook('on_apply_prefs', self._on_apply_prefs)
+ self.plugin.deregister_hook('on_show_prefs', self._on_show_prefs)
del self.glade
def update(self):
def _on_get_status(status):
- if status["state"] == "Downloading":
+ if status['state'] == 'Downloading':
self.table_info.hide()
- self.glade.get_widget("button_check_download").set_sensitive(False)
- self.glade.get_widget("button_force_download").set_sensitive(False)
- self.glade.get_widget("image_up_to_date").hide()
+ self.glade.get_widget('button_check_download').set_sensitive(False)
+ self.glade.get_widget('button_force_download').set_sensitive(False)
+ self.glade.get_widget('image_up_to_date').hide()
self.status_item.set_text(
- "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"])
+ '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()
- elif status["state"] == "Importing":
+ elif status['state'] == 'Importing':
self.table_info.hide()
- self.glade.get_widget("button_check_download").set_sensitive(False)
- self.glade.get_widget("button_force_download").set_sensitive(False)
- self.glade.get_widget("image_up_to_date").hide()
+ self.glade.get_widget('button_check_download').set_sensitive(False)
+ self.glade.get_widget('button_force_download').set_sensitive(False)
+ self.glade.get_widget('image_up_to_date').hide()
self.status_item.set_text(
- "Importing " + str(status["num_blocked"]))
- self.progress_bar.set_text("Importing %s" % (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()
- elif status["state"] == "Idle":
+ elif status['state'] == 'Idle':
self.progress_bar.hide()
- self.glade.get_widget("button_check_download").set_sensitive(True)
- self.glade.get_widget("button_force_download").set_sensitive(True)
- if status["up_to_date"]:
- self.glade.get_widget("image_up_to_date").show()
+ self.glade.get_widget('button_check_download').set_sensitive(True)
+ self.glade.get_widget('button_force_download').set_sensitive(True)
+ if status['up_to_date']:
+ self.glade.get_widget('image_up_to_date').show()
else:
- self.glade.get_widget("image_up_to_date").hide()
+ self.glade.get_widget('image_up_to_date').hide()
self.table_info.show()
- self.status_item.set_text("%(num_blocked)s/%(num_whited)s" % status)
+ self.status_item.set_text('%(num_blocked)s/%(num_whited)s' % status)
- self.glade.get_widget("label_filesize").set_text(
- deluge.common.fsize(status["file_size"]))
- self.glade.get_widget("label_modified").set_text(
- datetime.fromtimestamp(status["file_date"]).strftime("%c"))
- self.glade.get_widget("label_type").set_text(status["file_type"])
- self.glade.get_widget("label_url").set_text(
- status["file_url"])
+ self.glade.get_widget('label_filesize').set_text(
+ deluge.common.fsize(status['file_size']))
+ self.glade.get_widget('label_modified').set_text(
+ datetime.fromtimestamp(status['file_date']).strftime('%c'))
+ self.glade.get_widget('label_type').set_text(status['file_type'])
+ self.glade.get_widget('label_url').set_text(
+ status['file_url'])
client.blocklist.get_status().addCallback(_on_get_status)
def _on_show_prefs(self):
def _on_get_config(config):
- log.trace("Loaded config: %s", config)
- self.glade.get_widget("entry_url").set_text(config["url"])
- self.glade.get_widget("spin_check_days").set_value(config["check_after_days"])
- self.glade.get_widget("chk_import_on_start").set_active(config["load_on_start"])
- self.populate_whitelist(config["whitelisted"])
+ log.trace('Loaded config: %s', config)
+ self.glade.get_widget('entry_url').set_text(config['url'])
+ self.glade.get_widget('spin_check_days').set_value(config['check_after_days'])
+ self.glade.get_widget('chk_import_on_start').set_active(config['load_on_start'])
+ self.populate_whitelist(config['whitelisted'])
client.blocklist.get_config().addCallback(_on_get_config)
def _on_apply_prefs(self):
config = {}
- config["url"] = self.glade.get_widget("entry_url").get_text().strip()
- config["check_after_days"] = self.glade.get_widget("spin_check_days").get_value_as_int()
- config["load_on_start"] = self.glade.get_widget("chk_import_on_start").get_active()
- config["whitelisted"] = [ip[0] for ip in self.whitelist_model if ip[0] != 'IP HERE']
+ config['url'] = self.glade.get_widget('entry_url').get_text().strip()
+ config['check_after_days'] = self.glade.get_widget('spin_check_days').get_value_as_int()
+ config['load_on_start'] = self.glade.get_widget('chk_import_on_start').get_active()
+ config['whitelisted'] = [ip[0] for ip in self.whitelist_model if ip[0] != 'IP HERE']
client.blocklist.set_config(config)
def _on_button_check_download_clicked(self, widget):
@@ -132,16 +132,16 @@ class GtkUI(GtkPluginBase):
client.blocklist.check_import(force=True)
def _on_status_item_clicked(self, widget, event):
- component.get("Preferences").show(_("Blocklist"))
+ component.get('Preferences').show(_('Blocklist'))
def load_preferences_page(self):
"""Initializes the preferences page and adds it to the preferences dialog"""
# Load the preferences page
- self.glade = gtk.glade.XML(common.get_resource("blocklist_pref.glade"))
+ self.glade = gtk.glade.XML(common.get_resource('blocklist_pref.glade'))
- self.whitelist_frame = self.glade.get_widget("whitelist_frame")
- self.progress_bar = self.glade.get_widget("progressbar")
- self.table_info = self.glade.get_widget("table_info")
+ self.whitelist_frame = self.glade.get_widget('whitelist_frame')
+ self.progress_bar = self.glade.get_widget('progressbar')
+ self.table_info = self.glade.get_widget('table_info')
# Hide the progress bar initially
self.progress_bar.hide()
@@ -151,8 +151,8 @@ class GtkUI(GtkPluginBase):
self.build_whitelist_model_treeview()
self.glade.signal_autoconnect({
- "on_button_check_download_clicked": self._on_button_check_download_clicked,
- "on_button_force_download_clicked": self._on_button_force_download_clicked,
+ '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,
@@ -160,32 +160,32 @@ class GtkUI(GtkPluginBase):
})
# Set button icons
- self.glade.get_widget("image_download").set_from_file(
- common.get_resource("blocklist_download24.png"))
+ self.glade.get_widget('image_download').set_from_file(
+ common.get_resource('blocklist_download24.png'))
- self.glade.get_widget("image_import").set_from_file(
- common.get_resource("blocklist_import24.png"))
+ self.glade.get_widget('image_import').set_from_file(
+ common.get_resource('blocklist_import24.png'))
# Update the preferences page with config values from the core
self._on_show_prefs()
# Add the page to the preferences dialog
self.plugin.add_preferences_page(
- _("Blocklist"),
- self.glade.get_widget("blocklist_prefs_box"))
+ _('Blocklist'),
+ self.glade.get_widget('blocklist_prefs_box'))
def build_whitelist_model_treeview(self):
- self.whitelist_treeview = self.glade.get_widget("whitelist_treeview")
+ self.whitelist_treeview = self.glade.get_widget('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()
- renderer.connect("edited", self.on_cell_edited, self.whitelist_model)
- renderer.set_data("ip", 0)
+ renderer.connect('edited', self.on_cell_edited, self.whitelist_model)
+ renderer.set_data('ip', 0)
- column = gtk.TreeViewColumn("IPs", renderer, text=0, editable=1)
+ column = gtk.TreeViewColumn('IPs', renderer, text=0, editable=1)
column.set_expand(True)
self.whitelist_treeview.append_column(column)
self.whitelist_treeview.set_model(self.whitelist_model)
@@ -199,21 +199,21 @@ class GtkUI(GtkPluginBase):
except common.BadIP as ex:
model.remove(model.get_iter_from_string(path_string))
from deluge.ui.gtkui import dialogs
- d = dialogs.ErrorDialog(_("Bad IP address"), ex.message)
+ d = dialogs.ErrorDialog(_('Bad IP address'), ex.message)
d.run()
def on_whitelist_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected()
if selected_connection_iter:
- self.glade.get_widget("whitelist_delete").set_property('sensitive',
+ self.glade.get_widget('whitelist_delete').set_property('sensitive',
True)
else:
- self.glade.get_widget("whitelist_delete").set_property('sensitive',
+ self.glade.get_widget('whitelist_delete').set_property('sensitive',
False)
def on_add_button_clicked(self, widget, treeview):
model = treeview.get_model()
- model.set(model.append(), 0, "IP HERE", 1, True)
+ model.set(model.append(), 0, 'IP HERE', 1, True)
def on_delete_button_clicked(self, widget, treeview):
selection = treeview.get_selection()
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/peerguardian.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/peerguardian.py
index 55183758e..59372e23c 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/peerguardian.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/peerguardian.py
@@ -24,35 +24,35 @@ class PGException(Exception):
class PGReader(object):
def __init__(self, filename):
- log.debug("PGReader loading: %s", filename)
+ log.debug('PGReader loading: %s', filename)
try:
- with gzip.open(filename, "rb") as _file:
+ with gzip.open(filename, 'rb') as _file:
self.fd = _file
except IOError:
- log.debug("Blocklist: PGReader: Incorrect file type or list is corrupt")
+ log.debug('Blocklist: PGReader: Incorrect file type or list is corrupt')
# 4 bytes, should be 0xffffffff
buf = self.fd.read(4)
- hdr = unpack("l", buf)[0]
+ hdr = unpack('l', buf)[0]
if hdr != -1:
- raise PGException(_("Invalid leader") + " %d" % hdr)
+ raise PGException(_('Invalid leader') + ' %d' % hdr)
magic = self.fd.read(3)
- if magic != "P2B":
- raise PGException(_("Invalid magic code"))
+ if magic != 'P2B':
+ raise PGException(_('Invalid magic code'))
buf = self.fd.read(1)
ver = ord(buf)
if ver != 1 and ver != 2:
- raise PGException(_("Invalid version") + " %d" % ver)
+ raise PGException(_('Invalid version') + ' %d' % ver)
def __next__(self):
# Skip over the string
buf = -1
while buf != 0:
buf = self.fd.read(1)
- if buf == "": # EOF
+ if buf == '': # EOF
return False
buf = ord(buf)
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py
index 85766a3ea..7963709ed 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/readers.py
@@ -39,7 +39,7 @@ class BaseReader(object):
try:
callback(IP.parse(start), IP.parse(end))
except BadIP as ex:
- log.error("Failed to parse IP: %s", ex)
+ log.error('Failed to parse IP: %s', ex)
return self.file
def is_ignored(self, line):
@@ -55,8 +55,8 @@ class BaseReader(object):
if not self.is_ignored(line):
try:
(start, end) = self.parse(line)
- if not re.match(r"^(\d{1,3}\.){4}$", start + ".") or \
- not re.match(r"^(\d{1,3}\.){4}$", end + "."):
+ if not re.match(r'^(\d{1,3}\.){4}$', start + '.') or \
+ not re.match(r'^(\d{1,3}\.){4}$', end + '.'):
valid = False
except Exception:
valid = False
@@ -77,13 +77,13 @@ class BaseReader(object):
class EmuleReader(BaseReader):
"""Blocklist reader for emule style blocklists"""
def parse(self, line):
- return line.strip().split(" , ")[0].split(" - ")
+ return line.strip().split(' , ')[0].split(' - ')
class SafePeerReader(BaseReader):
"""Blocklist reader for SafePeer style blocklists"""
def parse(self, line):
- return line.strip().split(":")[-1].split("-")
+ return line.strip().split(':')[-1].split('-')
class PeerGuardianReader(SafePeerReader):
diff --git a/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py b/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
index 402d8ff0a..474f8d26d 100644
--- a/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
+++ b/deluge/plugins/Blocklist/deluge/plugins/blocklist/webui.py
@@ -16,14 +16,14 @@ from .common import get_resource
log = logging.getLogger(__name__)
FORMAT_LIST = [
- ('gzmule', _("Emule IP list (GZip)")),
- ('spzip', _("SafePeer Text (Zipped)")),
- ('pgtext', _("PeerGuardian Text (Uncompressed)")),
- ('p2bgz', _("PeerGuardian P2B (GZip)"))
+ ('gzmule', _('Emule IP list (GZip)')),
+ ('spzip', _('SafePeer Text (Zipped)')),
+ ('pgtext', _('PeerGuardian Text (Uncompressed)')),
+ ('p2bgz', _('PeerGuardian P2B (GZip)'))
]
class WebUI(WebPluginBase):
- scripts = [get_resource("blocklist.js")]
+ scripts = [get_resource('blocklist.js')]
debug_scripts = scripts
diff --git a/deluge/plugins/Blocklist/setup.py b/deluge/plugins/Blocklist/setup.py
index 3ee5b3adc..c49fb4f1c 100644
--- a/deluge/plugins/Blocklist/setup.py
+++ b/deluge/plugins/Blocklist/setup.py
@@ -9,15 +9,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Blocklist"
-__author__ = "John Garland"
-__author_email__ = "johnnybg+deluge@gmail.com"
-__version__ = "1.3"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Download and import IP blocklists"
+__plugin_name__ = 'Blocklist'
+__author__ = 'John Garland'
+__author_email__ = 'johnnybg+deluge@gmail.com'
+__version__ = '1.3'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Download and import IP blocklists'
__long_description__ = __description__
-__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ["data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['data/*']}
setup(
name=__plugin_name__,
@@ -30,7 +30,7 @@ setup(
zip_safe=False,
long_description=__long_description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
[deluge.plugin.core]
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/common.py b/deluge/plugins/Execute/deluge/plugins/execute/common.py
index 49e0e9fb8..2301bb91e 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/common.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/common.py
@@ -13,5 +13,5 @@ import pkg_resources
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.execute",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.execute',
+ os.path.join('data', filename))
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/core.py b/deluge/plugins/Execute/deluge/plugins/execute/core.py
index cdd2a2c19..81e9c3bf2 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/core.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/core.py
@@ -24,7 +24,7 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
DEFAULT_CONFIG = {
- "commands": []
+ 'commands': []
}
EXECUTE_ID = 0
@@ -32,9 +32,9 @@ EXECUTE_EVENT = 1
EXECUTE_COMMAND = 2
EVENT_MAP = {
- "complete": "TorrentFinishedEvent",
- "added": "TorrentAddedEvent",
- "removed": "TorrentRemovedEvent"
+ 'complete': 'TorrentFinishedEvent',
+ 'added': 'TorrentAddedEvent',
+ 'removed': 'TorrentRemovedEvent'
}
@@ -56,13 +56,13 @@ class ExecuteCommandRemovedEvent(DelugeEvent):
class Core(CorePluginBase):
def enable(self):
- self.config = ConfigManager("execute.conf", DEFAULT_CONFIG)
- event_manager = component.get("EventManager")
+ self.config = ConfigManager('execute.conf', DEFAULT_CONFIG)
+ event_manager = component.get('EventManager')
self.registered_events = {}
self.preremoved_cache = {}
# Go through the commands list and register event handlers
- for command in self.config["commands"]:
+ for command in self.config['commands']:
event = command[EXECUTE_EVENT]
if event in self.registered_events:
continue
@@ -73,47 +73,47 @@ class Core(CorePluginBase):
return event_handler
event_handler = create_event_handler(event)
event_manager.register_event_handler(EVENT_MAP[event], event_handler)
- if event == "removed":
- event_manager.register_event_handler("PreTorrentRemovedEvent", self.on_preremoved)
+ if event == 'removed':
+ event_manager.register_event_handler('PreTorrentRemovedEvent', self.on_preremoved)
self.registered_events[event] = event_handler
- log.debug("Execute core plugin enabled!")
+ log.debug('Execute core plugin enabled!')
def on_preremoved(self, torrent_id):
# Get and store the torrent info before it is removed
- torrent = component.get("TorrentManager").torrents[torrent_id]
- info = torrent.get_status(["name", "download_location"])
- self.preremoved_cache[torrent_id] = [utf8_encoded(torrent_id), utf8_encoded(info["name"]),
- utf8_encoded(info["download_location"])]
+ torrent = component.get('TorrentManager').torrents[torrent_id]
+ info = torrent.get_status(['name', 'download_location'])
+ self.preremoved_cache[torrent_id] = [utf8_encoded(torrent_id), utf8_encoded(info['name']),
+ utf8_encoded(info['download_location'])]
def execute_commands(self, torrent_id, event, *arg):
- if event == "added" and arg[0]:
+ if event == 'added' and arg[0]:
# No futher action as from_state (arg[0]) is True
return
- elif event == "removed":
+ elif event == 'removed':
torrent_id, torrent_name, download_location = self.preremoved_cache.pop(torrent_id)
else:
- torrent = component.get("TorrentManager").torrents[torrent_id]
- info = torrent.get_status(["name", "download_location"])
+ torrent = component.get('TorrentManager').torrents[torrent_id]
+ info = torrent.get_status(['name', 'download_location'])
# Grab the torrent name and download location
# getProcessOutputAndValue requires args to be str
torrent_id = utf8_encoded(torrent_id)
- torrent_name = utf8_encoded(info["name"])
- download_location = utf8_encoded(info["download_location"])
+ torrent_name = utf8_encoded(info['name'])
+ download_location = utf8_encoded(info['download_location'])
- log.debug("Running commands for %s", event)
+ log.debug('Running commands for %s', event)
def log_error(result, command):
(stdout, stderr, exit_code) = result
if exit_code:
log.warn("Command '%s' failed with exit code %d", command, exit_code)
if stdout:
- log.warn("stdout: %s", stdout)
+ log.warn('stdout: %s', stdout)
if stderr:
- log.warn("stderr: %s", stderr)
+ log.warn('stderr: %s', stderr)
# Go through and execute all the commands
- for command in self.config["commands"]:
+ for command in self.config['commands']:
if command[EXECUTE_EVENT] == event:
command = os.path.expandvars(command[EXECUTE_COMMAND])
command = os.path.expanduser(command)
@@ -121,47 +121,47 @@ class Core(CorePluginBase):
cmd_args = [torrent_id, torrent_name, download_location]
if windows_check():
# Escape ampersand on windows (see #2784)
- cmd_args = [cmd_arg.replace("&", "^^^&") for cmd_arg in cmd_args]
+ cmd_args = [cmd_arg.replace('&', '^^^&') for cmd_arg in cmd_args]
if os.path.isfile(command) and os.access(command, os.X_OK):
- log.debug("Running %s with args: %s", command, cmd_args)
+ log.debug('Running %s with args: %s', command, cmd_args)
d = getProcessOutputAndValue(command, cmd_args, env=os.environ)
d.addCallback(log_error, command)
else:
- log.error("Execute script not found or not executable")
+ log.error('Execute script not found or not executable')
def disable(self):
self.config.save()
- event_manager = component.get("EventManager")
+ event_manager = component.get('EventManager')
for event, handler in self.registered_events.iteritems():
event_manager.deregister_event_handler(event, handler)
- log.debug("Execute core plugin disabled!")
+ log.debug('Execute core plugin disabled!')
# Exported RPC methods #
@export
def add_command(self, event, command):
command_id = hashlib.sha1(str(time.time())).hexdigest()
- self.config["commands"].append((command_id, event, command))
+ self.config['commands'].append((command_id, event, command))
self.config.save()
- component.get("EventManager").emit(ExecuteCommandAddedEvent(command_id, event, command))
+ component.get('EventManager').emit(ExecuteCommandAddedEvent(command_id, event, command))
@export
def get_commands(self):
- return self.config["commands"]
+ return self.config['commands']
@export
def remove_command(self, command_id):
- for command in self.config["commands"]:
+ for command in self.config['commands']:
if command[EXECUTE_ID] == command_id:
- self.config["commands"].remove(command)
- component.get("EventManager").emit(ExecuteCommandRemovedEvent(command_id))
+ self.config['commands'].remove(command)
+ component.get('EventManager').emit(ExecuteCommandRemovedEvent(command_id))
break
self.config.save()
@export
def save_command(self, command_id, event, cmd):
- for i, command in enumerate(self.config["commands"]):
+ for i, command in enumerate(self.config['commands']):
if command[EXECUTE_ID] == command_id:
- self.config["commands"][i] = (command_id, event, cmd)
+ self.config['commands'][i] = (command_id, event, cmd)
break
self.config.save()
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py b/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
index 6a7b60361..08eb5e590 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/gtkui.py
@@ -27,12 +27,12 @@ EXECUTE_EVENT = 1
EXECUTE_COMMAND = 2
EVENT_MAP = {
- "complete": _("Torrent Complete"),
- "added": _("Torrent Added"),
- "removed": _("Torrent Removed")
+ 'complete': _('Torrent Complete'),
+ 'added': _('Torrent Added'),
+ 'removed': _('Torrent Removed')
}
-EVENTS = ["complete", "added", "removed"]
+EVENTS = ['complete', 'added', 'removed']
class ExecutePreferences(object):
@@ -40,13 +40,13 @@ class ExecutePreferences(object):
self.plugin = plugin
def load(self):
- log.debug("Adding Execute Preferences page")
- self.glade = gtk.glade.XML(common.get_resource("execute_prefs.glade"))
+ log.debug('Adding Execute Preferences page')
+ self.glade = gtk.glade.XML(common.get_resource('execute_prefs.glade'))
self.glade.signal_autoconnect({
- "on_add_button_clicked": self.on_add_button_clicked
+ 'on_add_button_clicked': self.on_add_button_clicked
})
- events = self.glade.get_widget("event_combobox")
+ events = self.glade.get_widget('event_combobox')
store = gtk.ListStore(str, str)
for event in EVENTS:
@@ -55,31 +55,31 @@ class ExecutePreferences(object):
events.set_model(store)
events.set_active(0)
- self.plugin.add_preferences_page(_("Execute"), self.glade.get_widget("execute_box"))
- self.plugin.register_hook("on_show_prefs", self.load_commands)
- self.plugin.register_hook("on_apply_prefs", self.on_apply_prefs)
+ self.plugin.add_preferences_page(_('Execute'), self.glade.get_widget('execute_box'))
+ self.plugin.register_hook('on_show_prefs', self.load_commands)
+ self.plugin.register_hook('on_apply_prefs', self.on_apply_prefs)
self.load_commands()
- client.register_event_handler("ExecuteCommandAddedEvent", self.on_command_added_event)
- client.register_event_handler("ExecuteCommandRemovedEvent", self.on_command_removed_event)
+ client.register_event_handler('ExecuteCommandAddedEvent', self.on_command_added_event)
+ client.register_event_handler('ExecuteCommandRemovedEvent', self.on_command_removed_event)
def unload(self):
- self.plugin.remove_preferences_page(_("Execute"))
- self.plugin.deregister_hook("on_apply_prefs", self.on_apply_prefs)
- self.plugin.deregister_hook("on_show_prefs", self.load_commands)
+ self.plugin.remove_preferences_page(_('Execute'))
+ self.plugin.deregister_hook('on_apply_prefs', self.on_apply_prefs)
+ self.plugin.deregister_hook('on_show_prefs', self.load_commands)
def add_command(self, command_id, event, command):
- log.debug("Adding command `%s`", command_id)
- vbox = self.glade.get_widget("commands_vbox")
+ log.debug('Adding command `%s`', command_id)
+ vbox = self.glade.get_widget('commands_vbox')
hbox = gtk.HBox(False, 5)
- hbox.set_name(command_id + "_" + event)
+ hbox.set_name(command_id + '_' + event)
label = gtk.Label(EVENT_MAP[event])
entry = gtk.Entry()
entry.set_text(command)
button = gtk.Button()
- button.set_name("remove_%s" % command_id)
- button.connect("clicked", self.on_remove_button_clicked)
+ button.set_name('remove_%s' % command_id)
+ button.connect('clicked', self.on_remove_button_clicked)
img = gtk.Image()
img.set_from_stock(gtk.STOCK_REMOVE, gtk.ICON_SIZE_BUTTON)
@@ -92,15 +92,15 @@ class ExecutePreferences(object):
vbox.pack_start(hbox)
def remove_command(self, command_id):
- vbox = self.glade.get_widget("commands_vbox")
+ vbox = self.glade.get_widget('commands_vbox')
children = vbox.get_children()
for child in children:
- if child.get_name().split("_")[0] == command_id:
+ if child.get_name().split('_')[0] == command_id:
vbox.remove(child)
break
def clear_commands(self):
- vbox = self.glade.get_widget("commands_vbox")
+ vbox = self.glade.get_widget('commands_vbox')
children = vbox.get_children()
for child in children:
vbox.remove(child)
@@ -108,7 +108,7 @@ class ExecutePreferences(object):
def load_commands(self):
def on_get_commands(commands):
self.clear_commands()
- log.debug("on_get_commands: %s", commands)
+ log.debug('on_get_commands: %s', commands)
for command in commands:
command_id, event, command = command
self.add_command(command_id, event, command)
@@ -116,38 +116,38 @@ class ExecutePreferences(object):
client.execute.get_commands().addCallback(on_get_commands)
def on_add_button_clicked(self, *args):
- command = self.glade.get_widget("command_entry").get_text()
- events = self.glade.get_widget("event_combobox")
+ command = self.glade.get_widget('command_entry').get_text()
+ events = self.glade.get_widget('event_combobox')
event = events.get_model()[events.get_active()][1]
client.execute.add_command(event, command)
def on_remove_button_clicked(self, widget, *args):
- command_id = widget.get_name().replace("remove_", "")
+ command_id = widget.get_name().replace('remove_', '')
client.execute.remove_command(command_id)
def on_apply_prefs(self):
- vbox = self.glade.get_widget("commands_vbox")
+ vbox = self.glade.get_widget('commands_vbox')
children = vbox.get_children()
for child in children:
- command_id, event = child.get_name().split("_")
+ command_id, event = child.get_name().split('_')
for widget in child.get_children():
if isinstance(widget, gtk.Entry):
command = widget.get_text()
client.execute.save_command(command_id, event, command)
def on_command_added_event(self, command_id, event, command):
- log.debug("Adding command %s: %s", event, command)
+ log.debug('Adding command %s: %s', event, command)
self.add_command(command_id, event, command)
def on_command_removed_event(self, command_id):
- log.debug("Removing command %s", command_id)
+ log.debug('Removing command %s', command_id)
self.remove_command(command_id)
class GtkUI(GtkPluginBase):
def enable(self):
- self.plugin = component.get("PluginManager")
+ self.plugin = component.get('PluginManager')
self.preferences = ExecutePreferences(self.plugin)
self.preferences.load()
diff --git a/deluge/plugins/Execute/deluge/plugins/execute/webui.py b/deluge/plugins/Execute/deluge/plugins/execute/webui.py
index 846bbb026..de337e73c 100644
--- a/deluge/plugins/Execute/deluge/plugins/execute/webui.py
+++ b/deluge/plugins/Execute/deluge/plugins/execute/webui.py
@@ -18,5 +18,5 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("execute.js")]
+ scripts = [get_resource('execute.js')]
debug_scripts = scripts
diff --git a/deluge/plugins/Execute/setup.py b/deluge/plugins/Execute/setup.py
index efd8a2d29..090131d1f 100644
--- a/deluge/plugins/Execute/setup.py
+++ b/deluge/plugins/Execute/setup.py
@@ -9,15 +9,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Execute"
-__author__ = "Damien Churchill"
-__author_email__ = "damoxc@gmail.com"
-__version__ = "1.2"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Plugin to execute a command upon an event"
+__plugin_name__ = 'Execute'
+__author__ = 'Damien Churchill'
+__author_email__ = 'damoxc@gmail.com'
+__version__ = '1.2'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Plugin to execute a command upon an event'
__long_description__ = __description__
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['data/*']}
setup(
name=__plugin_name__,
@@ -30,7 +30,7 @@ setup(
long_description=__long_description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/common.py b/deluge/plugins/Extractor/deluge/plugins/extractor/common.py
index 053d8285a..c748b5ec4 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/common.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/common.py
@@ -13,5 +13,5 @@ import pkg_resources
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.extractor",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.extractor',
+ os.path.join('data', filename))
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
index 4ddba3108..44192ae46 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/core.py
@@ -27,8 +27,8 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "extract_path": "",
- "use_name_folder": True
+ 'extract_path': '',
+ 'use_name_folder': True
}
if windows_check():
@@ -40,15 +40,15 @@ if windows_check():
import _winreg
try:
- hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
+ hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\7-Zip')
except WindowsError: # pylint: disable=undefined-variable
pass
else:
- win_7z_path = os.path.join(_winreg.QueryValueEx(hkey, "Path")[0], "7z.exe")
+ win_7z_path = os.path.join(_winreg.QueryValueEx(hkey, 'Path')[0], '7z.exe')
_winreg.CloseKey(hkey)
win_7z_exes.insert(1, win_7z_path)
- switch_7z = "x -y"
+ switch_7z = 'x -y'
# Future suport:
# 7-zip cannot extract tar.* with single command.
# ".tar.gz", ".tgz",
@@ -56,15 +56,15 @@ if windows_check():
# ".tar.lzma", ".tlz",
# ".tar.xz", ".txz",
exts_7z = [
- ".rar", ".zip", ".tar",
- ".7z", ".xz", ".lzma",
+ '.rar', '.zip', '.tar',
+ '.7z', '.xz', '.lzma',
]
for win_7z_exe in win_7z_exes:
if which(win_7z_exe):
EXTRACT_COMMANDS = dict.fromkeys(exts_7z, [win_7z_exe, switch_7z])
break
else:
- required_cmds = ["unrar", "unzip", "tar", "unxz", "unlzma", "7zr", "bunzip2"]
+ required_cmds = ['unrar', 'unzip', 'tar', 'unxz', 'unlzma', '7zr', 'bunzip2']
# Possible future suport:
# gunzip: gz (cmd will delete original archive)
# the following do not extract to dest dir
@@ -73,36 +73,36 @@ else:
# ".bz2": ["bzip2", "-d --keep"],
EXTRACT_COMMANDS = {
- ".rar": ["unrar", "x -o+ -y"],
- ".tar": ["tar", "-xf"],
- ".zip": ["unzip", ""],
- ".tar.gz": ["tar", "-xzf"], ".tgz": ["tar", "-xzf"],
- ".tar.bz2": ["tar", "-xjf"], ".tbz": ["tar", "-xjf"],
- ".tar.lzma": ["tar", "--lzma -xf"], ".tlz": ["tar", "--lzma -xf"],
- ".tar.xz": ["tar", "--xz -xf"], ".txz": ["tar", "--xz -xf"],
- ".7z": ["7zr", "x"],
+ '.rar': ['unrar', 'x -o+ -y'],
+ '.tar': ['tar', '-xf'],
+ '.zip': ['unzip', ''],
+ '.tar.gz': ['tar', '-xzf'], '.tgz': ['tar', '-xzf'],
+ '.tar.bz2': ['tar', '-xjf'], '.tbz': ['tar', '-xjf'],
+ '.tar.lzma': ['tar', '--lzma -xf'], '.tlz': ['tar', '--lzma -xf'],
+ '.tar.xz': ['tar', '--xz -xf'], '.txz': ['tar', '--xz -xf'],
+ '.7z': ['7zr', 'x'],
}
# Test command exists and if not, remove.
for command in required_cmds:
if not which(command):
for k, v in EXTRACT_COMMANDS.items():
if command in v[0]:
- log.warning("%s not found, disabling support for %s", command, k)
+ log.warning('%s not found, disabling support for %s', command, k)
del EXTRACT_COMMANDS[k]
if not EXTRACT_COMMANDS:
- raise Exception("No archive extracting programs found, plugin will be disabled")
+ raise Exception('No archive extracting programs found, plugin will be disabled')
class Core(CorePluginBase):
def enable(self):
- self.config = deluge.configmanager.ConfigManager("extractor.conf", DEFAULT_PREFS)
- if not self.config["extract_path"]:
- self.config["extract_path"] = deluge.configmanager.ConfigManager("core.conf")["download_location"]
- component.get("EventManager").register_event_handler("TorrentFinishedEvent", self._on_torrent_finished)
+ self.config = deluge.configmanager.ConfigManager('extractor.conf', DEFAULT_PREFS)
+ if not self.config['extract_path']:
+ self.config['extract_path'] = deluge.configmanager.ConfigManager('core.conf')['download_location']
+ component.get('EventManager').register_event_handler('TorrentFinishedEvent', self._on_torrent_finished)
def disable(self):
- component.get("EventManager").deregister_event_handler("TorrentFinishedEvent", self._on_torrent_finished)
+ component.get('EventManager').deregister_event_handler('TorrentFinishedEvent', self._on_torrent_finished)
def update(self):
pass
@@ -111,57 +111,57 @@ class Core(CorePluginBase):
"""
This is called when a torrent finishes and checks if any files to extract.
"""
- tid = component.get("TorrentManager").torrents[torrent_id]
- tid_status = tid.get_status(["download_location", "name"])
+ tid = component.get('TorrentManager').torrents[torrent_id]
+ tid_status = tid.get_status(['download_location', 'name'])
files = tid.get_files()
for f in files:
- file_root, file_ext = os.path.splitext(f["path"])
+ file_root, file_ext = os.path.splitext(f['path'])
file_ext_sec = os.path.splitext(file_root)[1]
if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS:
file_ext = file_ext_sec + file_ext
elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == '.tar':
- log.debug("Can't extract file with unknown file type: %s", f["path"])
+ log.debug("Can't extract file with unknown file type: %s", f['path'])
continue
- elif file_ext == ".rar" and "part" in file_ext_sec:
- part_num = file_ext_sec.split("part")[1]
+ elif file_ext == '.rar' and 'part' in file_ext_sec:
+ part_num = file_ext_sec.split('part')[1]
if part_num.isdigit() and int(part_num) != 1:
- log.debug("Skipping remaining multi-part rar files: %s", f["path"])
+ log.debug('Skipping remaining multi-part rar files: %s', f['path'])
continue
cmd = EXTRACT_COMMANDS[file_ext]
- fpath = os.path.join(tid_status["download_location"], os.path.normpath(f["path"]))
- dest = os.path.normpath(self.config["extract_path"])
- if self.config["use_name_folder"]:
- dest = os.path.join(dest, tid_status["name"])
+ fpath = os.path.join(tid_status['download_location'], os.path.normpath(f['path']))
+ dest = os.path.normpath(self.config['extract_path'])
+ if self.config['use_name_folder']:
+ dest = os.path.join(dest, tid_status['name'])
try:
os.makedirs(dest)
except OSError as ex:
if not (ex.errno == errno.EEXIST and os.path.isdir(dest)):
- log.error("Error creating destination folder: %s", ex)
+ log.error('Error creating destination folder: %s', ex)
break
def on_extract(result, torrent_id, fpath):
# Check command exit code.
if not result[2]:
- log.info("Extract successful: %s (%s)", fpath, torrent_id)
+ log.info('Extract successful: %s (%s)', fpath, torrent_id)
else:
- log.error("Extract failed: %s (%s) %s", fpath, torrent_id, result[1])
+ log.error('Extract failed: %s (%s) %s', fpath, torrent_id, result[1])
# Run the command and add callback.
- log.debug("Extracting %s from %s with %s %s to %s", fpath, torrent_id, cmd[0], cmd[1], dest)
+ log.debug('Extracting %s from %s with %s %s to %s', fpath, torrent_id, cmd[0], cmd[1], dest)
d = getProcessOutputAndValue(cmd[0], cmd[1].split() + [str(fpath)], os.environ, str(dest))
d.addCallback(on_extract, torrent_id, fpath)
@export
def set_config(self, config):
- "sets the config dictionary"
+ 'sets the config dictionary'
for key in config.keys():
self.config[key] = config[key]
self.config.save()
@export
def get_config(self):
- "returns the config dictionary"
+ 'returns the config dictionary'
return self.config.config
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py b/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
index 49c989f40..b545fba34 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/gtkui.py
@@ -27,47 +27,47 @@ log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
- self.glade = gtk.glade.XML(get_resource("extractor_prefs.glade"))
+ self.glade = gtk.glade.XML(get_resource('extractor_prefs.glade'))
- component.get("Preferences").add_page(_("Extractor"), self.glade.get_widget("extractor_prefs_box"))
- 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('Preferences').add_page(_('Extractor'), self.glade.get_widget('extractor_prefs_box'))
+ component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs)
self.on_show_prefs()
def disable(self):
- component.get("Preferences").remove_page(_("Extractor"))
- 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('Preferences').remove_page(_('Extractor'))
+ component.get('PluginManager').deregister_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').deregister_hook('on_show_prefs', self.on_show_prefs)
del self.glade
def on_apply_prefs(self):
- log.debug("applying prefs for Extractor")
+ log.debug('applying prefs for Extractor')
if client.is_localhost():
- path = self.glade.get_widget("folderchooser_path").get_filename()
+ path = self.glade.get_widget('folderchooser_path').get_filename()
else:
- path = self.glade.get_widget("entry_path").get_text()
+ path = self.glade.get_widget('entry_path').get_text()
config = {
- "extract_path": path,
- "use_name_folder": self.glade.get_widget("chk_use_name").get_active()
+ 'extract_path': path,
+ 'use_name_folder': self.glade.get_widget('chk_use_name').get_active()
}
client.extractor.set_config(config)
def on_show_prefs(self):
if client.is_localhost():
- self.glade.get_widget("folderchooser_path").show()
- self.glade.get_widget("entry_path").hide()
+ self.glade.get_widget('folderchooser_path').show()
+ self.glade.get_widget('entry_path').hide()
else:
- self.glade.get_widget("folderchooser_path").hide()
- self.glade.get_widget("entry_path").show()
+ self.glade.get_widget('folderchooser_path').hide()
+ self.glade.get_widget('entry_path').show()
def on_get_config(config):
if client.is_localhost():
- self.glade.get_widget("folderchooser_path").set_current_folder(config["extract_path"])
+ self.glade.get_widget('folderchooser_path').set_current_folder(config['extract_path'])
else:
- self.glade.get_widget("entry_path").set_text(config["extract_path"])
+ self.glade.get_widget('entry_path').set_text(config['extract_path'])
- self.glade.get_widget("chk_use_name").set_active(config["use_name_folder"])
+ self.glade.get_widget('chk_use_name').set_active(config['use_name_folder'])
client.extractor.get_config().addCallback(on_get_config)
diff --git a/deluge/plugins/Extractor/deluge/plugins/extractor/webui.py b/deluge/plugins/Extractor/deluge/plugins/extractor/webui.py
index bacb89113..eaab79a74 100644
--- a/deluge/plugins/Extractor/deluge/plugins/extractor/webui.py
+++ b/deluge/plugins/Extractor/deluge/plugins/extractor/webui.py
@@ -22,5 +22,5 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("extractor.js")]
+ scripts = [get_resource('extractor.js')]
debug_scripts = scripts
diff --git a/deluge/plugins/Extractor/setup.py b/deluge/plugins/Extractor/setup.py
index a3b7391ab..a38f4d76e 100644
--- a/deluge/plugins/Extractor/setup.py
+++ b/deluge/plugins/Extractor/setup.py
@@ -13,13 +13,13 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Extractor"
-__author__ = "Andrew Resch"
-__author_email__ = "andrewresch@gmail.com"
-__version__ = "0.6"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Extract files upon torrent completion"
+__plugin_name__ = 'Extractor'
+__author__ = 'Andrew Resch'
+__author_email__ = 'andrewresch@gmail.com'
+__version__ = '0.6'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Extract files upon torrent completion'
__long_description__ = """
Extract files upon torrent completion
@@ -30,7 +30,7 @@ Windows support: .rar, .zip, .tar, .7z, .xz, .lzma
Note: Will not extract with 'Move Completed' enabled
"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -43,7 +43,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Label/deluge/plugins/label/core.py b/deluge/plugins/Label/deluge/plugins/label/core.py
index 3b8a36a36..b3dc778b8 100644
--- a/deluge/plugins/Label/deluge/plugins/label/core.py
+++ b/deluge/plugins/Label/deluge/plugins/label/core.py
@@ -26,40 +26,40 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
-RE_VALID = re.compile(r"[a-z0-9_\-\.]*\Z")
+RE_VALID = re.compile(r'[a-z0-9_\-\.]*\Z')
KNOWN_STATES = ['Downloading', 'Seeding', 'Paused', 'Checking', 'Queued', 'Error']
-STATE = "state"
-TRACKER = "tracker"
-KEYWORD = "keyword"
-LABEL = "label"
+STATE = 'state'
+TRACKER = 'tracker'
+KEYWORD = 'keyword'
+LABEL = 'label'
CONFIG_DEFAULTS = {
- "torrent_labels": {}, # torrent_id:label_id
- "labels": {}, # label_id:{name:value}
+ 'torrent_labels': {}, # torrent_id:label_id
+ 'labels': {}, # label_id:{name:value}
}
-CORE_OPTIONS = ["auto_add_trackers"]
+CORE_OPTIONS = ['auto_add_trackers']
OPTIONS_DEFAULTS = {
- "apply_max": False,
- "max_download_speed": -1,
- "max_upload_speed": -1,
- "max_connections": -1,
- "max_upload_slots": -1,
- "prioritize_first_last": False,
- "apply_queue": False,
- "is_auto_managed": False,
- "stop_at_ratio": False,
- "stop_ratio": 2.0,
- "remove_at_ratio": False,
- "apply_move_completed": False,
- "move_completed": False,
- "move_completed_path": "",
- "auto_add": False,
- "auto_add_trackers": []
+ 'apply_max': False,
+ 'max_download_speed': -1,
+ 'max_upload_speed': -1,
+ 'max_connections': -1,
+ 'max_upload_slots': -1,
+ 'prioritize_first_last': False,
+ 'apply_queue': False,
+ 'is_auto_managed': False,
+ 'stop_at_ratio': False,
+ 'stop_ratio': 2.0,
+ 'remove_at_ratio': False,
+ 'apply_move_completed': False,
+ 'move_completed': False,
+ 'move_completed_path': '',
+ 'auto_add': False,
+ 'auto_add_trackers': []
}
-NO_LABEL = "No Label"
+NO_LABEL = 'No Label'
def check_input(cond, message):
@@ -73,35 +73,35 @@ class Core(CorePluginBase):
self.torrent_labels = {torrent_id:label_id}
"""
def enable(self):
- log.info("*** Start Label plugin ***")
- self.plugin = component.get("CorePluginManager")
- self.plugin.register_status_field("label", self._status_get_label)
+ log.info('*** Start Label plugin ***')
+ self.plugin = component.get('CorePluginManager')
+ self.plugin.register_status_field('label', self._status_get_label)
# __init__
- core = component.get("Core")
- self.config = ConfigManager("label.conf", defaults=CONFIG_DEFAULTS)
- self.core_cfg = ConfigManager("core.conf")
+ core = component.get('Core')
+ self.config = ConfigManager('label.conf', defaults=CONFIG_DEFAULTS)
+ self.core_cfg = ConfigManager('core.conf')
# reduce typing, assigning some values to self...
self.torrents = core.torrentmanager.torrents
- self.labels = self.config["labels"]
- self.torrent_labels = self.config["torrent_labels"]
+ self.labels = self.config['labels']
+ self.torrent_labels = self.config['torrent_labels']
self.clean_initial_config()
- component.get("EventManager").register_event_handler("TorrentAddedEvent", self.post_torrent_add)
- component.get("EventManager").register_event_handler("TorrentRemovedEvent", self.post_torrent_remove)
+ component.get('EventManager').register_event_handler('TorrentAddedEvent', self.post_torrent_add)
+ component.get('EventManager').register_event_handler('TorrentRemovedEvent', self.post_torrent_remove)
# register tree:
- component.get("FilterManager").register_tree_field("label", self.init_filter_dict)
+ component.get('FilterManager').register_tree_field('label', self.init_filter_dict)
- log.debug("Label plugin enabled..")
+ log.debug('Label plugin enabled..')
def disable(self):
- self.plugin.deregister_status_field("label")
- component.get("FilterManager").deregister_tree_field("label")
- component.get("EventManager").deregister_event_handler("TorrentAddedEvent", self.post_torrent_add)
- component.get("EventManager").deregister_event_handler("TorrentRemovedEvent", self.post_torrent_remove)
+ self.plugin.deregister_status_field('label')
+ component.get('FilterManager').deregister_tree_field('label')
+ component.get('EventManager').deregister_event_handler('TorrentAddedEvent', self.post_torrent_add)
+ component.get('EventManager').deregister_event_handler('TorrentRemovedEvent', self.post_torrent_remove)
def update(self):
pass
@@ -115,17 +115,17 @@ class Core(CorePluginBase):
def post_torrent_add(self, torrent_id, from_state):
if from_state:
return
- log.debug("post_torrent_add")
+ log.debug('post_torrent_add')
torrent = self.torrents[torrent_id]
for label_id, options in self.labels.iteritems():
- if options["auto_add"]:
+ if options['auto_add']:
if self._has_auto_match(torrent, options):
self.set_torrent(torrent_id, label_id)
return
def post_torrent_remove(self, torrent_id):
- log.debug("post_torrent_remove")
+ log.debug('post_torrent_remove')
if torrent_id in self.torrent_labels:
del self.torrent_labels[torrent_id]
@@ -134,7 +134,7 @@ class Core(CorePluginBase):
"""remove invalid data from config-file"""
for torrent_id, label_id in list(self.torrent_labels.iteritems()):
if (label_id not in self.labels) or (torrent_id not in self.torrents):
- log.debug("label: rm %s:%s", torrent_id, label_id)
+ log.debug('label: rm %s:%s', torrent_id, label_id)
del self.torrent_labels[torrent_id]
def clean_initial_config(self):
@@ -168,9 +168,9 @@ class Core(CorePluginBase):
see label_set_options for more options.
"""
label_id = label_id.lower()
- check_input(RE_VALID.match(label_id), _("Invalid label, valid characters:[a-z0-9_-]"))
- check_input(label_id, _("Empty Label"))
- check_input(not (label_id in self.labels), _("Label already exists"))
+ check_input(RE_VALID.match(label_id), _('Invalid label, valid characters:[a-z0-9_-]'))
+ check_input(label_id, _('Empty Label'))
+ check_input(not (label_id in self.labels), _('Label already exists'))
self.labels[label_id] = dict(OPTIONS_DEFAULTS)
self.config.save()
@@ -178,7 +178,7 @@ class Core(CorePluginBase):
@export
def remove(self, label_id):
"""remove a label"""
- check_input(label_id in self.labels, _("Unknown Label"))
+ check_input(label_id in self.labels, _('Unknown Label'))
del self.labels[label_id]
self.clean_config()
self.config.save()
@@ -187,27 +187,27 @@ class Core(CorePluginBase):
options = self.labels[label_id]
torrent = self.torrents[torrent_id]
- if not options["move_completed_path"]:
- options["move_completed_path"] = "" # no None.
+ if not options['move_completed_path']:
+ options['move_completed_path'] = '' # no None.
- if options["apply_max"]:
- torrent.set_max_download_speed(options["max_download_speed"])
- torrent.set_max_upload_speed(options["max_upload_speed"])
- torrent.set_max_connections(options["max_connections"])
- torrent.set_max_upload_slots(options["max_upload_slots"])
- torrent.set_prioritize_first_last_pieces(options["prioritize_first_last"])
+ if options['apply_max']:
+ torrent.set_max_download_speed(options['max_download_speed'])
+ torrent.set_max_upload_speed(options['max_upload_speed'])
+ torrent.set_max_connections(options['max_connections'])
+ torrent.set_max_upload_slots(options['max_upload_slots'])
+ torrent.set_prioritize_first_last_pieces(options['prioritize_first_last'])
- if options["apply_queue"]:
+ if options['apply_queue']:
torrent.set_auto_managed(options['is_auto_managed'])
torrent.set_stop_at_ratio(options['stop_at_ratio'])
torrent.set_stop_ratio(options['stop_ratio'])
torrent.set_remove_at_ratio(options['remove_at_ratio'])
- if options["apply_move_completed"]:
+ if options['apply_move_completed']:
torrent.set_options(
{
- "move_completed": options["move_completed"],
- "move_completed_path": options["move_completed_path"]
+ 'move_completed': options['move_completed'],
+ 'move_completed_path': options['move_completed_path']
}
)
@@ -215,32 +215,32 @@ class Core(CorePluginBase):
options = self.labels[label_id]
torrent = self.torrents[torrent_id]
- if options["apply_max"]:
- torrent.set_max_download_speed(self.core_cfg.config["max_download_speed_per_torrent"])
- torrent.set_max_upload_speed(self.core_cfg.config["max_upload_speed_per_torrent"])
- torrent.set_max_connections(self.core_cfg.config["max_connections_per_torrent"])
- torrent.set_max_upload_slots(self.core_cfg.config["max_upload_slots_per_torrent"])
- torrent.set_prioritize_first_last_pieces(self.core_cfg.config["prioritize_first_last_pieces"])
+ if options['apply_max']:
+ torrent.set_max_download_speed(self.core_cfg.config['max_download_speed_per_torrent'])
+ torrent.set_max_upload_speed(self.core_cfg.config['max_upload_speed_per_torrent'])
+ torrent.set_max_connections(self.core_cfg.config['max_connections_per_torrent'])
+ torrent.set_max_upload_slots(self.core_cfg.config['max_upload_slots_per_torrent'])
+ torrent.set_prioritize_first_last_pieces(self.core_cfg.config['prioritize_first_last_pieces'])
- if options["apply_queue"]:
+ if options['apply_queue']:
torrent.set_auto_managed(self.core_cfg.config['auto_managed'])
torrent.set_stop_at_ratio(self.core_cfg.config['stop_seed_at_ratio'])
torrent.set_stop_ratio(self.core_cfg.config['stop_seed_ratio'])
torrent.set_remove_at_ratio(self.core_cfg.config['remove_seed_at_ratio'])
- if options["apply_move_completed"]:
+ if options['apply_move_completed']:
torrent.set_options(
{
- "move_completed": self.core_cfg.config["move_completed"],
- "move_completed_path": self.core_cfg.config["move_completed_path"]
+ 'move_completed': self.core_cfg.config['move_completed'],
+ 'move_completed_path': self.core_cfg.config['move_completed_path']
}
)
def _has_auto_match(self, torrent, label_options):
"""match for auto_add fields"""
- for tracker_match in label_options["auto_add_trackers"]:
+ for tracker_match in label_options['auto_add_trackers']:
for tracker in torrent.trackers:
- if tracker_match in tracker["url"]:
+ if tracker_match in tracker['url']:
return True
return False
@@ -258,10 +258,10 @@ class Core(CorePluginBase):
"move_completed_to":string() or None
}
"""
- check_input(label_id in self.labels, _("Unknown Label"))
+ check_input(label_id in self.labels, _('Unknown Label'))
for key in options_dict.keys():
if key not in OPTIONS_DEFAULTS:
- raise Exception("label: Invalid options_dict key:%s" % key)
+ raise Exception('label: Invalid options_dict key:%s' % key)
self.labels[label_id].update(options_dict)
@@ -272,7 +272,7 @@ class Core(CorePluginBase):
# auto add
options = self.labels[label_id]
- if options["auto_add"]:
+ if options['auto_add']:
for torrent_id, torrent in self.torrents.iteritems():
if self._has_auto_match(torrent, options):
self.set_torrent(torrent_id, label_id)
@@ -293,8 +293,8 @@ class Core(CorePluginBase):
if label_id == NO_LABEL:
label_id = None
- check_input((not label_id) or (label_id in self.labels), _("Unknown Label"))
- check_input(torrent_id in self.torrents, _("Unknown Torrent"))
+ check_input((not label_id) or (label_id in self.labels), _('Unknown Label'))
+ check_input(torrent_id in self.torrents, _('Unknown Torrent'))
if torrent_id in self.torrent_labels:
self._unset_torrent_options(torrent_id, self.torrent_labels[torrent_id])
@@ -322,4 +322,4 @@ class Core(CorePluginBase):
self.config.save()
def _status_get_label(self, torrent_id):
- return self.torrent_labels.get(torrent_id) or ""
+ return self.torrent_labels.get(torrent_id) or ''
diff --git a/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py b/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py
index e2c192225..a603a64bf 100644
--- a/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py
+++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/__init__.py
@@ -16,7 +16,7 @@ from . import label_config, sidebar_menu, submenu
log = logging.getLogger(__name__)
-NO_LABEL = "No Label"
+NO_LABEL = 'No Label'
def cell_data_label(column, cell, model, row, data):
@@ -29,8 +29,8 @@ class GtkUI(GtkPluginBase):
self.label_menu.on_show()
def enable(self):
- self.plugin = component.get("PluginManager")
- self.torrentmenu = component.get("MenuBar").torrentmenu
+ self.plugin = component.get('PluginManager')
+ self.torrentmenu = component.get('MenuBar').torrentmenu
self.label_menu = None
self.labelcfg = None
self.sidebar_menu = None
@@ -44,7 +44,7 @@ class GtkUI(GtkPluginBase):
self.sidebar_menu.unload()
del self.sidebar_menu
- component.get("TorrentView").remove_column(_("Label"))
+ component.get('TorrentView').remove_column(_('Label'))
def load_interface(self):
# sidebar
@@ -54,7 +54,7 @@ class GtkUI(GtkPluginBase):
# self.sidebar.load()
# menu:
- log.debug("add items to torrentview-popup menu.")
+ log.debug('add items to torrentview-popup menu.')
self.label_menu = submenu.LabelMenu()
self.torrentmenu.append(self.label_menu)
self.label_menu.show_all()
@@ -70,6 +70,6 @@ class GtkUI(GtkPluginBase):
log.debug('Finished loading Label plugin')
def load_columns(self):
- log.debug("add columns")
+ log.debug('add columns')
- component.get("TorrentView").add_text_column(_("Label"), status_field=["label"])
+ component.get('TorrentView').add_text_column(_('Label'), status_field=['label'])
diff --git a/deluge/plugins/Label/deluge/plugins/label/gtkui/label_config.py b/deluge/plugins/Label/deluge/plugins/label/gtkui/label_config.py
index 81227088d..e7af15e61 100644
--- a/deluge/plugins/Label/deluge/plugins/label/gtkui/label_config.py
+++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/label_config.py
@@ -29,29 +29,29 @@ class LabelConfig(object):
def load(self):
log.debug('Adding Label Preferences page')
- self.glade = gtk.glade.XML(self.get_resource("label_pref.glade"))
+ self.glade = gtk.glade.XML(self.get_resource('label_pref.glade'))
- self.plugin.add_preferences_page(_("Label"), self.glade.get_widget("label_prefs_box"))
- self.plugin.register_hook("on_show_prefs", self.load_settings)
- self.plugin.register_hook("on_apply_prefs", self.on_apply_prefs)
+ self.plugin.add_preferences_page(_('Label'), self.glade.get_widget('label_prefs_box'))
+ self.plugin.register_hook('on_show_prefs', self.load_settings)
+ self.plugin.register_hook('on_apply_prefs', self.on_apply_prefs)
self.load_settings()
def unload(self):
- self.plugin.remove_preferences_page(_("Label"))
- self.plugin.deregister_hook("on_apply_prefs", self.on_apply_prefs)
- self.plugin.deregister_hook("on_show_prefs", self.load_settings)
+ self.plugin.remove_preferences_page(_('Label'))
+ self.plugin.deregister_hook('on_apply_prefs', self.on_apply_prefs)
+ self.plugin.deregister_hook('on_show_prefs', self.load_settings)
def get_resource(self, filename):
return pkg_resources.resource_filename(
- "deluge.plugins.label", os.path.join("data", filename)
+ 'deluge.plugins.label', os.path.join('data', filename)
)
def load_settings(self, widget=None, data=None):
client.label.get_config().addCallback(self.cb_global_options)
def cb_global_options(self, options):
- log.debug("options=%s", options)
+ log.debug('options=%s', options)
# for id in self.chk_ids:
# self.glade.get_widget(id).set_active(bool(options[id]))
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 39aeba2c3..3ee78ea2f 100644
--- a/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py
+++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/sidebar_menu.py
@@ -18,7 +18,7 @@ from deluge.ui.client import client
log = logging.getLogger(__name__)
-NO_LABEL = "No Label"
+NO_LABEL = 'No Label'
# helpers:
@@ -26,7 +26,7 @@ def get_resource(filename):
import pkg_resources
import os
return pkg_resources.resource_filename(
- "deluge.plugins.label", os.path.join("data", filename)
+ 'deluge.plugins.label', os.path.join('data', filename)
)
@@ -34,7 +34,7 @@ def get_resource(filename):
class LabelSidebarMenu(object):
def __init__(self):
- self.treeview = component.get("FilterTreeView")
+ self.treeview = component.get('FilterTreeView')
self.menu = self.treeview.menu
self.items = []
@@ -42,27 +42,27 @@ class LabelSidebarMenu(object):
sep = gtk.SeparatorMenuItem()
self.items.append(sep)
self.menu.prepend(sep)
- self._add_item("options", _("Label _Options"), gtk.STOCK_PREFERENCES)
- self._add_item("remove", _("_Remove Label"), gtk.STOCK_REMOVE)
- self._add_item("add", _("_Add Label"), gtk.STOCK_ADD)
+ self._add_item('options', _('Label _Options'), gtk.STOCK_PREFERENCES)
+ self._add_item('remove', _('_Remove Label'), gtk.STOCK_REMOVE)
+ self._add_item('add', _('_Add Label'), gtk.STOCK_ADD)
self.menu.show_all()
# dialogs:
self.add_dialog = AddDialog()
self.options_dialog = OptionsDialog()
# hooks:
- self.menu.connect("show", self.on_show, None)
+ self.menu.connect('show', self.on_show, None)
def _add_item(self, item_id, label, stock):
"""I hate glade.
id is automatically-added as self.item_<id>
"""
- func = getattr(self, "on_%s" % item_id)
+ func = getattr(self, 'on_%s' % item_id)
item = gtk.ImageMenuItem(stock)
item.get_children()[0].set_label(label)
- item.connect("activate", func)
+ item.connect('activate', func)
self.menu.prepend(item)
- setattr(self, "item_%s" % item_id, item)
+ setattr(self, 'item_%s' % item_id, item)
self.items.append(item)
return item
@@ -76,17 +76,17 @@ class LabelSidebarMenu(object):
self.options_dialog.show(self.treeview.value)
def on_show(self, widget=None, data=None):
- "No Label:disable options/del"
- log.debug("label-sidebar-popup:on-show")
+ 'No Label:disable options/del'
+ log.debug('label-sidebar-popup:on-show')
cat = self.treeview.cat
label = self.treeview.value
- if cat == "label" or (cat == "cat" and label == "label"):
+ if cat == 'label' or (cat == 'cat' and label == 'label'):
# is a label : show menu-items
for item in self.items:
item.show()
# default items
- sensitive = ((label not in (NO_LABEL, None, "", "All")) and (cat != "cat"))
+ sensitive = ((label not in (NO_LABEL, None, '', 'All')) and (cat != 'cat'))
for item in self.items:
item.set_sensitive(sensitive)
@@ -98,11 +98,11 @@ class LabelSidebarMenu(object):
item.hide()
def unload(self):
- log.debug("disable01")
+ log.debug('disable01')
for item in list(self.items):
item.hide()
item.destroy()
- log.debug("disable02")
+ log.debug('disable02')
self.items = []
@@ -112,18 +112,18 @@ class AddDialog(object):
pass
def show(self):
- self.glade = gtk.glade.XML(get_resource("label_options.glade"))
- self.dialog = self.glade.get_widget("dlg_label_add")
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ self.glade = gtk.glade.XML(get_resource('label_options.glade'))
+ self.dialog = self.glade.get_widget('dlg_label_add')
+ self.dialog.set_transient_for(component.get('MainWindow').window)
self.glade.signal_autoconnect({
- "on_add_ok": self.on_ok,
- "on_add_cancel": self.on_cancel,
+ 'on_add_ok': self.on_ok,
+ 'on_add_cancel': self.on_cancel,
})
self.dialog.run()
def on_ok(self, event=None):
- value = self.glade.get_widget("txt_add").get_text()
+ value = self.glade.get_widget('txt_add').get_text()
client.label.add(value)
self.dialog.destroy()
@@ -132,19 +132,19 @@ 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"]
+ 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']
# list of tuples, because order matters when nesting.
sensitive_groups = [
- ("apply_max", ["max_download_speed", "max_upload_speed", "max_upload_slots", "max_connections"]),
- ("apply_queue", ["is_auto_managed", "stop_at_ratio"]),
- ("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"])
+ ('apply_max', ['max_download_speed', 'max_upload_speed', 'max_upload_slots', 'max_connections']),
+ ('apply_queue', ['is_auto_managed', 'stop_at_ratio']),
+ ('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'])
]
def __init__(self):
@@ -152,20 +152,20 @@ class OptionsDialog(object):
def show(self, label):
self.label = label
- self.glade = gtk.glade.XML(get_resource("label_options.glade"))
- self.dialog = self.glade.get_widget("dlg_label_options")
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ self.glade = gtk.glade.XML(get_resource('label_options.glade'))
+ self.dialog = self.glade.get_widget('dlg_label_options')
+ self.dialog.set_transient_for(component.get('MainWindow').window)
self.glade.signal_autoconnect({
- "on_options_ok": self.on_ok,
- "on_options_cancel": self.on_cancel,
+ 'on_options_ok': self.on_ok,
+ 'on_options_cancel': self.on_cancel,
})
# Show the label name in the header label
- self.glade.get_widget("label_header").set_markup("<b>%s:</b> %s" % (_("Label Options"), self.label))
+ self.glade.get_widget('label_header').set_markup('<b>%s:</b> %s' % (_('Label Options'), self.label))
for chk_id, group in self.sensitive_groups:
chk = self.glade.get_widget(chk_id)
- chk.connect("toggled", self.apply_sensitivity)
+ chk.connect('toggled', self.apply_sensitivity)
client.label.get_options(self.label).addCallback(self.load_options)
@@ -180,20 +180,20 @@ class OptionsDialog(object):
self.glade.get_widget(chk_id).set_active(bool(options[chk_id]))
if client.is_localhost():
- self.glade.get_widget("move_completed_path").set_filename(options["move_completed_path"])
- self.glade.get_widget("move_completed_path").show()
- self.glade.get_widget("move_completed_path_entry").hide()
+ self.glade.get_widget('move_completed_path').set_filename(options['move_completed_path'])
+ self.glade.get_widget('move_completed_path').show()
+ self.glade.get_widget('move_completed_path_entry').hide()
else:
- self.glade.get_widget("move_completed_path_entry").set_text(options["move_completed_path"])
- self.glade.get_widget("move_completed_path_entry").show()
- self.glade.get_widget("move_completed_path").hide()
+ self.glade.get_widget('move_completed_path_entry').set_text(options['move_completed_path'])
+ self.glade.get_widget('move_completed_path_entry').show()
+ self.glade.get_widget('move_completed_path').hide()
- self.glade.get_widget("auto_add_trackers").get_buffer().set_text("\n".join(options["auto_add_trackers"]))
+ self.glade.get_widget('auto_add_trackers').get_buffer().set_text('\n'.join(options['auto_add_trackers']))
self.apply_sensitivity()
def on_ok(self, event=None):
- "save options.."
+ 'save options..'
options = {}
for spin_id in self.spin_ids:
@@ -204,13 +204,13 @@ class OptionsDialog(object):
options[chk_id] = self.glade.get_widget(chk_id).get_active()
if client.is_localhost():
- options["move_completed_path"] = self.glade.get_widget("move_completed_path").get_filename()
+ options['move_completed_path'] = self.glade.get_widget('move_completed_path').get_filename()
else:
- options["move_completed_path"] = self.glade.get_widget("move_completed_path_entry").get_text()
+ options['move_completed_path'] = self.glade.get_widget('move_completed_path_entry').get_text()
- buff = self.glade.get_widget("auto_add_trackers").get_buffer() # sometimes I hate gtk...
- tracker_lst = buff.get_text(buff.get_start_iter(), buff.get_end_iter()).strip().split("\n")
- options["auto_add_trackers"] = [x for x in tracker_lst if x] # filter out empty lines.
+ buff = self.glade.get_widget('auto_add_trackers').get_buffer() # sometimes I hate gtk...
+ tracker_lst = buff.get_text(buff.get_start_iter(), buff.get_end_iter()).strip().split('\n')
+ options['auto_add_trackers'] = [x for x in tracker_lst if x] # filter out empty lines.
log.debug(options)
client.label.set_options(self.label, options)
@@ -219,7 +219,7 @@ class OptionsDialog(object):
def apply_sensitivity(self, event=None):
for chk_id, sensitive_list in self.sensitive_groups:
chk = self.glade.get_widget(chk_id)
- sens = chk.get_active() and chk.get_property("sensitive")
+ sens = chk.get_active() and chk.get_property('sensitive')
for widget_id in sensitive_list:
self.glade.get_widget(widget_id).set_sensitive(sens)
diff --git a/deluge/plugins/Label/deluge/plugins/label/gtkui/submenu.py b/deluge/plugins/Label/deluge/plugins/label/gtkui/submenu.py
index cb38deca1..0a4e89221 100644
--- a/deluge/plugins/Label/deluge/plugins/label/gtkui/submenu.py
+++ b/deluge/plugins/Label/deluge/plugins/label/gtkui/submenu.py
@@ -21,26 +21,26 @@ log = logging.getLogger(__name__)
# Deferred Translation
def _(message):
return message
-NO_LABEL = _("No Label")
+NO_LABEL = _('No Label')
del _
class LabelMenu(gtk.MenuItem):
def __init__(self):
- gtk.MenuItem.__init__(self, _("Label"))
+ gtk.MenuItem.__init__(self, _('Label'))
self.sub_menu = gtk.Menu()
self.set_submenu(self.sub_menu)
self.items = []
# attach..
- self.sub_menu.connect("show", self.on_show, None)
+ self.sub_menu.connect('show', self.on_show, None)
def get_torrent_ids(self):
- return component.get("TorrentView").get_selected_torrents()
+ return component.get('TorrentView').get_selected_torrents()
def on_show(self, widget=None, data=None):
- log.debug("label-on-show")
+ log.debug('label-on-show')
client.label.get_labels().addCallback(self.cb_labels)
def cb_labels(self, labels):
@@ -50,12 +50,12 @@ class LabelMenu(gtk.MenuItem):
if label == NO_LABEL:
item = gtk.MenuItem(_(NO_LABEL))
else:
- item = gtk.MenuItem(label.replace("_", "__"))
- item.connect("activate", self.on_select_label, label)
+ item = gtk.MenuItem(label.replace('_', '__'))
+ item.connect('activate', self.on_select_label, label)
self.sub_menu.append(item)
self.show_all()
def on_select_label(self, widget=None, label_id=None):
- log.debug("select label:%s,%s", label_id, self.get_torrent_ids())
+ log.debug('select label:%s,%s', label_id, self.get_torrent_ids())
for torrent_id in self.get_torrent_ids():
client.label.set_torrent(torrent_id, label_id)
diff --git a/deluge/plugins/Label/deluge/plugins/label/test.py b/deluge/plugins/Label/deluge/plugins/label/test.py
index 8fa3f2a1b..bdb6f6d2a 100644
--- a/deluge/plugins/Label/deluge/plugins/label/test.py
+++ b/deluge/plugins/Label/deluge/plugins/label/test.py
@@ -19,32 +19,32 @@ sclient.set_core_uri()
print(sclient.get_enabled_plugins())
# enable plugin.
-if "label" not in sclient.get_enabled_plugins():
- sclient.enable_plugin("label")
+if 'label' not in sclient.get_enabled_plugins():
+ sclient.enable_plugin('label')
# test labels.
-print("#init labels")
+print('#init labels')
try:
- sclient.label_remove("test")
+ sclient.label_remove('test')
except Exception:
pass
sess_id = sclient.get_session_state()[0]
-print("#add")
-sclient.label_add("test")
-print("#set")
-sclient.label_set_torrent(id, "test")
+print('#add')
+sclient.label_add('test')
+print('#set')
+sclient.label_set_torrent(id, 'test')
-print(sclient.get_torrents_status({"label": "test"}, "name"))
+print(sclient.get_torrents_status({'label': 'test'}, 'name'))
-print("#set options")
-sclient.label_set_options("test", {"max_download_speed": 999}, True)
-print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "999")
-sclient.label_set_options("test", {"max_download_speed": 9}, True)
-print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "9")
-sclient.label_set_options("test", {"max_download_speed": 888}, False)
-print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "9 (888)")
+print('#set options')
+sclient.label_set_options('test', {'max_download_speed': 999}, True)
+print(sclient.get_torrent_status(sess_id, ['max_download_speed']), '999')
+sclient.label_set_options('test', {'max_download_speed': 9}, True)
+print(sclient.get_torrent_status(sess_id, ['max_download_speed']), '9')
+sclient.label_set_options('test', {'max_download_speed': 888}, False)
+print(sclient.get_torrent_status(sess_id, ['max_download_speed']), '9 (888)')
print(sclient.get_torrent_status(sess_id, ['name', 'tracker_host', 'label']))
diff --git a/deluge/plugins/Label/deluge/plugins/label/webui.py b/deluge/plugins/Label/deluge/plugins/label/webui.py
index 3415cf469..421470ba3 100644
--- a/deluge/plugins/Label/deluge/plugins/label/webui.py
+++ b/deluge/plugins/Label/deluge/plugins/label/webui.py
@@ -22,11 +22,11 @@ log = logging.getLogger(__name__)
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.label",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.label',
+ os.path.join('data', filename))
class WebUI(WebPluginBase):
- scripts = [get_resource("label.js")]
+ scripts = [get_resource('label.js')]
debug_scripts = scripts
diff --git a/deluge/plugins/Label/setup.py b/deluge/plugins/Label/setup.py
index 7b8f2d9dd..b69438d0b 100644
--- a/deluge/plugins/Label/setup.py
+++ b/deluge/plugins/Label/setup.py
@@ -9,19 +9,19 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Label"
-__author__ = "Martijn Voncken"
-__author_email__ = "mvoncken@gmail.com"
-__version__ = "0.2"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Allows labels to be assigned to torrents"
+__plugin_name__ = 'Label'
+__author__ = 'Martijn Voncken'
+__author_email__ = 'mvoncken@gmail.com'
+__version__ = '0.2'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Allows labels to be assigned to torrents'
__long_description__ = """
Allows labels to be assigned to torrents
Also offers filters on state, tracker and keywords
"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -34,7 +34,7 @@ setup(
long_description=__long_description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/common.py b/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
index 191cb9e12..bc3f7578c 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/common.py
@@ -30,17 +30,17 @@ except ImportError:
def get_resource(filename):
import os
import pkg_resources
- return pkg_resources.resource_filename("deluge.plugins.notifications", os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.notifications', os.path.join('data', filename))
class CustomNotifications(object):
def __init__(self, plugin_name=None):
self.custom_notifications = {
- "email": {},
- "popup": {},
- "blink": {},
- "sound": {}
+ 'email': {},
+ 'popup': {},
+ 'blink': {},
+ 'sound': {}
}
def enable(self):
@@ -55,9 +55,9 @@ class CustomNotifications(object):
def _handle_custom_providers(self, kind, eventtype, *args, **kwargs):
log.debug("Calling CORE's custom %s providers for %s: %s %s",
kind, eventtype, args, kwargs)
- if eventtype in self.config["subscriptions"][kind]:
+ if eventtype in self.config['subscriptions'][kind]:
wrapper, handler = self.custom_notifications[kind][eventtype]
- log.debug("Found handler for kind %s: %s", kind, handler)
+ log.debug('Found handler for kind %s: %s', kind, handler)
custom_notif_func = getattr(self,
'handle_custom_%s_notification' % kind)
d = defer.maybeDeferred(handler, *args, **kwargs)
@@ -68,7 +68,7 @@ class CustomNotifications(object):
def _register_custom_provider(self, kind, eventtype, handler):
if not self._handled_eventtype(eventtype, handler):
- return defer.succeed("Event not handled")
+ return defer.succeed('Event not handled')
if eventtype not in self.custom_notifications:
def wrapper(*args, **kwargs):
return self._handle_custom_providers(kind, eventtype, *args, **kwargs)
@@ -76,7 +76,7 @@ class CustomNotifications(object):
else:
wrapper, handler = self.custom_notifications[kind][eventtype]
try:
- component.get("EventManager").register_event_handler(
+ component.get('EventManager').register_event_handler(
eventtype, wrapper
)
except KeyError:
@@ -87,7 +87,7 @@ class CustomNotifications(object):
try:
wrapper, handler = self.custom_notifications[kind][eventtype]
try:
- component.get("EventManager").deregister_event_handler(
+ component.get('EventManager').deregister_event_handler(
eventtype, wrapper
)
except KeyError:
@@ -104,15 +104,15 @@ 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
def _on_notify_sucess(self, result, kind):
- log.debug("Notification success using %s: %s", kind, result)
+ log.debug('Notification success using %s: %s', kind, result)
return result
def _on_notify_failure(self, failure, kind):
- log.debug("Notification failure using %s: %s", kind, failure)
+ log.debug('Notification failure using %s: %s', kind, failure)
return failure
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
index 3af5d4b7d..d4de6b7ef 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/core.py
@@ -29,17 +29,17 @@ from .common import CustomNotifications
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "smtp_enabled": False,
- "smtp_host": "",
- "smtp_port": 25,
- "smtp_user": "",
- "smtp_pass": "",
- "smtp_from": "",
- "smtp_tls": False, # SSL or TLS
- "smtp_recipients": [],
+ 'smtp_enabled': False,
+ 'smtp_host': '',
+ 'smtp_port': 25,
+ 'smtp_user': '',
+ 'smtp_pass': '',
+ 'smtp_from': '',
+ 'smtp_tls': False, # SSL or TLS
+ 'smtp_recipients': [],
# Subscriptions
- "subscriptions": {
- "email": []
+ 'subscriptions': {
+ 'email': []
}
}
@@ -73,9 +73,9 @@ class CoreNotifications(CustomNotifications):
def handle_custom_email_notification(self, result, eventtype):
if not self.config['smtp_enabled']:
- return defer.succeed("SMTP notification not enabled.")
+ return defer.succeed('SMTP notification not enabled.')
subject, message = result
- log.debug("Spawning new thread to send email with subject: %s: %s",
+ 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.
@@ -90,11 +90,11 @@ class CoreNotifications(CustomNotifications):
continue
classdoc = known_events[evt].__doc__.strip()
handled_events.append((evt, classdoc))
- log.debug("Handled Notification Events: %s", handled_events)
+ log.debug('Handled Notification Events: %s', handled_events)
return handled_events
def _notify_email(self, subject='', message=''):
- log.debug("Email prepared")
+ log.debug('Email prepared')
to_addrs = self.config['smtp_recipients']
to_addrs_str = ', '.join(self.config['smtp_recipients'])
headers_dict = {
@@ -115,9 +115,9 @@ Date: %(date)s
try:
# Python 2.6
- server = smtplib.SMTP(self.config["smtp_host"], self.config["smtp_port"], timeout=60)
+ server = smtplib.SMTP(self.config['smtp_host'], self.config['smtp_port'], timeout=60)
except Exception as ex:
- err_msg = _("There was an error sending the notification email: %s") % ex
+ err_msg = _('There was an error sending the notification email: %s') % ex
log.error(err_msg)
return ex
@@ -126,7 +126,7 @@ Date: %(date)s
if security_enabled:
server.ehlo()
if 'starttls' not in server.esmtp_features:
- log.warning("TLS/SSL enabled but server does not support it")
+ log.warning('TLS/SSL enabled but server does not support it')
else:
server.starttls()
server.ehlo()
@@ -136,12 +136,12 @@ Date: %(date)s
server.login(self.config['smtp_user'], self.config['smtp_pass'])
except smtplib.SMTPHeloError as ex:
err_msg = _("The server didn't reply properly to the helo "
- "greeting: %s") % ex
+ 'greeting: %s') % ex
log.error(err_msg)
return ex
except smtplib.SMTPAuthenticationError as ex:
err_msg = _("The server didn't accept the username/password "
- "combination: %s") % ex
+ 'combination: %s') % ex
log.error(err_msg)
return ex
@@ -149,8 +149,8 @@ Date: %(date)s
try:
server.sendmail(self.config['smtp_from'], to_addrs, message)
except smtplib.SMTPException as ex:
- err_msg = _("There was an error sending the notification email:"
- " %s") % ex
+ err_msg = _('There was an error sending the notification email:'
+ ' %s') % ex
log.error(err_msg)
return ex
finally:
@@ -164,20 +164,20 @@ Date: %(date)s
pass
else:
server.quit()
- return _("Notification email sent.")
+ return _('Notification email sent.')
def _on_torrent_finished_event(self, torrent_id):
- log.debug("Handler for TorrentFinishedEvent called for CORE")
- torrent = component.get("TorrentManager")[torrent_id]
+ log.debug('Handler for TorrentFinishedEvent called for CORE')
+ torrent = component.get('TorrentManager')[torrent_id]
torrent_status = torrent.get_status({})
# Email
subject = _("Finished Torrent \"%(name)s\"") % torrent_status
message = _(
- "This email is to inform you that Deluge has finished "
+ 'This email is to inform you that Deluge has finished '
"downloading \"%(name)s\", which includes %(num_files)i files."
- "\nTo stop receiving these alerts, simply turn off email "
+ '\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
@@ -197,23 +197,23 @@ class Core(CorePluginBase, CoreNotifications):
def enable(self):
CoreNotifications.enable(self)
self.config = deluge.configmanager.ConfigManager(
- "notifications-core.conf", DEFAULT_PREFS)
- log.debug("ENABLING CORE NOTIFICATIONS")
+ 'notifications-core.conf', DEFAULT_PREFS)
+ log.debug('ENABLING CORE NOTIFICATIONS')
def disable(self):
- log.debug("DISABLING CORE NOTIFICATIONS")
+ log.debug('DISABLING CORE NOTIFICATIONS')
CoreNotifications.disable(self)
@export
def set_config(self, config):
- "sets the config dictionary"
+ 'sets the config dictionary'
for key in config.keys():
self.config[key] = config[key]
self.config.save()
@export
def get_config(self):
- "returns the config dictionary"
+ 'returns the config dictionary'
return self.config.config
@export
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
index f225e87bf..faf3a1080 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/gtkui.py
@@ -48,20 +48,20 @@ except ImportError:
DEFAULT_PREFS = {
# BLINK
- "blink_enabled": False,
+ 'blink_enabled': False,
# FLASH
- "flash_enabled": False,
+ 'flash_enabled': False,
# POPUP
- "popup_enabled": False,
+ 'popup_enabled': False,
# SOUND
- "sound_enabled": False,
- "sound_path": "",
- "custom_sounds": {},
+ 'sound_enabled': False,
+ 'sound_path': '',
+ 'custom_sounds': {},
# Subscriptions
- "subscriptions": {
- "popup": [],
- "blink": [],
- "sound": [],
+ 'subscriptions': {
+ 'popup': [],
+ 'blink': [],
+ 'sound': [],
},
}
@@ -79,19 +79,19 @@ 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):
- self.deregister_custom_blink_notification("TorrentFinishedEvent")
- self.deregister_custom_sound_notification("TorrentFinishedEvent")
- self.deregister_custom_popup_notification("TorrentFinishedEvent")
+ self.deregister_custom_blink_notification('TorrentFinishedEvent')
+ self.deregister_custom_sound_notification('TorrentFinishedEvent')
+ self.deregister_custom_popup_notification('TorrentFinishedEvent')
CustomNotifications.disable(self)
def register_custom_popup_notification(self, eventtype, handler):
@@ -146,7 +146,7 @@ class GtkUiNotifications(CustomNotifications):
if result:
return defer.maybeDeferred(self.__blink)
return defer.succeed("Won't blink. The returned value from the custom "
- "handler was: %s" % result)
+ 'handler was: %s' % result)
def handle_custom_sound_notification(self, result, eventtype):
if isinstance(result, basestring):
@@ -155,33 +155,33 @@ class GtkUiNotifications(CustomNotifications):
self.__play_sound, self.config['custom_sounds'][eventtype])
return defer.maybeDeferred(self.__play_sound, result)
return defer.succeed("Won't play sound. The returned value from the "
- "custom handler was: %s" % result)
+ 'custom handler was: %s' % result)
def __blink(self):
self.systray.blink(True)
- return defer.succeed(_("Notification Blink shown"))
+ return defer.succeed(_('Notification Blink shown'))
def __popup(self, title='', message=''):
if not self.config['popup_enabled']:
- return defer.succeed(_("Popup notification is not enabled."))
+ return defer.succeed(_('Popup notification is not enabled.'))
if not POPUP_AVAILABLE:
- return defer.fail(_("pynotify is not installed"))
+ return defer.fail(_('pynotify is not installed'))
- if pynotify.init("Deluge"):
- icon = gtk.gdk.pixbuf_new_from_file_at_size(deluge.common.get_pixmap("deluge.svg"), 48, 48)
+ if pynotify.init('Deluge'):
+ icon = gtk.gdk.pixbuf_new_from_file_at_size(deluge.common.get_pixmap('deluge.svg'), 48, 48)
self.note = pynotify.Notification(title, message)
self.note.set_icon_from_pixbuf(icon)
if not self.note.show():
- err_msg = _("pynotify failed to show notification")
+ err_msg = _('pynotify failed to show notification')
log.warning(err_msg)
return defer.fail(err_msg)
- return defer.succeed(_("Notification popup shown"))
+ return defer.succeed(_('Notification popup shown'))
def __play_sound(self, sound_path=''):
if not self.config['sound_enabled']:
- return defer.succeed(_("Sound notification not enabled"))
+ return defer.succeed(_('Sound notification not enabled'))
if not SOUND_AVAILABLE:
- err_msg = _("pygame is not installed")
+ err_msg = _('pygame is not installed')
log.warning(err_msg)
return defer.fail(err_msg)
@@ -193,11 +193,11 @@ class GtkUiNotifications(CustomNotifications):
alert_sound.load(sound_path)
alert_sound.play()
except pygame.error as ex:
- err_msg = _("Sound notification failed %s") % ex
+ err_msg = _('Sound notification failed %s') % ex
log.warning(err_msg)
return defer.fail(err_msg)
else:
- msg = _("Sound notification Success")
+ msg = _('Sound notification Success')
log.info(msg)
return defer.succeed(msg)
@@ -209,21 +209,21 @@ class GtkUiNotifications(CustomNotifications):
return ''
def _on_torrent_finished_event_popup(self, torrent_id):
- d = client.core.get_torrent_status(torrent_id, ["name", "file_progress"])
+ d = client.core.get_torrent_status(torrent_id, ['name', 'file_progress'])
d.addCallback(self._on_torrent_finished_event_got_torrent_status)
d.addErrback(self._on_torrent_finished_event_torrent_status_failure)
return d
def _on_torrent_finished_event_torrent_status_failure(self, failure):
- log.debug("Failed to get torrent status to be able to show the popup")
+ 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")
- title = _("Finished Torrent")
- torrent_status["num_files"] = torrent_status["file_progress"].count(1.0)
+ 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
+ 'has finished downloading.') % torrent_status
return title, message
@@ -234,11 +234,11 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def enable(self):
self.config = deluge.configmanager.ConfigManager(
- "notifications-gtk.conf", DEFAULT_PREFS
+ 'notifications-gtk.conf', DEFAULT_PREFS
)
- self.glade = gtk.glade.XML(get_resource("config.glade"))
- self.glade.get_widget("smtp_port").set_value(25)
- self.prefs = self.glade.get_widget("prefs_box")
+ self.glade = gtk.glade.XML(get_resource('config.glade'))
+ self.glade.get_widget('smtp_port').set_value(25)
+ self.prefs = self.glade.get_widget('prefs_box')
self.prefs.show_all()
self.build_recipients_model_populate_treeview()
@@ -261,25 +261,25 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
'on_sound_path_update_preview': self.on_sound_path_update_preview
})
- prefs = component.get("Preferences")
+ prefs = component.get('Preferences')
parent = self.prefs.get_parent()
if parent:
parent.remove(self.prefs)
index = prefs.notebook.append_page(self.prefs)
- prefs.liststore.append([index, _("Notifications")])
+ prefs.liststore.append([index, _('Notifications')])
- component.get("PluginManager").register_hook("on_apply_prefs",
+ component.get('PluginManager').register_hook('on_apply_prefs',
self.on_apply_prefs)
- component.get("PluginManager").register_hook("on_show_prefs",
+ component.get('PluginManager').register_hook('on_show_prefs',
self.on_show_prefs)
if not POPUP_AVAILABLE:
- self.glade.get_widget("popup_enabled").set_property('sensitive',
+ self.glade.get_widget('popup_enabled').set_property('sensitive',
False)
if not SOUND_AVAILABLE:
# for widget_name in ('sound_enabled', 'sound_path', 'sounds_page', 'sounds_page_label'):
# self.glade.get_widget(widget_name).set_property('sensitive', False)
- self.glade.get_widget("sound_enabled").set_property('sensitive',
+ self.glade.get_widget('sound_enabled').set_property('sensitive',
False)
self.glade.get_widget('sound_path').set_property('sensitive', False)
self.glade.get_widget('sounds_page').set_property('sensitive',
@@ -287,7 +287,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.glade.get_widget('sounds_page_label').set_property('sensitive',
False)
- self.systray = component.get("SystemTray")
+ self.systray = component.get('SystemTray')
if not hasattr(self.systray, 'tray'):
# Tray is not beeing used
self.glade.get_widget('blink_enabled').set_property('sensitive',
@@ -297,25 +297,25 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def disable(self):
GtkUiNotifications.disable(self)
- component.get("Preferences").remove_page(_("Notifications"))
- component.get("PluginManager").deregister_hook("on_apply_prefs",
+ 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",
+ 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.glade.get_widget("smtp_recipients")
+ self.recipients_treeview = self.glade.get_widget('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,
+ 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.set_expand(True)
@@ -327,32 +327,32 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
self.sounds_treeview = self.glade.get_widget('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)
self.sounds_model = gtk.ListStore(str, str, str, str)
renderer = gtk.CellRendererText()
- renderer.set_data("event", SND_EVENT)
- column = gtk.TreeViewColumn("Event", renderer, text=SND_EVENT)
+ renderer.set_data('event', SND_EVENT)
+ column = gtk.TreeViewColumn('Event', renderer, text=SND_EVENT)
column.set_expand(True)
self.sounds_treeview.append_column(column)
renderer = gtk.CellRendererText()
- renderer.set_data("event_doc", SND_EVENT_DOC)
- column = gtk.TreeViewColumn("Doc", renderer, text=SND_EVENT_DOC)
+ renderer.set_data('event_doc', SND_EVENT_DOC)
+ column = gtk.TreeViewColumn('Doc', renderer, text=SND_EVENT_DOC)
column.set_property('visible', False)
self.sounds_treeview.append_column(column)
renderer = gtk.CellRendererText()
- renderer.set_data("sound_name", SND_NAME)
- column = gtk.TreeViewColumn("Name", renderer, text=SND_NAME)
+ renderer.set_data('sound_name', SND_NAME)
+ column = gtk.TreeViewColumn('Name', renderer, text=SND_NAME)
self.sounds_treeview.append_column(column)
renderer = gtk.CellRendererText()
- renderer.set_data("sound_path", SND_PATH)
- column = gtk.TreeViewColumn("Path", renderer, text=SND_PATH)
+ renderer.set_data('sound_path', SND_PATH)
+ column = gtk.TreeViewColumn('Path', renderer, text=SND_PATH)
column.set_property('visible', False)
self.sounds_treeview.append_column(column)
@@ -360,51 +360,51 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def build_notifications_model_populate_treeview(self):
# Notification Subscriptions treeview/model
- self.subscriptions_treeview = self.glade.get_widget("subscriptions_treeview")
+ self.subscriptions_treeview = self.glade.get_widget('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)
renderer = gtk.CellRendererText()
- renderer.set_data("event", SUB_EVENT)
- column = gtk.TreeViewColumn("Event", renderer, text=SUB_EVENT)
+ renderer.set_data('event', SUB_EVENT)
+ column = gtk.TreeViewColumn('Event', renderer, text=SUB_EVENT)
column.set_expand(True)
self.subscriptions_treeview.append_column(column)
renderer = gtk.CellRendererText()
- renderer.set_data("event_doc", SUB_EVENT)
- column = gtk.TreeViewColumn("Doc", renderer, text=SUB_EVENT_DOC)
+ renderer.set_data('event_doc', SUB_EVENT)
+ column = gtk.TreeViewColumn('Doc', renderer, text=SUB_EVENT_DOC)
column.set_property('visible', False)
self.subscriptions_treeview.append_column(column)
renderer = gtk.CellRendererToggle()
renderer.set_property('activatable', True)
renderer.connect('toggled', self._on_email_col_toggled)
- column = gtk.TreeViewColumn("Email", renderer, active=SUB_NOT_EMAIL)
+ column = gtk.TreeViewColumn('Email', renderer, active=SUB_NOT_EMAIL)
column.set_clickable(True)
self.subscriptions_treeview.append_column(column)
renderer = gtk.CellRendererToggle()
- renderer.set_property("activatable", True)
- renderer.connect("toggled", self._on_popup_col_toggled)
- column = gtk.TreeViewColumn("Popup", renderer, active=SUB_NOT_POPUP)
+ renderer.set_property('activatable', True)
+ renderer.connect('toggled', self._on_popup_col_toggled)
+ column = gtk.TreeViewColumn('Popup', renderer, active=SUB_NOT_POPUP)
column.set_clickable(True)
self.subscriptions_treeview.append_column(column)
renderer = gtk.CellRendererToggle()
- renderer.set_property("activatable", True)
- renderer.connect("toggled", self._on_blink_col_toggled)
- column = gtk.TreeViewColumn("Blink", renderer, active=SUB_NOT_BLINK)
+ renderer.set_property('activatable', True)
+ renderer.connect('toggled', self._on_blink_col_toggled)
+ column = gtk.TreeViewColumn('Blink', renderer, active=SUB_NOT_BLINK)
column.set_clickable(True)
self.subscriptions_treeview.append_column(column)
renderer = gtk.CellRendererToggle()
renderer.set_property('activatable', True)
renderer.connect('toggled', self._on_sound_col_toggled)
- column = gtk.TreeViewColumn("Sound", renderer, active=SUB_NOT_SOUND)
+ column = gtk.TreeViewColumn('Sound', renderer, active=SUB_NOT_SOUND)
column.set_clickable(True)
self.subscriptions_treeview.append_column(column)
self.subscriptions_treeview.set_model(self.subscriptions_model)
@@ -444,13 +444,13 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
SUB_EVENT, event_name,
SUB_EVENT_DOC, event_doc,
SUB_NOT_EMAIL, event_name in email_subscriptions,
- SUB_NOT_POPUP, event_name in subscriptions_dict["popup"],
+ 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']
)
def on_apply_prefs(self):
- log.debug("applying prefs for Notifications")
+ log.debug('applying prefs for Notifications')
current_popup_subscriptions = []
current_blink_subscriptions = []
@@ -467,8 +467,8 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
current_sound_subscriptions.append(event)
old_sound_file = self.config['sound_path']
- new_sound_file = self.glade.get_widget("sound_path").get_filename()
- log.debug("Old Default sound file: %s New one: %s",
+ new_sound_file = self.glade.get_widget('sound_path').get_filename()
+ 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:
@@ -478,30 +478,30 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
custom_sounds[event_name] = filepath
self.config.config.update({
- "popup_enabled": self.glade.get_widget("popup_enabled").get_active(),
- "blink_enabled": self.glade.get_widget("blink_enabled").get_active(),
- "sound_enabled": self.glade.get_widget("sound_enabled").get_active(),
- "sound_path": new_sound_file,
- "subscriptions": {
- "popup": current_popup_subscriptions,
- "blink": current_blink_subscriptions,
- "sound": current_sound_subscriptions
+ 'popup_enabled': self.glade.get_widget('popup_enabled').get_active(),
+ 'blink_enabled': self.glade.get_widget('blink_enabled').get_active(),
+ 'sound_enabled': self.glade.get_widget('sound_enabled').get_active(),
+ 'sound_path': new_sound_file,
+ 'subscriptions': {
+ 'popup': current_popup_subscriptions,
+ 'blink': current_blink_subscriptions,
+ 'sound': current_sound_subscriptions
},
- "custom_sounds": custom_sounds
+ 'custom_sounds': custom_sounds
})
self.config.save()
core_config = {
- "smtp_enabled": self.glade.get_widget("smtp_enabled").get_active(),
- "smtp_host": self.glade.get_widget("smtp_host").get_text(),
- "smtp_port": self.glade.get_widget("smtp_port").get_value(),
- "smtp_user": self.glade.get_widget("smtp_user").get_text(),
- "smtp_pass": self.glade.get_widget("smtp_pass").get_text(),
- "smtp_from": self.glade.get_widget("smtp_from").get_text(),
- "smtp_tls": self.glade.get_widget("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_enabled': self.glade.get_widget('smtp_enabled').get_active(),
+ 'smtp_host': self.glade.get_widget('smtp_host').get_text(),
+ 'smtp_port': self.glade.get_widget('smtp_port').get_value(),
+ 'smtp_user': self.glade.get_widget('smtp_user').get_text(),
+ 'smtp_pass': self.glade.get_widget('smtp_pass').get_text(),
+ 'smtp_from': self.glade.get_widget('smtp_from').get_text(),
+ 'smtp_tls': self.glade.get_widget('smtp_tls').get_active(),
+ '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)
@@ -511,37 +511,37 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
client.notifications.get_config().addCallback(self.cb_get_config)
def cb_get_config(self, core_config):
- "callback for on show_prefs"
- self.glade.get_widget("smtp_host").set_text(core_config["smtp_host"])
- self.glade.get_widget("smtp_port").set_value(core_config["smtp_port"])
- self.glade.get_widget("smtp_user").set_text(core_config["smtp_user"])
- self.glade.get_widget("smtp_pass").set_text(core_config["smtp_pass"])
- self.glade.get_widget("smtp_from").set_text(core_config["smtp_from"])
- self.glade.get_widget("smtp_tls").set_active(core_config["smtp_tls"])
+ 'callback for on show_prefs'
+ self.glade.get_widget('smtp_host').set_text(core_config['smtp_host'])
+ self.glade.get_widget('smtp_port').set_value(core_config['smtp_port'])
+ self.glade.get_widget('smtp_user').set_text(core_config['smtp_user'])
+ self.glade.get_widget('smtp_pass').set_text(core_config['smtp_pass'])
+ self.glade.get_widget('smtp_from').set_text(core_config['smtp_from'])
+ self.glade.get_widget('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.glade.get_widget("smtp_enabled").set_active(
+ self.glade.get_widget('smtp_enabled').set_active(
core_config['smtp_enabled']
)
- self.glade.get_widget("sound_enabled").set_active(
+ self.glade.get_widget('sound_enabled').set_active(
self.config['sound_enabled']
)
- self.glade.get_widget("popup_enabled").set_active(
+ self.glade.get_widget('popup_enabled').set_active(
self.config['popup_enabled']
)
- self.glade.get_widget("blink_enabled").set_active(
+ self.glade.get_widget('blink_enabled').set_active(
self.config['blink_enabled']
)
if self.config['sound_path']:
sound_path = self.config['sound_path']
else:
sound_path = deluge.common.get_default_download_dir()
- self.glade.get_widget("sound_path").set_filename(sound_path)
+ self.glade.get_widget('sound_path').set_filename(sound_path)
# Force toggle
- self.on_enabled_toggled(self.glade.get_widget("smtp_enabled"))
+ self.on_enabled_toggled(self.glade.get_widget('smtp_enabled'))
self.on_sound_enabled_toggled(self.glade.get_widget('sound_enabled'))
client.notifications.get_handled_events().addCallback(
@@ -557,7 +557,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def on_add_button_clicked(self, widget, treeview):
model = treeview.get_model()
model.set(model.append(),
- RECIPIENT_FIELD, "USER@HOST",
+ RECIPIENT_FIELD, 'USER@HOST',
RECIPIENT_EDIT, True)
def on_delete_button_clicked(self, widget, treeview):
@@ -573,53 +573,53 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
def on_recipients_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected()
if selected_connection_iter:
- self.glade.get_widget("delete_button").set_property('sensitive',
+ self.glade.get_widget('delete_button').set_property('sensitive',
True)
else:
- self.glade.get_widget("delete_button").set_property('sensitive',
+ self.glade.get_widget('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.glade.get_widget("delete_button").set_property('sensitive',
+ self.glade.get_widget('delete_button').set_property('sensitive',
True)
else:
- self.glade.get_widget("delete_button").set_property('sensitive',
+ self.glade.get_widget('delete_button').set_property('sensitive',
False)
def on_sounds_treeview_selection_changed(self, selection):
model, selected_iter = selection.get_selected()
if selected_iter:
- self.glade.get_widget("sounds_edit_button").set_property("sensitive", True)
+ self.glade.get_widget('sounds_edit_button').set_property('sensitive', True)
path = model.get(selected_iter, SND_PATH)[0]
- log.debug("Sound selection changed: %s", path)
+ log.debug('Sound selection changed: %s', path)
if path != self.config['sound_path']:
- self.glade.get_widget("sounds_revert_button").set_property("sensitive", True)
+ self.glade.get_widget('sounds_revert_button').set_property('sensitive', True)
else:
- self.glade.get_widget("sounds_revert_button").set_property("sensitive", False)
+ self.glade.get_widget('sounds_revert_button').set_property('sensitive', False)
else:
- self.glade.get_widget("sounds_edit_button").set_property("sensitive", False)
- self.glade.get_widget("sounds_revert_button").set_property("sensitive", False)
+ self.glade.get_widget('sounds_edit_button').set_property('sensitive', False)
+ self.glade.get_widget('sounds_revert_button').set_property('sensitive', False)
def on_sounds_revert_button_clicked(self, widget):
- log.debug("on_sounds_revert_button_clicked")
+ log.debug('on_sounds_revert_button_clicked')
selection = self.sounds_treeview.get_selection()
model, selected_iter = selection.get_selected()
if selected_iter:
- log.debug("on_sounds_revert_button_clicked: got 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']))
def on_sounds_edit_button_clicked(self, widget):
- log.debug("on_sounds_edit_button_clicked")
+ log.debug('on_sounds_edit_button_clicked')
selection = self.sounds_treeview.get_selection()
model, selected_iter = selection.get_selected()
if selected_iter:
path = model.get(selected_iter, SND_PATH)[0]
dialog = gtk.FileChooserDialog(
- title=_("Choose Sound File"),
+ title=_('Choose Sound File'),
buttons=(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN,
@@ -638,7 +638,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
d = defer.maybeDeferred(dialog.run)
d.addCallback(update_model)
- log.debug("dialog should have been shown")
+ 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',
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/test.py b/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
index cf58ee325..3a488be67 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/test.py
@@ -37,16 +37,16 @@ class TestEmailNotifications(component.Component):
self.events_classes = []
def enable(self):
- log.debug("\n\nEnabling %s", self.__class__.__name__)
+ log.debug('\n\nEnabling %s', self.__class__.__name__)
for event in self.events:
if self.__imp == 'core':
# component.get("CorePlugin.Notifications").register_custom_email_notification(
- component.get("Notifications").register_custom_email_notification(
+ component.get('Notifications').register_custom_email_notification(
event.__class__.__name__,
self.custom_email_message_provider
)
elif self.__imp == 'gtk':
- notifications_component = component.get("Notifications")
+ notifications_component = component.get('Notifications')
notifications_component.register_custom_popup_notification(
event.__class__.__name__,
self.custom_popup_message_provider
@@ -63,32 +63,32 @@ class TestEmailNotifications(component.Component):
self.lc.start(60, False)
def disable(self):
- log.debug("\n\nDisabling %s", self.__class__.__name__)
+ log.debug('\n\nDisabling %s', self.__class__.__name__)
self.lc.stop()
def update(self):
if self.__imp == 'core':
- log.debug("\n\nUpdating %s", self.__class__.__name__)
+ log.debug('\n\nUpdating %s', self.__class__.__name__)
self.events.append(self.events.pop(0)) # Re-Queue
self.n += 1
- component.get("EventManager").emit(self.events[0])
+ component.get('EventManager').emit(self.events[0])
def custom_email_message_provider(self, *evt_args, **evt_kwargs):
- log.debug("Running custom email message provider: %s %s", evt_args, evt_kwargs)
- subject = "%s Email Subject: %s" % (self.events[0].__class__.__name__, self.n)
- message = "%s Email Message: %s" % (self.events[0].__class__.__name__, self.n)
+ log.debug('Running custom email message provider: %s %s', evt_args, evt_kwargs)
+ subject = '%s Email Subject: %s' % (self.events[0].__class__.__name__, self.n)
+ message = '%s Email Message: %s' % (self.events[0].__class__.__name__, self.n)
return subject, message
def custom_popup_message_provider(self, *evt_args, **evt_kwargs):
- log.debug("Running custom popup message provider: %s %s", evt_args, evt_kwargs)
- title = "%s Popup Title: %s" % (self.events[0].__class__.__name__, self.n)
- message = "%s Popup Message: %s" % (self.events[0].__class__.__name__, self.n)
+ log.debug('Running custom popup message provider: %s %s', evt_args, evt_kwargs)
+ title = '%s Popup Title: %s' % (self.events[0].__class__.__name__, self.n)
+ message = '%s Popup Message: %s' % (self.events[0].__class__.__name__, self.n)
return title, message
def custom_blink_message_provider(self, *evt_args, **evt_kwargs):
- log.debug("Running custom blink message provider: %s %s", evt_args, evt_kwargs)
+ log.debug('Running custom blink message provider: %s %s', evt_args, evt_kwargs)
return True
def custom_sound_message_provider(self, *evt_args, **evt_kwargs):
- log.debug("Running custom sound message provider: %s %s", evt_args, evt_kwargs)
+ log.debug('Running custom sound message provider: %s %s', evt_args, evt_kwargs)
return ''
diff --git a/deluge/plugins/Notifications/deluge/plugins/notifications/webui.py b/deluge/plugins/Notifications/deluge/plugins/notifications/webui.py
index f65bdaaff..9ce1b0012 100644
--- a/deluge/plugins/Notifications/deluge/plugins/notifications/webui.py
+++ b/deluge/plugins/Notifications/deluge/plugins/notifications/webui.py
@@ -23,11 +23,11 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("notifications.js")]
+ scripts = [get_resource('notifications.js')]
debug_scripts = scripts
def enable(self):
- log.debug("Enabling Web UI notifications")
+ log.debug('Enabling Web UI notifications')
def disable(self):
- log.debug("Disabling Web UI notifications")
+ log.debug('Disabling Web UI notifications')
diff --git a/deluge/plugins/Notifications/setup.py b/deluge/plugins/Notifications/setup.py
index d2d0a21d4..9c94dd34b 100755
--- a/deluge/plugins/Notifications/setup.py
+++ b/deluge/plugins/Notifications/setup.py
@@ -14,13 +14,13 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Notifications"
-__author__ = "Pedro Algarvio"
-__author_email__ = "pedro@algarvio.me"
-__version__ = "0.2"
-__url__ = "http://dev.deluge-torrent.org/"
-__license__ = "GPLv3"
-__description__ = "Plugin which provides notifications to Deluge."
+__plugin_name__ = 'Notifications'
+__author__ = 'Pedro Algarvio'
+__author_email__ = 'pedro@algarvio.me'
+__version__ = '0.2'
+__url__ = 'http://dev.deluge-torrent.org/'
+__license__ = 'GPLv3'
+__description__ = 'Plugin which provides notifications to Deluge.'
__long_description__ = """
Plugin which provides notifications to Deluge
@@ -29,7 +29,7 @@ Email, Popup, Blink and Sound notifications
The plugin also allows other plugins to make
use of itself for their own custom notifications
"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -42,7 +42,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(exclude=['**/test.py']),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/common.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/common.py
index d963eb70a..8c11465d0 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/common.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/common.py
@@ -15,4 +15,4 @@
def get_resource(filename):
import os
import pkg_resources
- return pkg_resources.resource_filename("deluge.plugins.scheduler", os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.scheduler', os.path.join('data', filename))
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
index d3b3a2777..448621886 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/core.py
@@ -25,26 +25,26 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "low_down": -1.0,
- "low_up": -1.0,
- "low_active": -1,
- "low_active_down": -1,
- "low_active_up": -1,
- "button_state": [[0] * 7 for dummy in xrange(24)]
+ 'low_down': -1.0,
+ 'low_up': -1.0,
+ 'low_active': -1,
+ 'low_active_down': -1,
+ 'low_active_up': -1,
+ 'button_state': [[0] * 7 for dummy in xrange(24)]
}
STATES = {
- 0: "Green",
- 1: "Yellow",
- 2: "Red"
+ 0: 'Green',
+ 1: 'Yellow',
+ 2: 'Red'
}
CONTROLLED_SETTINGS = [
- "max_download_speed",
- "max_upload_speed",
- "max_active_limit",
- "max_active_downloading",
- "max_active_seeding"
+ 'max_download_speed',
+ 'max_upload_speed',
+ 'max_active_limit',
+ 'max_active_downloading',
+ 'max_active_seeding'
]
@@ -62,14 +62,14 @@ class SchedulerEvent(DelugeEvent):
class Core(CorePluginBase):
def enable(self):
# Create the defaults with the core config
- core_config = component.get("Core").config
- DEFAULT_PREFS["low_down"] = core_config["max_download_speed"]
- DEFAULT_PREFS["low_up"] = core_config["max_upload_speed"]
- DEFAULT_PREFS["low_active"] = core_config["max_active_limit"]
- DEFAULT_PREFS["low_active_down"] = core_config["max_active_downloading"]
- DEFAULT_PREFS["low_active_up"] = core_config["max_active_seeding"]
+ core_config = component.get('Core').config
+ DEFAULT_PREFS['low_down'] = core_config['max_download_speed']
+ DEFAULT_PREFS['low_up'] = core_config['max_upload_speed']
+ DEFAULT_PREFS['low_active'] = core_config['max_active_limit']
+ DEFAULT_PREFS['low_active_down'] = core_config['max_active_downloading']
+ DEFAULT_PREFS['low_active_up'] = core_config['max_active_seeding']
- self.config = deluge.configmanager.ConfigManager("scheduler.conf", DEFAULT_PREFS)
+ self.config = deluge.configmanager.ConfigManager('scheduler.conf', DEFAULT_PREFS)
self.state = self.get_state()
@@ -82,12 +82,12 @@ class Core(CorePluginBase):
self.timer = reactor.callLater(secs_to_next_hour, self.do_schedule)
# Register for config changes so state isn't overridden
- component.get("EventManager").register_event_handler("ConfigValueChangedEvent", self.on_config_value_changed)
+ component.get('EventManager').register_event_handler('ConfigValueChangedEvent', self.on_config_value_changed)
def disable(self):
if self.timer.active():
self.timer.cancel()
- component.get("EventManager").deregister_event_handler("ConfigValueChangedEvent", self.on_config_value_changed)
+ component.get('EventManager').deregister_event_handler('ConfigValueChangedEvent', self.on_config_value_changed)
self.__apply_set_functions()
def update(self):
@@ -101,11 +101,11 @@ class Core(CorePluginBase):
"""
Have the core apply it's bandwidth settings as specified in core.conf.
"""
- core_config = deluge.configmanager.ConfigManager("core.conf")
+ core_config = deluge.configmanager.ConfigManager('core.conf')
for setting in CONTROLLED_SETTINGS:
- component.get("PreferencesManager").do_config_set_func(setting, core_config[setting])
+ component.get('PreferencesManager').do_config_set_func(setting, core_config[setting])
# Resume the session if necessary
- component.get("Core").resume_session()
+ component.get('Core').resume_session()
def do_schedule(self, timer=True):
"""
@@ -114,30 +114,30 @@ class Core(CorePluginBase):
state = self.get_state()
- if state == "Green":
+ if state == 'Green':
# This is Green (Normal) so we just make sure we've applied the
# global defaults
self.__apply_set_functions()
- elif state == "Yellow":
+ elif state == 'Yellow':
# This is Yellow (Slow), so use the settings provided from the user
settings = {
- "active_limit": self.config["low_active"],
- "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)
+ 'active_limit': self.config['low_active'],
+ '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)
}
- component.get("Core").apply_session_settings(settings)
+ component.get('Core').apply_session_settings(settings)
# Resume the session if necessary
- component.get("Core").resume_session()
- elif state == "Red":
+ component.get('Core').resume_session()
+ elif state == 'Red':
# This is Red (Stop), so pause the libtorrent session
- component.get("Core").pause_session()
+ component.get('Core').pause_session()
if state != self.state:
# The state has changed since last update so we need to emit an event
self.state = state
- component.get("EventManager").emit(SchedulerEvent(self.state))
+ component.get('EventManager').emit(SchedulerEvent(self.state))
if timer:
# Call this again in 1 hour
@@ -145,7 +145,7 @@ class Core(CorePluginBase):
@export()
def set_config(self, config):
- "sets the config dictionary"
+ 'sets the config dictionary'
for key in config.keys():
self.config[key] = config[key]
self.config.save()
@@ -153,11 +153,11 @@ class Core(CorePluginBase):
@export()
def get_config(self):
- "returns the config dictionary"
+ 'returns the config dictionary'
return self.config.config
@export()
def get_state(self):
now = time.localtime(time.time())
- level = self.config["button_state"][now[3]][now[6]]
+ level = self.config['button_state'][now[3]][now[6]]
return STATES[level]
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
index d48b21b50..2dc058332 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/gtkui.py
@@ -25,7 +25,7 @@ from .common import get_resource
log = logging.getLogger(__name__)
-DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
+DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
class SchedulerSelectWidget(gtk.DrawingArea):
@@ -34,11 +34,11 @@ class SchedulerSelectWidget(gtk.DrawingArea):
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)
- self.connect("button_release_event", self.mouse_up)
- self.connect("motion_notify_event", self.mouse_hover)
- self.connect("leave_notify_event", self.mouse_leave)
+ self.connect('expose_event', self.expose)
+ self.connect('button_press_event', self.mouse_down)
+ self.connect('button_release_event', self.mouse_up)
+ 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],
@@ -124,8 +124,8 @@ class SchedulerSelectWidget(gtk.DrawingArea):
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")
+ ' ' + 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]]]
@@ -138,7 +138,7 @@ class SchedulerSelectWidget(gtk.DrawingArea):
# clear hover text on mouse leave
def mouse_leave(self, widget, event):
- self.hover_label.set_text("")
+ self.hover_label.set_text('')
self.hover_point = [-1, -1]
@@ -146,63 +146,63 @@ class GtkUI(GtkPluginBase):
def enable(self):
self.create_prefs_page()
- component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs)
- component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs)
- self.statusbar = component.get("StatusBar")
+ component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs)
+ self.statusbar = component.get('StatusBar')
self.status_item = self.statusbar.add_item(
- image=get_resource("green.png"),
- text="",
+ image=get_resource('green.png'),
+ text='',
callback=self.on_status_item_clicked,
- tooltip="Scheduler")
+ tooltip='Scheduler')
def on_state_deferred(state):
self.state = state
self.on_scheduler_event(state)
client.scheduler.get_state().addCallback(on_state_deferred)
- client.register_event_handler("SchedulerEvent", self.on_scheduler_event)
+ client.register_event_handler('SchedulerEvent', self.on_scheduler_event)
def disable(self):
- component.get("Preferences").remove_page(_("Scheduler"))
+ component.get('Preferences').remove_page(_('Scheduler'))
# Reset statusbar dict.
- self.statusbar.config_value_changed_dict["max_download_speed"] = self.statusbar._on_max_download_speed
- self.statusbar.config_value_changed_dict["max_upload_speed"] = self.statusbar._on_max_upload_speed
+ self.statusbar.config_value_changed_dict['max_download_speed'] = self.statusbar._on_max_download_speed
+ self.statusbar.config_value_changed_dict['max_upload_speed'] = self.statusbar._on_max_upload_speed
# Remove statusbar item.
self.statusbar.remove_item(self.status_item)
del self.status_item
- 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 on_apply_prefs(self):
- log.debug("applying prefs for Scheduler")
+ log.debug('applying prefs for Scheduler')
config = {}
- config["low_down"] = self.spin_download.get_value()
- config["low_up"] = self.spin_upload.get_value()
- config["low_active"] = self.spin_active.get_value_as_int()
- config["low_active_down"] = self.spin_active_down.get_value_as_int()
- config["low_active_up"] = self.spin_active_up.get_value_as_int()
- config["button_state"] = self.scheduler_select.button_state
+ config['low_down'] = self.spin_download.get_value()
+ config['low_up'] = self.spin_upload.get_value()
+ config['low_active'] = self.spin_active.get_value_as_int()
+ config['low_active_down'] = self.spin_active_down.get_value_as_int()
+ config['low_active_up'] = self.spin_active_up.get_value_as_int()
+ config['button_state'] = self.scheduler_select.button_state
client.scheduler.set_config(config)
def on_show_prefs(self):
def on_get_config(config):
- log.debug("config: %s", config)
- self.scheduler_select.set_button_state(config["button_state"])
- self.spin_download.set_value(config["low_down"])
- self.spin_upload.set_value(config["low_up"])
- self.spin_active.set_value(config["low_active"])
- self.spin_active_down.set_value(config["low_active_down"])
- self.spin_active_up.set_value(config["low_active_up"])
+ log.debug('config: %s', config)
+ self.scheduler_select.set_button_state(config['button_state'])
+ self.spin_download.set_value(config['low_down'])
+ self.spin_upload.set_value(config['low_up'])
+ self.spin_active.set_value(config['low_active'])
+ self.spin_active_down.set_value(config['low_active_down'])
+ self.spin_active_up.set_value(config['low_active_up'])
client.scheduler.get_config().addCallback(on_get_config)
def on_scheduler_event(self, state):
self.state = state
- self.status_item.set_image_from_file(get_resource(self.state.lower() + ".png"))
- if self.state == "Yellow":
+ self.status_item.set_image_from_file(get_resource(self.state.lower() + '.png'))
+ if self.state == 'Yellow':
# Prevent func calls in Statusbar if the config changes.
- self.statusbar.config_value_changed_dict.pop("max_download_speed", None)
- self.statusbar.config_value_changed_dict.pop("max_upload_speed", None)
+ self.statusbar.config_value_changed_dict.pop('max_download_speed', None)
+ self.statusbar.config_value_changed_dict.pop('max_upload_speed', None)
try:
self.statusbar._on_max_download_speed(self.spin_download.get_value())
self.statusbar._on_max_upload_speed(self.spin_upload.get_value())
@@ -210,20 +210,20 @@ class GtkUI(GtkPluginBase):
# Skip error due to Plugin being enabled before statusbar items created on startup.
pass
else:
- self.statusbar.config_value_changed_dict["max_download_speed"] = self.statusbar._on_max_download_speed
- self.statusbar.config_value_changed_dict["max_upload_speed"] = self.statusbar._on_max_upload_speed
+ self.statusbar.config_value_changed_dict['max_download_speed'] = self.statusbar._on_max_download_speed
+ self.statusbar.config_value_changed_dict['max_upload_speed'] = self.statusbar._on_max_upload_speed
def update_config_values(config):
try:
- self.statusbar._on_max_download_speed(config["max_download_speed"])
- self.statusbar._on_max_upload_speed(config["max_upload_speed"])
+ self.statusbar._on_max_download_speed(config['max_download_speed'])
+ self.statusbar._on_max_upload_speed(config['max_upload_speed'])
except AttributeError:
# Skip error due to Plugin being enabled before statusbar items created on startup.
pass
- client.core.get_config_values(["max_download_speed", "max_upload_speed"]).addCallback(update_config_values)
+ client.core.get_config_values(['max_download_speed', 'max_upload_speed']).addCallback(update_config_values)
def on_status_item_clicked(self, widget, event):
- component.get("Preferences").show("Scheduler")
+ component.get('Preferences').show('Scheduler')
# Configuration dialog
def create_prefs_page(self):
@@ -240,7 +240,7 @@ class GtkUI(GtkPluginBase):
hbox.pack_start(self.scheduler_select, True, True)
frame = gtk.Frame()
label = gtk.Label()
- label.set_markup("<b>Schedule</b>")
+ label.set_markup('<b>Schedule</b>')
frame.set_label_widget(label)
frame.set_shadow_type(gtk.SHADOW_NONE)
frame.add(hbox)
@@ -250,7 +250,7 @@ class GtkUI(GtkPluginBase):
table = gtk.Table(3, 4)
- label = gtk.Label(_("Download Limit:"))
+ label = gtk.Label(_('Download Limit:'))
label.set_alignment(0.0, 0.6)
table.attach(label, 0, 1, 0, 1, gtk.FILL)
self.spin_download = gtk.SpinButton()
@@ -259,7 +259,7 @@ class GtkUI(GtkPluginBase):
self.spin_download.set_increments(1, 10)
table.attach(self.spin_download, 1, 2, 0, 1, gtk.FILL)
- label = gtk.Label(_("Upload Limit:"))
+ label = gtk.Label(_('Upload Limit:'))
label.set_alignment(0.0, 0.6)
table.attach(label, 0, 1, 1, 2, gtk.FILL)
self.spin_upload = gtk.SpinButton()
@@ -268,7 +268,7 @@ class GtkUI(GtkPluginBase):
self.spin_upload.set_increments(1, 10)
table.attach(self.spin_upload, 1, 2, 1, 2, gtk.FILL)
- label = gtk.Label(_("Active Torrents:"))
+ label = gtk.Label(_('Active Torrents:'))
label.set_alignment(0.0, 0.6)
table.attach(label, 2, 3, 0, 1, gtk.FILL)
self.spin_active = gtk.SpinButton()
@@ -277,7 +277,7 @@ class GtkUI(GtkPluginBase):
self.spin_active.set_increments(1, 10)
table.attach(self.spin_active, 3, 4, 0, 1, gtk.FILL)
- label = gtk.Label(_("Active Downloading:"))
+ label = gtk.Label(_('Active Downloading:'))
label.set_alignment(0.0, 0.6)
table.attach(label, 2, 3, 1, 2, gtk.FILL)
self.spin_active_down = gtk.SpinButton()
@@ -286,7 +286,7 @@ class GtkUI(GtkPluginBase):
self.spin_active_down.set_increments(1, 10)
table.attach(self.spin_active_down, 3, 4, 1, 2, gtk.FILL)
- label = gtk.Label(_("Active Seeding:"))
+ label = gtk.Label(_('Active Seeding:'))
label.set_alignment(0.0, 0.6)
table.attach(label, 2, 3, 2, 3, gtk.FILL)
self.spin_active_up = gtk.SpinButton()
@@ -296,16 +296,16 @@ class GtkUI(GtkPluginBase):
table.attach(self.spin_active_up, 3, 4, 2, 3, gtk.FILL)
eventbox = gtk.EventBox()
- eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#EDD400"))
+ eventbox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#EDD400'))
eventbox.add(table)
frame = gtk.Frame()
label = gtk.Label()
- label.set_markup(_("<b>Slow Settings</b>"))
+ label.set_markup(_('<b>Slow Settings</b>'))
frame.set_label_widget(label)
- frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#CDB400"))
+ frame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#CDB400'))
frame.set_border_width(2)
frame.add(eventbox)
vbox.pack_start(frame, False, False)
vbox.show_all()
- component.get("Preferences").add_page(_("Scheduler"), vbox)
+ component.get('Preferences').add_page(_('Scheduler'), vbox)
diff --git a/deluge/plugins/Scheduler/deluge/plugins/scheduler/webui.py b/deluge/plugins/Scheduler/deluge/plugins/scheduler/webui.py
index 50db1b450..9991f96b6 100644
--- a/deluge/plugins/Scheduler/deluge/plugins/scheduler/webui.py
+++ b/deluge/plugins/Scheduler/deluge/plugins/scheduler/webui.py
@@ -23,5 +23,5 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("scheduler.js")]
+ scripts = [get_resource('scheduler.js')]
debug_scripts = scripts
diff --git a/deluge/plugins/Scheduler/setup.py b/deluge/plugins/Scheduler/setup.py
index 0c1c5ec83..c5ab60a8a 100644
--- a/deluge/plugins/Scheduler/setup.py
+++ b/deluge/plugins/Scheduler/setup.py
@@ -13,15 +13,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Scheduler"
-__author__ = "Andrew Resch"
-__author_email__ = "andrewresch@gmail.com"
-__version__ = "0.2"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Schedule limits on a per-hour per-day basis."
+__plugin_name__ = 'Scheduler'
+__author__ = 'Andrew Resch'
+__author_email__ = 'andrewresch@gmail.com'
+__version__ = '0.2'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Schedule limits on a per-hour per-day basis.'
__long_description__ = """"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -34,7 +34,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/common.py b/deluge/plugins/Stats/deluge/plugins/stats/common.py
index e930dfe69..79d9df535 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/common.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/common.py
@@ -13,4 +13,4 @@ import pkg_resources
def get_resource(filename):
- return pkg_resources.resource_filename("deluge.plugins.stats", os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.stats', os.path.join('data', filename))
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/core.py b/deluge/plugins/Stats/deluge/plugins/stats/core.py
index cbb556c32..48e1ec30d 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/core.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/core.py
@@ -23,17 +23,17 @@ from deluge.core.rpcserver import export
from deluge.plugins.pluginbase import CorePluginBase
DEFAULT_PREFS = {
- "test": "NiNiNi",
- "update_interval": 1, # 2 seconds.
- "length": 150, # 2 seconds * 150 --> 5 minutes.
+ 'test': 'NiNiNi',
+ 'update_interval': 1, # 2 seconds.
+ 'length': 150, # 2 seconds * 150 --> 5 minutes.
}
DEFAULT_TOTALS = {
- "total_upload": 0,
- "total_download": 0,
- "total_payload_upload": 0,
- "total_payload_download": 0,
- "stats": {}
+ 'total_upload': 0,
+ 'total_download': 0,
+ 'total_payload_upload': 0,
+ 'total_payload_download': 0,
+ 'stats': {}
}
log = logging.getLogger(__name__)
@@ -57,8 +57,8 @@ class Core(CorePluginBase):
totals = {} # class var to catch only updating this once per session in enable.
def enable(self):
- log.debug("Stats plugin enabled")
- self.core = component.get("Core")
+ log.debug('Stats plugin enabled')
+ self.core = component.get('Core')
self.stats = {}
self.count = {}
self.intervals = [1, 5, 30, 300]
@@ -70,12 +70,12 @@ class Core(CorePluginBase):
self.last_update[i] = t
self.count[i] = 0
- self.config = configmanager.ConfigManager("stats.conf", DEFAULT_PREFS)
- self.saved_stats = configmanager.ConfigManager("stats.totals", DEFAULT_TOTALS)
+ self.config = configmanager.ConfigManager('stats.conf', DEFAULT_PREFS)
+ self.saved_stats = configmanager.ConfigManager('stats.totals', DEFAULT_TOTALS)
if self.totals == {}:
self.totals.update(self.saved_stats.config)
- self.length = self.config["length"]
+ self.length = self.config['length']
# self.stats = get_key(self.saved_stats, "stats") or {}
self.stats_keys = []
@@ -92,7 +92,7 @@ class Core(CorePluginBase):
self.update_stats()
self.update_timer = LoopingCall(self.update_stats)
- self.update_timer.start(self.config["update_interval"])
+ self.update_timer.start(self.config['update_interval'])
self.save_timer = LoopingCall(self.save_stats)
self.save_timer.start(60)
@@ -124,10 +124,10 @@ class Core(CorePluginBase):
stats.update(self.core.get_session_status([key]))
except AttributeError:
pass
- stats["num_connections"] = stats["num_peers"]
- stats.update(self.core.get_config_values(["max_download",
- "max_upload",
- "max_num_connections"]))
+ stats['num_connections'] = stats['num_peers']
+ 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:
@@ -166,16 +166,16 @@ class Core(CorePluginBase):
update_interval(300, 30, 10)
except Exception as ex:
- log.error("Stats update error %s", ex)
+ log.error('Stats update error %s', ex)
return True
def save_stats(self):
try:
- self.saved_stats["stats"] = self.stats
+ self.saved_stats['stats'] = self.stats
self.saved_stats.config.update(self.get_totals())
self.saved_stats.save()
except Exception as ex:
- log.error("Stats save error %s", ex)
+ log.error('Stats save error %s', ex)
return True
# export:
@@ -189,9 +189,9 @@ class Core(CorePluginBase):
if key in self.stats[interval]:
stats_dict[key] = self.stats[interval][key]
- stats_dict["_last_update"] = self.last_update[interval]
- stats_dict["_length"] = self.config["length"]
- stats_dict["_update_interval"] = interval
+ stats_dict['_last_update'] = self.last_update[interval]
+ stats_dict['_length'] = self.config['length']
+ stats_dict['_update_interval'] = interval
return stats_dict
@export
@@ -206,25 +206,25 @@ class Core(CorePluginBase):
def get_session_totals(self):
status = self.core.session.status()
return {
- "total_upload": status.total_upload,
- "total_download": status.total_download,
- "total_payload_upload": status.total_payload_upload,
- "total_payload_download": status.total_payload_download
+ 'total_upload': status.total_upload,
+ 'total_download': status.total_download,
+ 'total_payload_upload': status.total_payload_upload,
+ 'total_payload_download': status.total_payload_download
}
@export
def set_config(self, config):
- "sets the config dictionary"
+ 'sets the config dictionary'
for key in config.keys():
self.config[key] = config[key]
self.config.save()
@export
def get_config(self):
- "returns the config dictionary"
+ 'returns the config dictionary'
return self.config.config
@export
def get_intervals(self):
- "Returns the available resolutions"
+ 'Returns the available resolutions'
return self.intervals
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/graph.py b/deluge/plugins/Stats/deluge/plugins/stats/graph.py
index 86682b9cc..d2027c701 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/graph.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/graph.py
@@ -88,12 +88,12 @@ class Graph(object):
}
def set_stats(self, stats):
- self.last_update = stats["_last_update"]
- del stats["_last_update"]
- self.length = stats["_length"]
- del stats["_length"]
- self.interval = stats["_update_interval"]
- del stats["_update_interval"]
+ self.last_update = stats['_last_update']
+ del stats['_last_update']
+ self.length = stats['_length']
+ del stats['_length']
+ self.interval = stats['_update_interval']
+ del stats['_update_interval']
self.stats = stats
return
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py b/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
index 968114aa8..6262e6875 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/gtkui.py
@@ -36,17 +36,17 @@ DEFAULT_CONF = {
'version': 1,
'colors': {
'bandwidth_graph': {
- 'upload_rate': str(gtk.gdk.Color("blue")),
- 'download_rate': str(gtk.gdk.Color("green")),
+ 'upload_rate': str(gtk.gdk.Color('blue')),
+ 'download_rate': str(gtk.gdk.Color('green')),
},
'connections_graph': {
- 'dht_nodes': str(gtk.gdk.Color("orange")),
- 'dht_cache_nodes': str(gtk.gdk.Color("blue")),
- 'dht_torrents': str(gtk.gdk.Color("green")),
- 'num_connections': str(gtk.gdk.Color("darkred")),
+ 'dht_nodes': str(gtk.gdk.Color('orange')),
+ 'dht_cache_nodes': str(gtk.gdk.Color('blue')),
+ 'dht_torrents': str(gtk.gdk.Color('green')),
+ 'num_connections': str(gtk.gdk.Color('darkred')),
},
'seeds_graph': {
- 'num_peers': str(gtk.gdk.Color("blue")),
+ 'num_peers': str(gtk.gdk.Color('blue')),
}}}
@@ -54,13 +54,13 @@ def neat_time(column, cell, model, data):
"""Render seconds as seconds or minutes with label"""
seconds = model.get_value(data, 0)
if seconds > 60:
- text = "%d %s" % (seconds // 60, _("minutes"))
+ text = '%d %s' % (seconds // 60, _('minutes'))
elif seconds == 60:
- text = _("1 minute")
+ text = _('1 minute')
elif seconds == 1:
- text = _("1 second")
+ text = _('1 second')
else:
- text = "%d %s" % (seconds, _("seconds"))
+ text = '%d %s' % (seconds, _('seconds'))
cell.set_property('text', text)
return
@@ -114,7 +114,7 @@ class GraphsTab(Tab):
cell = gtk.CellRendererText()
self.intervals_combo.pack_start(cell, True)
self.intervals_combo.set_cell_data_func(cell, neat_time)
- self.intervals_combo.connect("changed", self._on_selected_interval_changed)
+ self.intervals_combo.connect('changed', self._on_selected_interval_changed)
self.update_intervals()
def graph_expose(self, widget, event):
@@ -145,7 +145,7 @@ class GraphsTab(Tab):
client.stats.get_intervals().addCallback(self._on_intervals_changed)
def select_bandwidth_graph(self):
- log.debug("Selecting bandwidth graph")
+ log.debug('Selecting bandwidth graph')
self.graph_widget = self.bandwidth_graph
self.graph = Graph()
colors = self.colors['bandwidth_graph']
@@ -157,7 +157,7 @@ class GraphsTab(Tab):
formatter_scale=size_formatter_scale)
def select_connections_graph(self):
- log.debug("Selecting connections graph")
+ log.debug('Selecting connections graph')
self.graph_widget = self.connections_graph
g = Graph()
self.graph = g
@@ -169,7 +169,7 @@ class GraphsTab(Tab):
g.set_left_axis(formatter=int_str, min=10)
def select_seeds_graph(self):
- log.debug("Selecting connections graph")
+ log.debug('Selecting connections graph')
self.graph_widget = self.seeds_graph
self.graph = Graph()
colors = self.colors['seeds_graph']
@@ -219,32 +219,32 @@ class GraphsTab(Tab):
class GtkUI(GtkPluginBase):
def enable(self):
- log.debug("Stats plugin enable called")
- self.config = deluge.configmanager.ConfigManager("stats.gtkui.conf", DEFAULT_CONF)
- self.glade = XML(common.get_resource("config.glade"))
- component.get("Preferences").add_page("Stats", self.glade.get_widget("prefs_box"))
- component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs)
- component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs)
+ log.debug('Stats plugin enable called')
+ self.config = deluge.configmanager.ConfigManager('stats.gtkui.conf', DEFAULT_CONF)
+ self.glade = XML(common.get_resource('config.glade'))
+ component.get('Preferences').add_page('Stats', self.glade.get_widget('prefs_box'))
+ component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs)
self.on_show_prefs()
- self.graphs_tab = GraphsTab(XML(common.get_resource("tabs.glade")), self.config['colors'])
+ self.graphs_tab = GraphsTab(XML(common.get_resource('tabs.glade')), self.config['colors'])
self.torrent_details = component.get('TorrentDetails')
self.torrent_details.add_tab(self.graphs_tab)
def disable(self):
- component.get("Preferences").remove_page("Stats")
- 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('Preferences').remove_page('Stats')
+ component.get('PluginManager').deregister_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').deregister_hook('on_show_prefs', self.on_show_prefs)
self.torrent_details.remove_tab(self.graphs_tab.get_name())
def on_apply_prefs(self):
- log.debug("applying prefs for Stats")
+ log.debug('applying prefs for Stats')
gtkconf = {}
for graph, colors in self.config['colors'].items():
gtkconf[graph] = {}
for value, color in colors.items():
try:
- color_btn = self.glade.get_widget("%s_%s_color" % (graph, value))
+ color_btn = self.glade.get_widget('%s_%s_color' % (graph, value))
gtkconf[graph][value] = str(color_btn.get_color())
except Exception:
gtkconf[graph][value] = DEFAULT_CONF['colors'][graph][value]
@@ -258,12 +258,12 @@ class GtkUI(GtkPluginBase):
for graph, colors in self.config['colors'].items():
for value, color in colors.items():
try:
- color_btn = self.glade.get_widget("%s_%s_color" % (graph, value))
+ color_btn = self.glade.get_widget('%s_%s_color' % (graph, value))
color_btn.set_color(gtk.gdk.Color(color))
except Exception:
- log.debug("Unable to set %s %s %s", graph, value, color)
+ log.debug('Unable to set %s %s %s', graph, value, color)
client.stats.get_config().addCallback(self.cb_get_config)
def cb_get_config(self, config):
- "callback for on show_prefs"
+ 'callback for on show_prefs'
pass
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 36bd1c235..2ceb75c6f 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/tests/test_stats.py
@@ -21,9 +21,9 @@ def print_totals(totals):
for name, value in totals.iteritems():
print(name, fsize(value))
- print("overhead:")
- print("up:", fsize(totals["total_upload"] - totals["total_payload_upload"]))
- print("down:", fsize(totals["total_download"] - totals["total_payload_download"]))
+ print('overhead:')
+ print('up:', fsize(totals['total_upload'] - totals['total_payload_upload']))
+ print('down:', fsize(totals['total_download'] - totals['total_payload_download']))
class StatsTestCase(BaseTestCase):
@@ -32,7 +32,7 @@ class StatsTestCase(BaseTestCase):
defer.setDebugging(True)
tests_common.set_tmp_config_dir()
client.start_standalone()
- client.core.enable_plugin("Stats")
+ client.core.enable_plugin('Stats')
return component.start()
def tear_down(self):
@@ -42,8 +42,8 @@ class StatsTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_client_totals(self):
plugins = yield client.core.get_available_plugins()
- if "Stats" not in plugins:
- raise unittest.SkipTest("WebUi plugin not available for testing")
+ if 'Stats' not in plugins:
+ raise unittest.SkipTest('WebUi plugin not available for testing')
totals = yield client.stats.get_totals()
self.assertEquals(totals['total_upload'], 0)
@@ -55,8 +55,8 @@ class StatsTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_session_totals(self):
plugins = yield client.core.get_available_plugins()
- if "Stats" not in plugins:
- raise unittest.SkipTest("WebUi plugin not available for testing")
+ if 'Stats' not in plugins:
+ raise unittest.SkipTest('WebUi plugin not available for testing')
totals = yield client.stats.get_session_totals()
self.assertEquals(totals['total_upload'], 0)
@@ -82,7 +82,7 @@ class StatsTestCase(BaseTestCase):
from deluge.ui.gtkui.torrentview import TorrentView
from deluge.plugins.Stats.deluge.plugins.stats import graph, gtkui
- ConfigManager("gtkui.conf", defaults=DEFAULT_PREFS)
+ ConfigManager('gtkui.conf', defaults=DEFAULT_PREFS)
self.plugins = PluginManager()
MainWindow()
@@ -97,7 +97,7 @@ class StatsTestCase(BaseTestCase):
def write(self, data):
self.data.append(data)
- stats_gtkui = gtkui.GtkUI("test_stats")
+ stats_gtkui = gtkui.GtkUI('test_stats')
stats_gtkui.enable()
yield stats_gtkui.graphs_tab.update()
@@ -109,6 +109,6 @@ class StatsTestCase(BaseTestCase):
surface = g.draw(900, 150)
file_like = FakeFile()
surface.write_to_png(file_like)
- data = "".join(file_like.data)
- with open("file_like.png", "wb") as _file:
+ data = ''.join(file_like.data)
+ with open('file_like.png', 'wb') as _file:
_file.write(data)
diff --git a/deluge/plugins/Stats/deluge/plugins/stats/webui.py b/deluge/plugins/Stats/deluge/plugins/stats/webui.py
index d40176d95..9e7e6992d 100644
--- a/deluge/plugins/Stats/deluge/plugins/stats/webui.py
+++ b/deluge/plugins/Stats/deluge/plugins/stats/webui.py
@@ -22,13 +22,13 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("stats.js")]
+ scripts = [get_resource('stats.js')]
# The enable and disable methods are not scrictly required on the WebUI
# plugins. They are only here if you need to register images/stylesheets
# with the webserver.
def enable(self):
- log.debug("Stats Web plugin enabled!")
+ log.debug('Stats Web plugin enabled!')
def disable(self):
- log.debug("Stats Web plugin disabled!")
+ log.debug('Stats Web plugin disabled!')
diff --git a/deluge/plugins/Stats/setup.py b/deluge/plugins/Stats/setup.py
index f8ca45322..64b12373b 100644
--- a/deluge/plugins/Stats/setup.py
+++ b/deluge/plugins/Stats/setup.py
@@ -14,18 +14,18 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Stats"
-__author__ = "Ian Martin"
-__author_email__ = "ianmartin@cantab.net"
-__version__ = "0.3.2"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Display stats graphs"
+__plugin_name__ = 'Stats'
+__author__ = 'Ian Martin'
+__author_email__ = 'ianmartin@cantab.net'
+__version__ = '0.3.2'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Display stats graphs'
__long_description__ = """
Records lots of extra stats
and produces time series
graphs"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -38,7 +38,7 @@ setup(
long_description=__long_description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/Toggle/deluge/plugins/toggle/common.py b/deluge/plugins/Toggle/deluge/plugins/toggle/common.py
index 463a6dcb7..bc1d4774e 100644
--- a/deluge/plugins/Toggle/deluge/plugins/toggle/common.py
+++ b/deluge/plugins/Toggle/deluge/plugins/toggle/common.py
@@ -16,5 +16,5 @@
def get_resource(filename):
import os.path
import pkg_resources
- return pkg_resources.resource_filename("deluge.plugins.toggle",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.toggle',
+ os.path.join('data', filename))
diff --git a/deluge/plugins/Toggle/deluge/plugins/toggle/core.py b/deluge/plugins/Toggle/deluge/plugins/toggle/core.py
index 2fceb3441..43fb63408 100644
--- a/deluge/plugins/Toggle/deluge/plugins/toggle/core.py
+++ b/deluge/plugins/Toggle/deluge/plugins/toggle/core.py
@@ -26,7 +26,7 @@ DEFAULT_PREFS = {
class Core(CorePluginBase):
def enable(self):
- self.core = component.get("Core")
+ self.core = component.get('Core')
def disable(self):
pass
diff --git a/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py b/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
index cd6fd47f5..87503a008 100644
--- a/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
+++ b/deluge/plugins/Toggle/deluge/plugins/toggle/gtkui.py
@@ -24,25 +24,25 @@ log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
self.core = client.toggle
- self.plugin = component.get("PluginManager")
+ 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)
- component.get("PluginManager").remove_toolbar_button(self.separator)
+ component.get('PluginManager').remove_toolbar_button(self.button)
+ component.get('PluginManager').remove_toolbar_button(self.separator)
def update(self):
def _on_get_status(paused):
if paused:
- self.button.set_label("Resume Session")
- self.button.set_tooltip_text("Resume the session")
- self.button.set_stock_id("gtk-media-play")
+ self.button.set_label('Resume Session')
+ self.button.set_tooltip_text('Resume the session')
+ self.button.set_stock_id('gtk-media-play')
else:
- self.button.set_label("Pause Session")
- self.button.set_tooltip_text("Pause the session")
- self.button.set_stock_id("gtk-media-pause")
+ self.button.set_label('Pause Session')
+ self.button.set_tooltip_text('Pause the session')
+ self.button.set_stock_id('gtk-media-pause')
self.core.get_status().addCallback(_on_get_status)
def _on_button_clicked(self, widget):
diff --git a/deluge/plugins/Toggle/deluge/plugins/toggle/webui.py b/deluge/plugins/Toggle/deluge/plugins/toggle/webui.py
index 4bb5861c4..c46af6d65 100644
--- a/deluge/plugins/Toggle/deluge/plugins/toggle/webui.py
+++ b/deluge/plugins/Toggle/deluge/plugins/toggle/webui.py
@@ -23,7 +23,7 @@ log = logging.getLogger(__name__)
class WebUI(WebPluginBase):
- scripts = [get_resource("toggle.js")]
+ scripts = [get_resource('toggle.js')]
def enable(self):
pass
diff --git a/deluge/plugins/Toggle/setup.py b/deluge/plugins/Toggle/setup.py
index 9152b5f9c..89fe9e35f 100644
--- a/deluge/plugins/Toggle/setup.py
+++ b/deluge/plugins/Toggle/setup.py
@@ -14,15 +14,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "Toggle"
-__author__ = "John Garland"
-__author_email__ = "johnnybg+deluge@gmail.com"
-__version__ = "0.3"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Toggles the session"
+__plugin_name__ = 'Toggle'
+__author__ = 'John Garland'
+__author_email__ = 'johnnybg+deluge@gmail.com'
+__version__ = '0.3'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Toggles the session'
__long_description__ = """"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -35,7 +35,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/WebUi/deluge/plugins/webui/common.py b/deluge/plugins/WebUi/deluge/plugins/webui/common.py
index d9d26f631..6aeca01eb 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/common.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/common.py
@@ -15,5 +15,5 @@
def get_resource(filename):
import os.path
import pkg_resources
- return pkg_resources.resource_filename("deluge.plugins.webui",
- os.path.join("data", filename))
+ return pkg_resources.resource_filename('deluge.plugins.webui',
+ os.path.join('data', filename))
diff --git a/deluge/plugins/WebUi/deluge/plugins/webui/core.py b/deluge/plugins/WebUi/deluge/plugins/webui/core.py
index 4540e7655..0435d249d 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/core.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/core.py
@@ -24,9 +24,9 @@ from deluge.plugins.pluginbase import CorePluginBase
log = logging.getLogger(__name__)
DEFAULT_PREFS = {
- "enabled": False,
- "ssl": False,
- "port": 8112
+ 'enabled': False,
+ 'ssl': False,
+ 'port': 8112
}
@@ -34,7 +34,7 @@ class Core(CorePluginBase):
server = None
def enable(self):
- self.config = configmanager.ConfigManager("web_plugin.conf", DEFAULT_PREFS)
+ self.config = configmanager.ConfigManager('web_plugin.conf', DEFAULT_PREFS)
if self.config['enabled']:
self.start_server()
@@ -63,16 +63,16 @@ class Core(CorePluginBase):
return False
try:
- self.server = component.get("DelugeWeb")
+ self.server = component.get('DelugeWeb')
except KeyError:
self.server = server.DelugeWeb(daemon=False)
- self.server.port = self.config["port"]
- self.server.https = self.config["ssl"]
+ self.server.port = self.config['port']
+ self.server.https = self.config['ssl']
try:
self.server.start()
except CannotListenError as ex:
- log.warn("Failed to start WebUI server: %s", ex)
+ log.warn('Failed to start WebUI server: %s', ex)
raise
return True
@@ -86,14 +86,14 @@ class Core(CorePluginBase):
@export
def set_config(self, config):
- "sets the config dictionary"
+ 'sets the config dictionary'
action = None
- if "enabled" in config:
- if config["enabled"] != self.config["enabled"]:
- action = config["enabled"] and 'start' or 'stop'
+ if 'enabled' in config:
+ if config['enabled'] != self.config['enabled']:
+ action = config['enabled'] and 'start' or 'stop'
- if "ssl" in config:
+ if 'ssl' in config:
if not action:
action = 'restart'
@@ -110,5 +110,5 @@ class Core(CorePluginBase):
@export
def get_config(self):
- "returns the config dictionary"
+ 'returns the config dictionary'
return self.config.config
diff --git a/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py b/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
index b566c8df4..00f378490 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/gtkui.py
@@ -27,27 +27,27 @@ log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase):
def enable(self):
- self.glade = gtk.glade.XML(get_resource("config.glade"))
+ self.glade = gtk.glade.XML(get_resource('config.glade'))
- component.get("Preferences").add_page(_("WebUi"), self.glade.get_widget("prefs_box"))
- 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('Preferences').add_page(_('WebUi'), self.glade.get_widget('prefs_box'))
+ component.get('PluginManager').register_hook('on_apply_prefs', self.on_apply_prefs)
+ component.get('PluginManager').register_hook('on_show_prefs', self.on_show_prefs)
client.webui.get_config().addCallback(self.cb_get_config)
client.webui.got_deluge_web().addCallback(self.cb_chk_deluge_web)
def disable(self):
- component.get("Preferences").remove_page(_("WebUi"))
- 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('Preferences').remove_page(_('WebUi'))
+ 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 on_apply_prefs(self):
if not self.have_web:
return
- log.debug("applying prefs for WebUi")
+ log.debug('applying prefs for WebUi')
config = {
- "enabled": self.glade.get_widget("enabled_checkbutton").get_active(),
- "ssl": self.glade.get_widget("ssl_checkbutton").get_active(),
- "port": self.glade.get_widget("port_spinbutton").get_value_as_int()
+ 'enabled': self.glade.get_widget('enabled_checkbutton').get_active(),
+ 'ssl': self.glade.get_widget('ssl_checkbutton').get_active(),
+ 'port': self.glade.get_widget('port_spinbutton').get_value_as_int()
}
client.webui.set_config(config)
@@ -55,26 +55,26 @@ class GtkUI(GtkPluginBase):
client.webui.get_config().addCallback(self.cb_get_config)
def cb_get_config(self, config):
- "callback for on show_prefs"
- self.glade.get_widget("enabled_checkbutton").set_active(config["enabled"])
- self.glade.get_widget("ssl_checkbutton").set_active(config["ssl"])
- self.glade.get_widget("port_spinbutton").set_value(config["port"])
+ 'callback for on show_prefs'
+ self.glade.get_widget('enabled_checkbutton').set_active(config['enabled'])
+ self.glade.get_widget('ssl_checkbutton').set_active(config['ssl'])
+ self.glade.get_widget('port_spinbutton').set_value(config['port'])
def cb_chk_deluge_web(self, have_web):
self.have_web = have_web
if have_web:
return
- self.glade.get_widget("settings_vbox").set_sensitive(False)
+ self.glade.get_widget('settings_vbox').set_sensitive(False)
- vbox = self.glade.get_widget("prefs_box")
+ vbox = self.glade.get_widget('prefs_box')
hbox = gtk.HBox()
icon = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_SMALL_TOOLBAR)
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/deluge/plugins/webui/tests/test_plugin_webui.py b/deluge/plugins/WebUi/deluge/plugins/webui/tests/test_plugin_webui.py
index ed6c5ed1f..d5b30a867 100644
--- a/deluge/plugins/WebUi/deluge/plugins/webui/tests/test_plugin_webui.py
+++ b/deluge/plugins/WebUi/deluge/plugins/webui/tests/test_plugin_webui.py
@@ -34,14 +34,14 @@ class WebUIPluginTestCase(BaseTestCase):
return component.shutdown().addCallback(on_shutdown)
def test_enable_webui(self):
- if "WebUi" not in self.core.get_available_plugins():
- raise unittest.SkipTest("WebUi plugin not available for testing")
+ if 'WebUi' not in self.core.get_available_plugins():
+ raise unittest.SkipTest('WebUi plugin not available for testing')
- d = self.core.enable_plugin("WebUi")
+ d = self.core.enable_plugin('WebUi')
def result_cb(result):
- if "WebUi" not in self.core.get_enabled_plugins():
- self.fail("Failed to enable WebUi plugin")
+ if 'WebUi' not in self.core.get_enabled_plugins():
+ self.fail('Failed to enable WebUi plugin')
self.assertTrue(result)
d.addBoth(result_cb)
diff --git a/deluge/plugins/WebUi/setup.py b/deluge/plugins/WebUi/setup.py
index c0732597c..3a7b130f0 100644
--- a/deluge/plugins/WebUi/setup.py
+++ b/deluge/plugins/WebUi/setup.py
@@ -13,15 +13,15 @@
from setuptools import find_packages, setup
-__plugin_name__ = "WebUi"
-__author__ = "Damien Churchill"
-__author_email__ = "damoxc@gmail.com"
-__version__ = "0.1"
-__url__ = "http://deluge-torrent.org"
-__license__ = "GPLv3"
-__description__ = "Allows starting the web interface within the daemon."
+__plugin_name__ = 'WebUi'
+__author__ = 'Damien Churchill'
+__author_email__ = 'damoxc@gmail.com'
+__version__ = '0.1'
+__url__ = 'http://deluge-torrent.org'
+__license__ = 'GPLv3'
+__description__ = 'Allows starting the web interface within the daemon.'
__long_description__ = """"""
-__pkg_data__ = {"deluge.plugins." + __plugin_name__.lower(): ["template/*", "data/*"]}
+__pkg_data__ = {'deluge.plugins.' + __plugin_name__.lower(): ['template/*', 'data/*']}
setup(
name=__plugin_name__,
@@ -34,7 +34,7 @@ setup(
long_description=__long_description__ if __long_description__ else __description__,
packages=find_packages(),
- namespace_packages=["deluge", "deluge.plugins"],
+ namespace_packages=['deluge', 'deluge.plugins'],
package_data=__pkg_data__,
entry_points="""
diff --git a/deluge/plugins/pluginbase.py b/deluge/plugins/pluginbase.py
index 9e39ff98d..0829625a5 100644
--- a/deluge/plugins/pluginbase.py
+++ b/deluge/plugins/pluginbase.py
@@ -22,22 +22,22 @@ class PluginBase(component.Component):
super(PluginBase, self).__init__(name, self.update_interval)
def enable(self):
- raise NotImplementedError("Need to define an enable method!")
+ raise NotImplementedError('Need to define an enable method!')
def disable(self):
- raise NotImplementedError("Need to define a disable method!")
+ raise NotImplementedError('Need to define a disable method!')
class CorePluginBase(PluginBase):
def __init__(self, plugin_name):
- super(CorePluginBase, self).__init__("CorePlugin." + plugin_name)
+ super(CorePluginBase, self).__init__('CorePlugin.' + plugin_name)
# Register RPC methods
- component.get("RPCServer").register_object(self, plugin_name.lower())
- log.debug("CorePlugin initialized..")
+ component.get('RPCServer').register_object(self, plugin_name.lower())
+ log.debug('CorePlugin initialized..')
def __del__(self):
- component.get("RPCServer").deregister_object(self)
+ component.get('RPCServer').deregister_object(self)
def enable(self):
super(CorePluginBase, self).enable()
@@ -49,8 +49,8 @@ class CorePluginBase(PluginBase):
class GtkPluginBase(PluginBase):
def __init__(self, plugin_name):
- super(GtkPluginBase, self).__init__("GtkPlugin." + plugin_name)
- log.debug("GtkPlugin initialized..")
+ super(GtkPluginBase, self).__init__('GtkPlugin.' + plugin_name)
+ log.debug('GtkPlugin initialized..')
def enable(self):
super(GtkPluginBase, self).enable()
@@ -68,11 +68,11 @@ class WebPluginBase(PluginBase):
debug_stylesheets = []
def __init__(self, plugin_name):
- super(WebPluginBase, self).__init__("WebPlugin." + plugin_name)
+ super(WebPluginBase, self).__init__('WebPlugin.' + plugin_name)
# Register JSON rpc methods
- component.get("JSON").register_object(self, plugin_name.lower())
- log.debug("WebPlugin initialized..")
+ component.get('JSON').register_object(self, plugin_name.lower())
+ log.debug('WebPlugin initialized..')
def enable(self):
pass
diff --git a/deluge/rencode.py b/deluge/rencode.py
index 4ae5796d8..e24f86548 100644
--- a/deluge/rencode.py
+++ b/deluge/rencode.py
@@ -62,7 +62,7 @@ import struct
import sys
from threading import Lock
-__version__ = ("Python", 1, 0, 4)
+__version__ = ('Python', 1, 0, 4)
__all__ = ['dumps', 'loads']
py3 = sys.version_info[0] >= 3
@@ -244,7 +244,7 @@ def make_fixed_length_string_decoders():
def f(x, f):
s = x[f + 1:f + 1 + slen]
if _decode_utf8:
- s = s.decode("utf8")
+ s = s.decode('utf8')
return (s, f + 1 + slen)
return f
for i in range(STR_FIXED_COUNT):
@@ -324,7 +324,7 @@ def encode_int(x, r):
else:
s = str(x)
if py3:
- s = bytes(s, "ascii")
+ s = bytes(s, 'ascii')
if len(s) >= MAX_INT_LENGTH:
raise ValueError('overflow')
@@ -353,12 +353,12 @@ def encode_string(x, r):
else:
s = str(len(x))
if py3:
- s = bytes(s, "ascii")
+ s = bytes(s, 'ascii')
r.extend((s, b':', x))
def encode_unicode(x, r):
- encode_string(x.encode("utf8"), r)
+ encode_string(x.encode('utf8'), r)
def encode_list(x, r):
@@ -447,7 +447,7 @@ def test():
assert 1e-10 < abs(loads(dumps(1.1)) - 1.1) < 1e-6
assert 1e-10 < abs(loads(dumps(1.1, 32)) - 1.1) < 1e-6
assert abs(loads(dumps(1.1, 64)) - 1.1) < 1e-12
- assert loads(dumps("Hello World!!"), decode_utf8=True)
+ assert loads(dumps('Hello World!!'), decode_utf8=True)
try:
import psyco
psyco.bind(dumps)
diff --git a/deluge/scripts/create_plugin.py b/deluge/scripts/create_plugin.py
index 718ed59f9..2a1ce339a 100644
--- a/deluge/scripts/create_plugin.py
+++ b/deluge/scripts/create_plugin.py
@@ -16,15 +16,15 @@ from datetime import datetime
import deluge.common
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("-u", "--url", metavar="<URL>", help="Homepage URL")
-parser.add_argument("-c", "--config", metavar="<Config dir>", dest="configdir", help="Location of deluge configuration")
+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('-u', '--url', metavar='<URL>', help='Homepage URL')
+parser.add_argument('-c', '--config', metavar='<Config dir>', dest='configdir', help='Location of deluge configuration')
options = parser.parse_args()
@@ -32,10 +32,10 @@ options = parser.parse_args()
def create_plugin():
if not options.url:
- options.url = ""
+ options.url = ''
if not os.path.exists(options.basepath):
- print("basepath does not exist")
+ print('basepath does not exist')
return
if not options.configdir:
@@ -44,65 +44,65 @@ def create_plugin():
options.configdir = os.path.realpath(options.configdir)
real_name = options.name
- name = real_name.replace(" ", "_")
+ name = real_name.replace(' ', '_')
safe_name = name.lower()
if options.module_name:
safe_name = options.module_name.lower()
plugin_base = os.path.realpath(os.path.join(options.basepath, name))
- deluge_namespace = os.path.join(plugin_base, "deluge")
- plugins_namespace = os.path.join(deluge_namespace, "plugins")
+ deluge_namespace = os.path.join(plugin_base, 'deluge')
+ plugins_namespace = os.path.join(deluge_namespace, 'plugins')
src = os.path.join(plugins_namespace, safe_name)
- data_dir = os.path.join(src, "data")
+ data_dir = os.path.join(src, 'data')
python_path = sys.executable
if os.path.exists(plugin_base):
- print("the directory %s already exists, delete it first" % plugin_base)
+ print('the directory %s already exists, delete it first' % plugin_base)
return
def write_file(path, filename, template, include_gpl=True):
plugin_args = {
- "author_name": options.author_name,
- "author_email": options.author_email,
- "name": name,
- "safe_name": safe_name,
- "filename": filename,
- "plugin_base": plugin_base,
- "python_path": python_path,
- "url": options.url,
- "configdir": options.configdir,
- "current_year": datetime.utcnow().year
+ 'author_name': options.author_name,
+ 'author_email': options.author_email,
+ 'name': name,
+ 'safe_name': safe_name,
+ 'filename': filename,
+ 'plugin_base': plugin_base,
+ 'python_path': python_path,
+ 'url': options.url,
+ 'configdir': options.configdir,
+ 'current_year': datetime.utcnow().year
}
filename = os.path.join(path, filename)
- with open(filename, "w") as _file:
- if filename.endswith(".py") and include_gpl:
+ with open(filename, 'w') as _file:
+ if filename.endswith('.py') and include_gpl:
_file.write(GPL % plugin_args)
_file.write(template % plugin_args)
- print("creating folders..")
+ print('creating folders..')
os.mkdir(plugin_base)
os.mkdir(deluge_namespace)
os.mkdir(plugins_namespace)
os.mkdir(src)
os.mkdir(data_dir)
- print("creating files..")
- write_file(plugin_base, "setup.py", SETUP)
- write_file(deluge_namespace, "__init__.py", NAMESPACE_INIT, False)
- write_file(plugins_namespace, "__init__.py", NAMESPACE_INIT, False)
- write_file(src, "__init__.py", INIT)
- write_file(src, "gtkui.py", GTKUI)
- write_file(src, "webui.py", WEBUI)
- write_file(src, "core.py", CORE)
- write_file(src, "common.py", COMMON)
- write_file(data_dir, "config.glade", GLADE)
- write_file(data_dir, "%s.js" % safe_name, DEFAULT_JS)
+ print('creating files..')
+ write_file(plugin_base, 'setup.py', SETUP)
+ write_file(deluge_namespace, '__init__.py', NAMESPACE_INIT, False)
+ write_file(plugins_namespace, '__init__.py', NAMESPACE_INIT, False)
+ write_file(src, '__init__.py', INIT)
+ write_file(src, 'gtkui.py', GTKUI)
+ write_file(src, 'webui.py', WEBUI)
+ write_file(src, 'core.py', CORE)
+ write_file(src, 'common.py', COMMON)
+ write_file(data_dir, 'config.glade', GLADE)
+ write_file(data_dir, '%s.js' % safe_name, DEFAULT_JS)
# add an input parameter for this?
- print("building dev-link..")
- write_file(plugin_base, "create_dev_link.sh", CREATE_DEV_LINK)
- dev_link_path = os.path.join(plugin_base, "create_dev_link.sh")
- os.system("chmod +x %s" % dev_link_path) # lazy..
+ print('building dev-link..')
+ write_file(plugin_base, 'create_dev_link.sh', CREATE_DEV_LINK)
+ dev_link_path = os.path.join(plugin_base, 'create_dev_link.sh')
+ os.system('chmod +x %s' % dev_link_path) # lazy..
os.system(dev_link_path)
diff --git a/deluge/scripts/deluge_remote.py b/deluge/scripts/deluge_remote.py
index 922abd8c4..cd614ffdd 100644
--- a/deluge/scripts/deluge_remote.py
+++ b/deluge/scripts/deluge_remote.py
@@ -28,21 +28,21 @@ 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('--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')
# grab command-line options
(options, args) = parser.parse_args()
@@ -57,21 +57,21 @@ if options.max_active_limit:
if options.max_active_limit.isdigit() and int(options.max_active_limit) >= 0:
settings['max_active_limit'] = int(options.max_active_limit)
else:
- sys.stderr.write("ERROR: Invalid max_active_limit parameter!\n")
+ sys.stderr.write('ERROR: Invalid max_active_limit parameter!\n')
sys.exit(-1)
if options.max_active_downloading:
if options.max_active_downloading.isdigit() and int(options.max_active_downloading) >= 0:
settings['max_active_downloading'] = int(options.max_active_downloading)
else:
- sys.stderr.write("ERROR: Invalid max_active_downloading parameter!\n")
+ sys.stderr.write('ERROR: Invalid max_active_downloading parameter!\n')
sys.exit(-1)
if options.max_active_seeding:
if options.max_active_seeding.isdigit() and int(options.max_active_seeding) >= 0:
settings['max_active_seeding'] = int(options.max_active_seeding)
else:
- sys.stderr.write("ERROR: Invalid max_active_seeding parameter!\n")
+ sys.stderr.write('ERROR: Invalid max_active_seeding parameter!\n')
sys.exit(-1)
if options.max_download_speed:
@@ -79,7 +79,7 @@ if options.max_download_speed:
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")
+ sys.stderr.write('ERROR: Invalid max_download_speed parameter!\n')
sys.exit(-1)
if options.max_upload_speed:
@@ -87,14 +87,14 @@ if options.max_upload_speed:
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")
+ sys.stderr.write('ERROR: Invalid max_upload_speed parameter!\n')
sys.exit(-1)
# If there is something to do ...
if settings:
# create connection to daemon
from deluge.ui.client import sclient as client
- client.set_core_uri("http://" + options.host + ":" + options.port)
+ client.set_core_uri('http://' + options.host + ':' + options.port)
# commit configurations changes
client.set_config(settings)
diff --git a/deluge/tests/__init__.py b/deluge/tests/__init__.py
index 388b399e8..6c7f1c6fc 100644
--- a/deluge/tests/__init__.py
+++ b/deluge/tests/__init__.py
@@ -10,4 +10,4 @@ else:
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536))
except (ValueError, resource.error) as ex:
- print("Failed to raise file descriptor limit:", ex)
+ print('Failed to raise file descriptor limit:', ex)
diff --git a/deluge/tests/basetest.py b/deluge/tests/basetest.py
index d32532019..11da5ef5a 100644
--- a/deluge/tests/basetest.py
+++ b/deluge/tests/basetest.py
@@ -16,13 +16,13 @@ class BaseTestCase(unittest.TestCase):
def setUp(self): # NOQA
if len(component._ComponentRegistry.components) != 0:
- warnings.warn("The component._ComponentRegistry.components is not empty on test setup.\n"
+ warnings.warn('The component._ComponentRegistry.components is not empty on test setup.\n'
"This is probably caused by another test that didn't clean up after finishing!: %s" %
component._ComponentRegistry.components)
d = maybeDeferred(self.set_up)
def on_setup_error(error):
- warnings.warn("Error caught in test setup!\n%s" % error.getTraceback())
+ warnings.warn('Error caught in test setup!\n%s' % error.getTraceback())
self.fail()
return d.addErrback(on_setup_error)
@@ -31,7 +31,7 @@ class BaseTestCase(unittest.TestCase):
d = maybeDeferred(self.tear_down)
def on_teardown_failed(error):
- warnings.warn("Error caught in test teardown!\n%s" % error.getTraceback())
+ warnings.warn('Error caught in test teardown!\n%s' % error.getTraceback())
self.fail()
def on_teardown_complete(result):
diff --git a/deluge/tests/common.py b/deluge/tests/common.py
index d751b85c6..30e71fe1f 100644
--- a/deluge/tests/common.py
+++ b/deluge/tests/common.py
@@ -26,11 +26,11 @@ from deluge.error import DelugeError
from deluge.ui.util import lang
# This sets log level to critical, so use log.critical() to debug while running unit tests
-deluge.log.setup_logger("none")
+deluge.log.setup_logger('none')
def disable_new_release_check():
- deluge.core.preferencesmanager.DEFAULT_PREFS["new_release_check"] = False
+ deluge.core.preferencesmanager.DEFAULT_PREFS['new_release_check'] = False
def set_tmp_config_dir():
@@ -39,24 +39,24 @@ def set_tmp_config_dir():
return config_directory
-def setup_test_logger(level="info", prefix="deluge"):
- deluge.log.setup_logger(level, filename="%s.log" % prefix, twisted_observer=False)
+def setup_test_logger(level='info', prefix='deluge'):
+ deluge.log.setup_logger(level, filename='%s.log' % prefix, twisted_observer=False)
def get_test_data_file(filename):
- return os.path.join(os.path.join(os.path.dirname(__file__), "data"), filename)
+ return os.path.join(os.path.join(os.path.dirname(__file__), 'data'), filename)
def todo_test(caller):
# If we are using the delugereporter we can set todo mark on the test
# Without the delugereporter the todo would print a stack trace, so in
# that case we rely only on skipTest
- if os.environ.get("DELUGE_REPORTER", None):
- getattr(caller, caller._testMethodName).__func__.todo = "To be fixed"
+ if os.environ.get('DELUGE_REPORTER', None):
+ getattr(caller, caller._testMethodName).__func__.todo = 'To be fixed'
filename = os.path.basename(traceback.extract_stack(None, 2)[0][0])
funcname = traceback.extract_stack(None, 2)[0][2]
- raise unittest.SkipTest("TODO: %s:%s" % (filename, funcname))
+ raise unittest.SkipTest('TODO: %s:%s' % (filename, funcname))
def add_watchdog(deferred, timeout=0.05, message=None):
@@ -85,9 +85,9 @@ class ReactorOverride(object):
"""
def __getattr__(self, attr):
- if attr == "run":
+ if attr == 'run':
return self._run
- if attr == "stop":
+ if attr == 'stop':
return self._stop
return getattr(reactor, attr)
@@ -115,8 +115,8 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
"""
self.callbacks = callbacks
self.script = script
- self.log_output = ""
- self.stderr_out = ""
+ self.log_output = ''
+ self.stderr_out = ''
self.logfile = logfile
self.print_stderr = print_stderr
self.quit_d = None
@@ -163,24 +163,24 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
else:
self.quit_d.errback(status)
- def check_callbacks(self, data, cb_type="stdout"):
+ def check_callbacks(self, data, cb_type='stdout'):
ret = False
for c in self.callbacks:
- if cb_type not in c["types"] or c["deferred"].called:
+ if cb_type not in c['types'] or c['deferred'].called:
continue
- for trigger in c["triggers"]:
- if trigger["expr"] in data:
+ for trigger in c['triggers']:
+ if trigger['expr'] in data:
ret = True
- if "cb" in trigger:
- trigger["cb"](self, c["deferred"], data, self.log_output)
- elif "value" not in trigger:
+ if 'cb' in trigger:
+ trigger['cb'](self, c['deferred'], data, self.log_output)
+ elif 'value' not in trigger:
raise Exception("Trigger must specify either 'cb' or 'value'")
else:
- val = trigger["value"](self, data, self.log_output)
- if trigger.get("type", "callback") == "errback":
- c["deferred"].errback(val)
+ val = trigger['value'](self, data, self.log_output)
+ if trigger.get('type', 'callback') == 'errback':
+ c['deferred'].errback(val)
else:
- c["deferred"].callback(val)
+ c['deferred'].callback(val)
return ret
def outReceived(self, data): # NOQA
@@ -195,16 +195,16 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
"""Process output from stderr"""
self.log_output += data
self.stderr_out += data
- self.check_callbacks(data, cb_type="stderr")
+ self.check_callbacks(data, cb_type='stderr')
if not self.print_stderr:
return
- data = "\n%s" % data.strip()
- prefixed = data.replace("\n", "\nSTDERR: ")
- print("\n%s" % prefixed)
+ data = '\n%s' % data.strip()
+ prefixed = data.replace('\n', '\nSTDERR: ')
+ print('\n%s' % prefixed)
def start_core(listen_port=58846, logfile=None, timeout=10, timeout_msg=None,
- custom_script="", print_stderr=True, extra_callbacks=None):
+ custom_script='', print_stderr=True, extra_callbacks=None):
"""Start the deluge core as a daemon.
Args:
@@ -240,18 +240,18 @@ except:
sys.stderr.write("Exception raised:\\n %%s" %% traceback.format_exc())
""" % (config_directory, listen_port, custom_script)
callbacks = []
- default_core_cb = {"deferred": Deferred(), "types": "stdout"}
+ default_core_cb = {'deferred': Deferred(), 'types': 'stdout'}
if timeout:
- default_core_cb["timeout"] = timeout
+ default_core_cb['timeout'] = timeout
# Specify the triggers for daemon log output
- default_core_cb["triggers"] = [
- {"expr": "Finished loading ", "value": lambda reader, data, data_all: reader},
- {"expr": "Couldn't 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)}
+ default_core_cb['triggers'] = [
+ {'expr': 'Finished loading ', 'value': lambda reader, data, data_all: reader},
+ {'expr': "Couldn't 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)
@@ -259,7 +259,7 @@ except:
callbacks.extend(extra_callbacks)
process_protocol = start_process(daemon_script, callbacks, logfile, print_stderr)
- return default_core_cb["deferred"], process_protocol
+ return default_core_cb['deferred'], process_protocol
def start_process(script, callbacks, logfile=None, print_stderr=True):
@@ -291,8 +291,8 @@ def start_process(script, callbacks, logfile=None, print_stderr=True):
# Add timeouts to deferreds
for c in callbacks:
- if "timeout" in c:
- w = add_watchdog(c["deferred"], timeout=c["timeout"], message=c.get("timeout_msg", None))
+ if 'timeout' in c:
+ w = add_watchdog(c['deferred'], timeout=c['timeout'], message=c.get('timeout_msg', None))
process_protocol.watchdogs.append(w)
reactor.spawnProcess(process_protocol, sys.executable, args=[sys.executable], path=cwd)
diff --git a/deluge/tests/common_web.py b/deluge/tests/common_web.py
index 1c6b19c37..6799598f7 100644
--- a/deluge/tests/common_web.py
+++ b/deluge/tests/common_web.py
@@ -29,9 +29,9 @@ class ReactorOverride(object):
"""
def __getattr__(self, attr):
- if attr == "run":
+ if attr == 'run':
return self._run
- if attr == "stop":
+ if attr == 'stop':
return self._stop
return getattr(reactor, attr)
@@ -59,14 +59,14 @@ class WebServerTestBase(BaseTestCase, DaemonBase):
self.webserver_listen_port = 8999
config_defaults = deluge.ui.web.server.CONFIG_DEFAULTS.copy()
- config_defaults["port"] = self.webserver_listen_port
- self.config = configmanager.ConfigManager("web.conf", config_defaults)
+ config_defaults['port'] = self.webserver_listen_port
+ self.config = configmanager.ConfigManager('web.conf', config_defaults)
self.deluge_web = DelugeWeb(daemon=False)
- host = list(self.deluge_web.web_api.host_list["hosts"][0])
+ host = list(self.deluge_web.web_api.host_list['hosts'][0])
host[2] = self.listen_port
- self.deluge_web.web_api.host_list["hosts"][0] = tuple(host)
+ self.deluge_web.web_api.host_list['hosts'][0] = tuple(host)
self.host_id = host[0]
self.deluge_web.start()
@@ -86,11 +86,11 @@ class WebServerMockBase(object):
def check_request(request, method=None, level=None):
pass
- self.patch(auth, "check_request", check_request)
+ self.patch(auth, 'check_request', check_request)
def mock_compress_body(self):
def compress(contents, request):
return contents
# Patch compress to avoid having to decompress output with zlib
- self.patch(deluge.ui.web.json_api, "compress", compress)
+ self.patch(deluge.ui.web.json_api, 'compress', compress)
diff --git a/deluge/tests/daemon_base.py b/deluge/tests/daemon_base.py
index 10ff951f8..42bff39ca 100644
--- a/deluge/tests/daemon_base.py
+++ b/deluge/tests/daemon_base.py
@@ -21,21 +21,21 @@ class DaemonBase(object):
def terminate_core(self, *args):
if args[0] is not None:
- if hasattr(args[0], "getTraceback"):
- print("terminate_core: Errback Exception: %s" % args[0].getTraceback())
+ if hasattr(args[0], 'getTraceback'):
+ print('terminate_core: Errback Exception: %s' % args[0].getTraceback())
if not self.core.killed:
d = self.core.kill()
return d
@defer.inlineCallbacks
- def start_core(self, arg, custom_script="", logfile="", print_stderr=True, timeout=5,
+ def start_core(self, arg, custom_script='', logfile='', print_stderr=True, timeout=5,
port_range=10, extra_callbacks=None):
- if logfile == "":
- logfile = "daemon_%s.log" % self.id()
+ if logfile == '':
+ logfile = 'daemon_%s.log' % self.id()
# We are running py.test
- if hasattr(pytest, "config"):
+ if hasattr(pytest, 'config'):
# Put log file in the py.test --basetemp argument
basetemp = pytest.config.option.basetemp
if basetemp:
@@ -46,7 +46,7 @@ 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!",
+ timeout=timeout, timeout_msg='Timeout!',
custom_script=custom_script,
print_stderr=print_stderr,
extra_callbacks=extra_callbacks)
diff --git a/deluge/tests/test_alertmanager.py b/deluge/tests/test_alertmanager.py
index fc6a020b6..2402c5134 100644
--- a/deluge/tests/test_alertmanager.py
+++ b/deluge/tests/test_alertmanager.py
@@ -15,8 +15,8 @@ class AlertManagerTestCase(BaseTestCase):
def set_up(self):
self.core = Core()
- self.am = component.get("AlertManager")
- return component.start(["AlertManager"])
+ self.am = component.get('AlertManager')
+ return component.start(['AlertManager'])
def tear_down(self):
return component.shutdown()
@@ -25,13 +25,13 @@ class AlertManagerTestCase(BaseTestCase):
def handler(alert):
return
- self.am.register_handler("dummy_alert", handler)
- self.assertEquals(self.am.handlers["dummy_alert"], [handler])
+ self.am.register_handler('dummy_alert', handler)
+ self.assertEquals(self.am.handlers['dummy_alert'], [handler])
def test_deregister_handler(self):
def handler(alert):
return
- self.am.register_handler("dummy_alert", handler)
+ self.am.register_handler('dummy_alert', handler)
self.am.deregister_handler(handler)
- self.assertEquals(self.am.handlers["dummy_alert"], [])
+ self.assertEquals(self.am.handlers['dummy_alert'], [])
diff --git a/deluge/tests/test_client.py b/deluge/tests/test_client.py
index fe4d7ed65..0ca416cf4 100644
--- a/deluge/tests/test_client.py
+++ b/deluge/tests/test_client.py
@@ -20,7 +20,7 @@ from .daemon_base import DaemonBase
class NoVersionSendingDaemonSSLProxy(DaemonSSLProxy):
def authenticate(self, username, password):
self.login_deferred = defer.Deferred()
- d = self.call("daemon.login", username, password)
+ d = self.call('daemon.login', username, password)
d.addCallback(self.__on_login, username)
d.addErrback(self.__on_login_fail)
return self.login_deferred
@@ -34,7 +34,7 @@ class NoVersionSendingDaemonSSLProxy(DaemonSSLProxy):
class NoVersionSendingClient(Client):
- def connect(self, host="127.0.0.1", port=58846, username="", password="",
+ 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)
@@ -85,7 +85,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
return d
def test_connect_no_credentials(self):
- d = client.connect("localhost", self.listen_port, username="", password="")
+ d = client.connect('localhost', self.listen_port, username='', password='')
def on_connect(result):
self.assertEqual(client.get_auth_level(), AUTH_LEVEL_ADMIN)
@@ -97,7 +97,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def test_connect_localclient(self):
username, password = deluge.ui.common.get_localhost_auth()
- d = client.connect("localhost", self.listen_port, username=username, password=password)
+ d = client.connect('localhost', self.listen_port, username=username, password=password)
def on_connect(result):
self.assertEqual(client.get_auth_level(), AUTH_LEVEL_ADMIN)
@@ -109,14 +109,14 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def test_connect_bad_password(self):
username, password = deluge.ui.common.get_localhost_auth()
- d = client.connect("localhost", self.listen_port, username=username, password=password + "1")
+ d = client.connect('localhost', self.listen_port, username=username, password=password + '1')
def on_failure(failure):
self.assertEqual(
failure.trap(error.BadLoginError),
error.BadLoginError
)
- self.assertEquals(failure.value.message, "Password does not match")
+ self.assertEquals(failure.value.message, 'Password does not match')
self.addCleanup(client.disconnect)
d.addCallbacks(self.fail, on_failure)
@@ -124,14 +124,14 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def test_connect_invalid_user(self):
username, password = deluge.ui.common.get_localhost_auth()
- d = client.connect("localhost", self.listen_port, username="invalid-user")
+ d = client.connect('localhost', self.listen_port, username='invalid-user')
def on_failure(failure):
self.assertEqual(
failure.trap(error.BadLoginError),
error.BadLoginError
)
- self.assertEquals(failure.value.message, "Username does not exist")
+ self.assertEquals(failure.value.message, 'Username does not exist')
self.addCleanup(client.disconnect)
d.addCallbacks(self.fail, on_failure)
@@ -139,7 +139,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
def test_connect_without_password(self):
username, password = deluge.ui.common.get_localhost_auth()
- d = client.connect("localhost", self.listen_port, username=username)
+ d = client.connect('localhost', self.listen_port, username=username)
def on_failure(failure):
self.assertEqual(
@@ -155,16 +155,16 @@ class ClientTestCase(BaseTestCase, DaemonBase):
@defer.inlineCallbacks
def test_connect_with_password(self):
username, password = deluge.ui.common.get_localhost_auth()
- yield client.connect("localhost", self.listen_port, username=username, password=password)
- yield client.core.create_account("testuser", "testpw", "DEFAULT")
+ yield client.connect('localhost', self.listen_port, username=username, password=password)
+ yield client.core.create_account('testuser', 'testpw', 'DEFAULT')
yield client.disconnect()
- ret = yield client.connect("localhost", self.listen_port, username="testuser", password="testpw")
+ ret = yield client.connect('localhost', self.listen_port, username='testuser', password='testpw')
self.assertEquals(ret, deluge.common.AUTH_LEVEL_NORMAL)
yield
@defer.inlineCallbacks
def test_invalid_rpc_method_call(self):
- yield client.connect("localhost", self.listen_port, username="", password="")
+ yield client.connect('localhost', self.listen_port, username='', password='')
d = client.core.invalid_method()
def on_failure(failure):
@@ -177,7 +177,7 @@ class ClientTestCase(BaseTestCase, DaemonBase):
username, password = deluge.ui.common.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):
diff --git a/deluge/tests/test_common.py b/deluge/tests/test_common.py
index a488b4aaa..e37764761 100644
--- a/deluge/tests/test_common.py
+++ b/deluge/tests/test_common.py
@@ -15,95 +15,95 @@ class CommonTestCase(unittest.TestCase):
pass
def test_fsize(self):
- self.assertEquals(fsize(0), "0 B")
- self.assertEquals(fsize(100), "100 B")
- self.assertEquals(fsize(1023), "1023 B")
- self.assertEquals(fsize(1024), "1.0 KiB")
- self.assertEquals(fsize(1048575), "1024.0 KiB")
- self.assertEquals(fsize(1048576), "1.0 MiB")
- self.assertEquals(fsize(1073741823), "1024.0 MiB")
- self.assertEquals(fsize(1073741824), "1.0 GiB")
- self.assertEquals(fsize(112245), "109.6 KiB")
- self.assertEquals(fsize(110723441824), "103.1 GiB")
- self.assertEquals(fsize(1099511627775), "1024.0 GiB")
- self.assertEquals(fsize(1099511627777), "1.0 TiB")
- self.assertEquals(fsize(766148267453245), "696.8 TiB")
+ self.assertEquals(fsize(0), '0 B')
+ self.assertEquals(fsize(100), '100 B')
+ self.assertEquals(fsize(1023), '1023 B')
+ self.assertEquals(fsize(1024), '1.0 KiB')
+ self.assertEquals(fsize(1048575), '1024.0 KiB')
+ self.assertEquals(fsize(1048576), '1.0 MiB')
+ self.assertEquals(fsize(1073741823), '1024.0 MiB')
+ self.assertEquals(fsize(1073741824), '1.0 GiB')
+ self.assertEquals(fsize(112245), '109.6 KiB')
+ self.assertEquals(fsize(110723441824), '103.1 GiB')
+ self.assertEquals(fsize(1099511627775), '1024.0 GiB')
+ self.assertEquals(fsize(1099511627777), '1.0 TiB')
+ self.assertEquals(fsize(766148267453245), '696.8 TiB')
def test_fpcnt(self):
- self.failUnless(fpcnt(0.9311) == "93.11%")
+ self.failUnless(fpcnt(0.9311) == '93.11%')
def test_fspeed(self):
- self.failUnless(fspeed(43134) == "42.1 KiB/s")
+ self.failUnless(fspeed(43134) == '42.1 KiB/s')
def test_fpeer(self):
- self.failUnless(fpeer(10, 20) == "10 (20)")
- self.failUnless(fpeer(10, -1) == "10")
+ self.failUnless(fpeer(10, 20) == '10 (20)')
+ self.failUnless(fpeer(10, -1) == '10')
def test_ftime(self):
- self.failUnless(ftime(0) == "")
- self.failUnless(ftime(5) == "5s")
- self.failUnless(ftime(100) == "1m 40s")
- self.failUnless(ftime(3789) == "1h 3m")
- self.failUnless(ftime(23011) == "6h 23m")
- self.failUnless(ftime(391187) == "4d 12h")
- self.failUnless(ftime(604800) == "1w 0d")
- self.failUnless(ftime(13893086) == "22w 6d")
- self.failUnless(ftime(59740269) == "1y 46w")
+ self.failUnless(ftime(0) == '')
+ self.failUnless(ftime(5) == '5s')
+ self.failUnless(ftime(100) == '1m 40s')
+ self.failUnless(ftime(3789) == '1h 3m')
+ self.failUnless(ftime(23011) == '6h 23m')
+ self.failUnless(ftime(391187) == '4d 12h')
+ self.failUnless(ftime(604800) == '1w 0d')
+ self.failUnless(ftime(13893086) == '22w 6d')
+ self.failUnless(ftime(59740269) == '1y 46w')
def test_fdate(self):
- self.failUnless(fdate(-1) == "")
+ self.failUnless(fdate(-1) == '')
def test_is_url(self):
- self.failUnless(is_url("http://deluge-torrent.org"))
- self.failIf(is_url("file://test.torrent"))
+ self.failUnless(is_url('http://deluge-torrent.org'))
+ self.failIf(is_url('file://test.torrent'))
def test_is_magnet(self):
- self.failUnless(is_magnet("magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN"))
+ self.failUnless(is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN'))
def test_is_infohash(self):
- self.failUnless(is_infohash("2dc5d0e71a66fe69649a640d39cb00a259704973"))
+ self.failUnless(is_infohash('2dc5d0e71a66fe69649a640d39cb00a259704973'))
def test_get_path_size(self):
self.failUnless(get_path_size(os.devnull) == 0)
- self.failUnless(get_path_size("non-existant.file") == -1)
+ self.failUnless(get_path_size('non-existant.file') == -1)
def test_is_ip(self):
- self.failUnless(is_ip("127.0.0.1"))
- self.failIf(is_ip("127..0.0"))
+ self.failUnless(is_ip('127.0.0.1'))
+ self.failIf(is_ip('127..0.0'))
def test_version_split(self):
- self.failUnless(VersionSplit("1.2.2") == VersionSplit("1.2.2"))
- self.failUnless(VersionSplit("1.2.1") < VersionSplit("1.2.2"))
- self.failUnless(VersionSplit("1.1.9") < VersionSplit("1.2.2"))
- self.failUnless(VersionSplit("1.2.2") > VersionSplit("1.2.1"))
- self.failUnless(VersionSplit("1.2.2") < VersionSplit("1.2.2-dev"))
- self.failUnless(VersionSplit("1.2.2-dev") < VersionSplit("1.3.0-rc2"))
- self.failUnless(VersionSplit("1.2.2") > VersionSplit("1.2.2-rc2"))
- self.failUnless(VersionSplit("1.2.2-rc2-dev") > VersionSplit("1.2.2-rc2"))
- self.failUnless(VersionSplit("1.2.2-rc3") > VersionSplit("1.2.2-rc2"))
- self.failUnless(VersionSplit("0.14.9") == VersionSplit("0.14.9"))
- self.failUnless(VersionSplit("0.14.9") > VersionSplit("0.14.5"))
- self.failUnless(VersionSplit("0.14.10") >= VersionSplit("0.14.9"))
- self.failUnless(VersionSplit("1.4.0") > VersionSplit("1.3.900.dev123"))
- self.failUnless(VersionSplit("1.3.2rc2.dev1") < VersionSplit("1.3.2-rc2"))
- self.failUnless(VersionSplit("1.3.900.dev888") > VersionSplit("1.3.900.dev123"))
- self.failUnless(VersionSplit("1.4.0") > VersionSplit("1.4.0.dev123"))
- self.failUnless(VersionSplit("1.4.0.dev1") < VersionSplit("1.4.0"))
- self.failUnless(VersionSplit("1.4.0a1") < VersionSplit("1.4.0"))
+ self.failUnless(VersionSplit('1.2.2') == VersionSplit('1.2.2'))
+ self.failUnless(VersionSplit('1.2.1') < VersionSplit('1.2.2'))
+ self.failUnless(VersionSplit('1.1.9') < VersionSplit('1.2.2'))
+ self.failUnless(VersionSplit('1.2.2') > VersionSplit('1.2.1'))
+ self.failUnless(VersionSplit('1.2.2') < VersionSplit('1.2.2-dev'))
+ self.failUnless(VersionSplit('1.2.2-dev') < VersionSplit('1.3.0-rc2'))
+ self.failUnless(VersionSplit('1.2.2') > VersionSplit('1.2.2-rc2'))
+ self.failUnless(VersionSplit('1.2.2-rc2-dev') > VersionSplit('1.2.2-rc2'))
+ self.failUnless(VersionSplit('1.2.2-rc3') > VersionSplit('1.2.2-rc2'))
+ self.failUnless(VersionSplit('0.14.9') == VersionSplit('0.14.9'))
+ self.failUnless(VersionSplit('0.14.9') > VersionSplit('0.14.5'))
+ self.failUnless(VersionSplit('0.14.10') >= VersionSplit('0.14.9'))
+ self.failUnless(VersionSplit('1.4.0') > VersionSplit('1.3.900.dev123'))
+ self.failUnless(VersionSplit('1.3.2rc2.dev1') < VersionSplit('1.3.2-rc2'))
+ self.failUnless(VersionSplit('1.3.900.dev888') > VersionSplit('1.3.900.dev123'))
+ self.failUnless(VersionSplit('1.4.0') > VersionSplit('1.4.0.dev123'))
+ self.failUnless(VersionSplit('1.4.0.dev1') < VersionSplit('1.4.0'))
+ self.failUnless(VersionSplit('1.4.0a1') < VersionSplit('1.4.0'))
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)
diff --git a/deluge/tests/test_component.py b/deluge/tests/test_component.py
index 57558e150..41922cfd5 100644
--- a/deluge/tests/test_component.py
+++ b/deluge/tests/test_component.py
@@ -69,41 +69,41 @@ class ComponentTestClass(BaseTestCase):
def test_start_component(self):
def on_start(result, c):
- self.assertEquals(c._component_state, "Started")
+ self.assertEquals(c._component_state, 'Started')
self.assertEquals(c.start_count, 1)
- c = ComponentTester("test_start_c1")
- d = component.start(["test_start_c1"])
+ c = ComponentTester('test_start_c1')
+ d = component.start(['test_start_c1'])
d.addCallback(on_start, c)
return d
def test_start_stop_depends(self):
def on_stop(result, c1, c2):
- self.assertEquals(c1._component_state, "Stopped")
- self.assertEquals(c2._component_state, "Stopped")
+ self.assertEquals(c1._component_state, 'Stopped')
+ self.assertEquals(c2._component_state, 'Stopped')
self.assertEquals(c1.stop_count, 1)
self.assertEquals(c2.stop_count, 1)
def on_start(result, c1, c2):
- self.assertEquals(c1._component_state, "Started")
- self.assertEquals(c2._component_state, "Started")
+ self.assertEquals(c1._component_state, 'Started')
+ self.assertEquals(c2._component_state, 'Started')
self.assertEquals(c1.start_count, 1)
self.assertEquals(c2.start_count, 1)
- return component.stop(["test_start_depends_c1"]).addCallback(on_stop, c1, c2)
+ return component.stop(['test_start_depends_c1']).addCallback(on_stop, c1, c2)
- c1 = ComponentTester("test_start_depends_c1")
- c2 = ComponentTester("test_start_depends_c2", depend=["test_start_depends_c1"])
+ c1 = ComponentTester('test_start_depends_c1')
+ c2 = ComponentTester('test_start_depends_c2', depend=['test_start_depends_c1'])
- d = component.start(["test_start_depends_c2"])
+ d = component.start(['test_start_depends_c2'])
d.addCallback(on_start, c1, c2)
return d
def start_with_depends(self):
- c1 = ComponentTesterDelayStart("test_start_all_c1")
- c2 = ComponentTester("test_start_all_c2", depend=["test_start_all_c4"])
- c3 = ComponentTesterDelayStart("test_start_all_c3", depend=["test_start_all_c5", "test_start_all_c1"])
- c4 = ComponentTester("test_start_all_c4", depend=["test_start_all_c3"])
- c5 = ComponentTester("test_start_all_c5")
+ c1 = ComponentTesterDelayStart('test_start_all_c1')
+ c2 = ComponentTester('test_start_all_c2', depend=['test_start_all_c4'])
+ c3 = ComponentTesterDelayStart('test_start_all_c3', depend=['test_start_all_c5', 'test_start_all_c1'])
+ c4 = ComponentTester('test_start_all_c4', depend=['test_start_all_c3'])
+ c5 = ComponentTester('test_start_all_c5')
d = component.start()
return (d, c1, c2, c3, c4, c5)
@@ -115,7 +115,7 @@ class ComponentTestClass(BaseTestCase):
def test_start_all(self):
def on_start(*args):
for c in args[1:]:
- self.assertEquals(c._component_state, "Started")
+ self.assertEquals(c._component_state, 'Started')
self.assertEquals(c.start_count, 1)
ret = self.start_with_depends()
@@ -124,36 +124,36 @@ class ComponentTestClass(BaseTestCase):
return ret[0]
def test_register_exception(self):
- ComponentTester("test_register_exception_c1")
+ ComponentTester('test_register_exception_c1')
self.assertRaises(
component.ComponentAlreadyRegistered,
ComponentTester,
- "test_register_exception_c1")
+ 'test_register_exception_c1')
def test_stop_component(self):
def on_stop(result, c):
- self.assertEquals(c._component_state, "Stopped")
+ self.assertEquals(c._component_state, 'Stopped')
self.assertFalse(c._component_timer.running)
self.assertEquals(c.stop_count, 1)
def on_start(result, c):
- self.assertEquals(c._component_state, "Started")
- return component.stop(["test_stop_component_c1"]).addCallback(on_stop, c)
+ self.assertEquals(c._component_state, 'Started')
+ return component.stop(['test_stop_component_c1']).addCallback(on_stop, c)
- c = ComponentTesterUpdate("test_stop_component_c1")
- d = component.start(["test_stop_component_c1"])
+ c = ComponentTesterUpdate('test_stop_component_c1')
+ d = component.start(['test_stop_component_c1'])
d.addCallback(on_start, c)
return d
def test_stop_all(self):
def on_stop(result, *args):
for c in args:
- self.assertEquals(c._component_state, "Stopped")
+ self.assertEquals(c._component_state, 'Stopped')
self.assertEquals(c.stop_count, 1)
def on_start(result, *args):
for c in args:
- self.assertEquals(c._component_state, "Started")
+ self.assertEquals(c._component_state, 'Started')
return component.stop().addCallback(on_stop, *args)
ret = self.start_with_depends()
@@ -168,50 +168,50 @@ class ComponentTestClass(BaseTestCase):
self.assertNotEqual(c1.counter, counter)
return component.stop()
- c1 = ComponentTesterUpdate("test_update_c1")
+ c1 = ComponentTesterUpdate('test_update_c1')
cnt = int(c1.counter)
- d = component.start(["test_update_c1"])
+ d = component.start(['test_update_c1'])
d.addCallback(on_start, c1, cnt)
return d
def test_pause(self):
def on_pause(result, c1, counter):
- self.assertEqual(c1._component_state, "Paused")
+ self.assertEqual(c1._component_state, 'Paused')
self.assertNotEqual(c1.counter, counter)
self.assertFalse(c1._component_timer.running)
def on_start(result, c1, counter):
self.assertTrue(c1._component_timer)
self.assertNotEqual(c1.counter, counter)
- d = component.pause(["test_pause_c1"])
+ d = component.pause(['test_pause_c1'])
d.addCallback(on_pause, c1, counter)
return d
- c1 = ComponentTesterUpdate("test_pause_c1")
+ c1 = ComponentTesterUpdate('test_pause_c1')
cnt = int(c1.counter)
- d = component.start(["test_pause_c1"])
+ d = component.start(['test_pause_c1'])
d.addCallback(on_start, c1, cnt)
return d
@defer.inlineCallbacks
def test_component_start_error(self):
- ComponentTesterUpdate("test_pause_c1")
- yield component.start(["test_pause_c1"])
- yield component.pause(["test_pause_c1"])
- test_comp = component.get("test_pause_c1")
+ ComponentTesterUpdate('test_pause_c1')
+ yield component.start(['test_pause_c1'])
+ yield component.pause(['test_pause_c1'])
+ test_comp = component.get('test_pause_c1')
try:
result = self.failureResultOf(test_comp._component_start())
except AttributeError:
- raise SkipTest("This test requires trial failureResultOf() in Twisted version >= 13")
+ raise SkipTest('This test requires trial failureResultOf() in Twisted version >= 13')
self.assertEqual(result.check(component.ComponentException), component.ComponentException)
@defer.inlineCallbacks
def test_start_paused_error(self):
- ComponentTesterUpdate("test_pause_c1")
- yield component.start(["test_pause_c1"])
- yield component.pause(["test_pause_c1"])
+ ComponentTesterUpdate('test_pause_c1')
+ yield component.start(['test_pause_c1'])
+ yield component.pause(['test_pause_c1'])
# Deferreds that fail in component have to error handler which results in
# twisted doing a log.err call which causes the test to fail.
@@ -223,12 +223,12 @@ class ComponentTestClass(BaseTestCase):
[(defer.FAILURE,
component.ComponentException("Trying to start a component ('%s') not in "
"stopped state. Current state: '%s'" %
- ("test_pause_c1", "Paused"), ""))])
+ ('test_pause_c1', 'Paused'), ''))])
def test_shutdown(self):
def on_shutdown(result, c1):
self.assertTrue(c1.shutdowned)
- self.assertEquals(c1._component_state, "Stopped")
+ self.assertEquals(c1._component_state, 'Stopped')
self.assertEquals(c1.stop_count, 1)
def on_start(result, c1):
@@ -236,7 +236,7 @@ class ComponentTestClass(BaseTestCase):
d.addCallback(on_shutdown, c1)
return d
- c1 = ComponentTesterShutdown("test_shutdown_c1")
- d = component.start(["test_shutdown_c1"])
+ c1 = ComponentTesterShutdown('test_shutdown_c1')
+ d = component.start(['test_shutdown_c1'])
d.addCallback(on_start, c1)
return d
diff --git a/deluge/tests/test_config.py b/deluge/tests/test_config.py
index 3be4d0b55..c38c1c0bf 100644
--- a/deluge/tests/test_config.py
+++ b/deluge/tests/test_config.py
@@ -10,7 +10,7 @@ from deluge.config import Config
from .common import set_tmp_config_dir
-DEFAULTS = {"string": "foobar", "int": 1, "float": 0.435, "bool": True, "unicode": u"foobar"}
+DEFAULTS = {'string': 'foobar', 'int': 1, 'float': 0.435, 'bool': True, 'unicode': u'foobar'}
class ConfigTestCase(unittest.TestCase):
@@ -18,102 +18,102 @@ class ConfigTestCase(unittest.TestCase):
self.config_dir = set_tmp_config_dir()
def test_init(self):
- config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir)
+ config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir)
self.assertEquals(DEFAULTS, config.config)
- config = Config("test.conf", config_dir=self.config_dir)
+ config = Config('test.conf', config_dir=self.config_dir)
self.assertEquals({}, config.config)
def test_set_get_item(self):
- config = Config("test.conf", config_dir=self.config_dir)
- config["foo"] = 1
- self.assertEquals(config["foo"], 1)
- self.assertRaises(ValueError, config.set_item, "foo", "bar")
+ config = Config('test.conf', config_dir=self.config_dir)
+ config['foo'] = 1
+ self.assertEquals(config['foo'], 1)
+ self.assertRaises(ValueError, config.set_item, 'foo', 'bar')
- config["foo"] = 2
- self.assertEquals(config.get_item("foo"), 2)
+ config['foo'] = 2
+ self.assertEquals(config.get_item('foo'), 2)
- config["foo"] = "3"
- self.assertEquals(config.get_item("foo"), 3)
+ config['foo'] = '3'
+ self.assertEquals(config.get_item('foo'), 3)
- config["unicode"] = u"ВИДЕОФИЛЬМЫ"
- self.assertEquals(config["unicode"], u"ВИДЕОФИЛЬМЫ")
+ config['unicode'] = u'ВИДЕОФИЛЬМЫ'
+ self.assertEquals(config['unicode'], u'ВИДЕОФИЛЬМЫ')
- config["unicode"] = "foostring"
- self.assertTrue(isinstance(config.get_item("unicode"), unicode))
+ config['unicode'] = 'foostring'
+ self.assertTrue(isinstance(config.get_item('unicode'), unicode))
config._save_timer.cancel()
def test_set_get_item_none(self):
- config = Config("test.conf", config_dir=self.config_dir)
+ config = Config('test.conf', config_dir=self.config_dir)
- config["foo"] = None
- self.assertIsNone(config["foo"])
- self.assertIsInstance(config["foo"], type(None))
+ config['foo'] = None
+ self.assertIsNone(config['foo'])
+ self.assertIsInstance(config['foo'], type(None))
- config["foo"] = 1
- self.assertEquals(config.get("foo"), 1)
+ config['foo'] = 1
+ self.assertEquals(config.get('foo'), 1)
- config["foo"] = None
- self.assertIsNone(config["foo"])
+ config['foo'] = None
+ self.assertIsNone(config['foo'])
- config["bar"] = None
- self.assertIsNone(config["bar"])
+ config['bar'] = None
+ self.assertIsNone(config['bar'])
- config["bar"] = None
- self.assertIsNone(config["bar"])
+ config['bar'] = None
+ self.assertIsNone(config['bar'])
config._save_timer.cancel()
def test_get(self):
- config = Config("test.conf", config_dir=self.config_dir)
- config["foo"] = 1
- self.assertEquals(config.get("foo"), 1)
- self.assertEquals(config.get("foobar"), None)
- self.assertEquals(config.get("foobar", 2), 2)
- config["foobar"] = 5
- self.assertEquals(config.get("foobar", 2), 5)
+ config = Config('test.conf', config_dir=self.config_dir)
+ config['foo'] = 1
+ self.assertEquals(config.get('foo'), 1)
+ self.assertEquals(config.get('foobar'), None)
+ self.assertEquals(config.get('foobar', 2), 2)
+ config['foobar'] = 5
+ self.assertEquals(config.get('foobar', 2), 5)
def test_load(self):
def check_config():
- config = Config("test.conf", config_dir=self.config_dir)
+ config = Config('test.conf', config_dir=self.config_dir)
- self.assertEquals(config["string"], "foobar")
- self.assertEquals(config["float"], 0.435)
+ self.assertEquals(config['string'], 'foobar')
+ self.assertEquals(config['float'], 0.435)
# Test loading an old config from 1.1.x
import pickle
- with open(os.path.join(self.config_dir, "test.conf"), "wb") as _file:
+ with open(os.path.join(self.config_dir, 'test.conf'), 'wb') as _file:
pickle.dump(DEFAULTS, _file)
check_config()
# Test opening a previous 1.2 config file of just a json object
import json
- with open(os.path.join(self.config_dir, "test.conf"), "wb") as _file:
+ with open(os.path.join(self.config_dir, 'test.conf'), 'wb') as _file:
json.dump(DEFAULTS, _file, indent=2)
check_config()
# Test opening a previous 1.2 config file of having the format versions
# as ints
- with open(os.path.join(self.config_dir, "test.conf"), "wb") as _file:
- _file.write(str(1) + "\n")
- _file.write(str(1) + "\n")
+ with open(os.path.join(self.config_dir, 'test.conf'), 'wb') as _file:
+ _file.write(str(1) + '\n')
+ _file.write(str(1) + '\n')
json.dump(DEFAULTS, _file, indent=2)
check_config()
# Test the 1.2 config format
- version = {"format": 1, "file": 1}
- with open(os.path.join(self.config_dir, "test.conf"), "wb") as _file:
+ version = {'format': 1, 'file': 1}
+ with open(os.path.join(self.config_dir, 'test.conf'), 'wb') as _file:
json.dump(version, _file, indent=2)
json.dump(DEFAULTS, _file, indent=2)
check_config()
def test_save(self):
- config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir)
+ config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir)
# We do this twice because the first time we need to save the file to disk
# and the second time we do a compare and we should not write
ret = config.save()
@@ -121,23 +121,23 @@ class ConfigTestCase(unittest.TestCase):
ret = config.save()
self.assertTrue(ret)
- config["string"] = "baz"
- config["int"] = 2
+ config['string'] = 'baz'
+ config['int'] = 2
ret = config.save()
self.assertTrue(ret)
del config
- config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir)
- self.assertEquals(config["string"], "baz")
- self.assertEquals(config["int"], 2)
+ config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir)
+ self.assertEquals(config['string'], 'baz')
+ self.assertEquals(config['int'], 2)
def test_save_timer(self):
self.clock = task.Clock()
deluge.config.callLater = self.clock.callLater
- config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir)
- config["string"] = "baz"
- config["int"] = 2
+ config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir)
+ config['string'] = 'baz'
+ config['int'] = 2
self.assertTrue(config._save_timer.active())
# Timeout set for 5 seconds in config, so lets move clock by 5 seconds
@@ -146,9 +146,9 @@ class ConfigTestCase(unittest.TestCase):
def check_config(config):
self.assertTrue(not config._save_timer.active())
del config
- config = Config("test.conf", defaults=DEFAULTS, config_dir=self.config_dir)
- self.assertEquals(config["string"], "baz")
- self.assertEquals(config["int"], 2)
+ config = Config('test.conf', defaults=DEFAULTS, config_dir=self.config_dir)
+ self.assertEquals(config['string'], 'baz')
+ self.assertEquals(config['int'], 2)
check_config(config)
diff --git a/deluge/tests/test_core.py b/deluge/tests/test_core.py
index 6d9165dac..620951268 100644
--- a/deluge/tests/test_core.py
+++ b/deluge/tests/test_core.py
@@ -28,12 +28,12 @@ common.disable_new_release_check()
class CookieResource(Resource):
def render(self, request):
- if request.getCookie("password") != "deluge":
+ if request.getCookie('password') != 'deluge':
request.setResponseCode(FORBIDDEN)
return
- request.setHeader("Content-Type", "application/x-bittorrent")
- with open(common.get_test_data_file("ubuntu-9.04-desktop-i386.iso.torrent")) as _file:
+ request.setHeader('Content-Type', 'application/x-bittorrent')
+ with open(common.get_test_data_file('ubuntu-9.04-desktop-i386.iso.torrent')) as _file:
data = _file.read()
return data
@@ -41,11 +41,11 @@ class CookieResource(Resource):
class PartialDownload(Resource):
def render(self, request):
- with open(common.get_test_data_file("ubuntu-9.04-desktop-i386.iso.torrent")) as _file:
+ with open(common.get_test_data_file('ubuntu-9.04-desktop-i386.iso.torrent')) as _file:
data = _file.read()
- request.setHeader("Content-Type", len(data))
- request.setHeader("Content-Type", "application/x-bittorrent")
- if request.requestHeaders.hasHeader("accept-encoding"):
+ request.setHeader('Content-Type', len(data))
+ request.setHeader('Content-Type', 'application/x-bittorrent')
+ if request.requestHeaders.hasHeader('accept-encoding'):
return compress(data, request)
return data
@@ -53,8 +53,8 @@ class PartialDownload(Resource):
class RedirectResource(Resource):
def render(self, request):
- request.redirect("/ubuntu-9.04-desktop-i386.iso.torrent")
- return ""
+ request.redirect('/ubuntu-9.04-desktop-i386.iso.torrent')
+ return ''
class TopLevelResource(Resource):
@@ -63,11 +63,11 @@ class TopLevelResource(Resource):
def __init__(self):
Resource.__init__(self)
- 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('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')))
class CoreTestCase(BaseTestCase):
@@ -106,7 +106,7 @@ class CoreTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_add_torrent_files(self):
options = {}
- filenames = ["test.torrent", "test_torrent.file.torrent"]
+ filenames = ['test.torrent', 'test_torrent.file.torrent']
files_to_add = []
for f in filenames:
filename = common.get_test_data_file(f)
@@ -119,7 +119,7 @@ class CoreTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_add_torrent_files_error_duplicate(self):
options = {}
- filenames = ["test.torrent", "test.torrent"]
+ filenames = ['test.torrent', 'test.torrent']
files_to_add = []
for f in filenames:
filename = common.get_test_data_file(f)
@@ -128,12 +128,12 @@ class CoreTestCase(BaseTestCase):
files_to_add.append((filename, filedump, options))
errors = yield self.core.add_torrent_files(files_to_add)
self.assertEquals(len(errors), 1)
- self.assertTrue(str(errors[0]).startswith("Torrent already in session"))
+ self.assertTrue(str(errors[0]).startswith('Torrent already in session'))
@defer.inlineCallbacks
def test_add_torrent_file(self):
options = {}
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
@@ -141,28 +141,28 @@ class CoreTestCase(BaseTestCase):
# Get the info hash from the test.torrent
from deluge.bencode import bdecode, bencode
with open(filename) as _file:
- info_hash = sha(bencode(bdecode(_file.read())["info"])).hexdigest()
+ info_hash = sha(bencode(bdecode(_file.read())['info'])).hexdigest()
self.assertEquals(torrent_id, info_hash)
def test_add_torrent_file_invalid_filedump(self):
options = {}
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
self.assertRaises(AddTorrentError, self.core.add_torrent_file, filename, False, options)
@defer.inlineCallbacks
def test_add_torrent_url(self):
- url = "http://localhost:%d/ubuntu-9.04-desktop-i386.iso.torrent" % self.listen_port
+ url = 'http://localhost:%d/ubuntu-9.04-desktop-i386.iso.torrent' % self.listen_port
options = {}
- info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
+ info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
torrent_id = yield self.core.add_torrent_url(url, options)
self.assertEquals(torrent_id, info_hash)
def test_add_torrent_url_with_cookie(self):
- url = "http://localhost:%d/cookie" % self.listen_port
+ url = 'http://localhost:%d/cookie' % self.listen_port
options = {}
- headers = {"Cookie": "password=deluge"}
- info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
+ headers = {'Cookie': 'password=deluge'}
+ info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
d = self.core.add_torrent_url(url, options)
d.addCallbacks(self.fail, self.assertIsInstance, errbackArgs=(Failure,))
@@ -173,18 +173,18 @@ class CoreTestCase(BaseTestCase):
return d
def test_add_torrent_url_with_redirect(self):
- url = "http://localhost:%d/redirect" % self.listen_port
+ url = 'http://localhost:%d/redirect' % self.listen_port
options = {}
- info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
+ info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
d = self.core.add_torrent_url(url, options)
d.addCallback(self.assertEquals, info_hash)
return d
def test_add_torrent_url_with_partial_download(self):
- url = "http://localhost:%d/partial" % self.listen_port
+ url = 'http://localhost:%d/partial' % self.listen_port
options = {}
- info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
+ info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
d = self.core.add_torrent_url(url, options)
d.addCallback(self.assertEquals, info_hash)
@@ -192,7 +192,7 @@ class CoreTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_add_torrent_magnet(self):
- info_hash = "60d5d82328b4547511fdeac9bf4d0112daa0ce00"
+ info_hash = '60d5d82328b4547511fdeac9bf4d0112daa0ce00'
uri = deluge.common.create_magnet_uri(info_hash)
options = {}
torrent_id = yield self.core.add_torrent_magnet(uri, options)
@@ -201,7 +201,7 @@ class CoreTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_remove_torrent(self):
options = {}
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
@@ -210,17 +210,17 @@ class CoreTestCase(BaseTestCase):
self.assertEquals(len(self.core.get_session_state()), 0)
def test_remove_torrent_invalid(self):
- self.assertRaises(InvalidTorrentError, self.core.remove_torrent, "torrentidthatdoesntexist", True)
+ self.assertRaises(InvalidTorrentError, self.core.remove_torrent, 'torrentidthatdoesntexist', True)
@defer.inlineCallbacks
def test_remove_torrents(self):
options = {}
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
- filename2 = common.get_test_data_file("unicode_filenames.torrent")
+ filename2 = common.get_test_data_file('unicode_filenames.torrent')
with open(filename2) as _file:
filedump = base64.encodestring(_file.read())
torrent_id2 = yield self.core.add_torrent_file(filename2, filedump, options)
@@ -238,35 +238,35 @@ class CoreTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_remove_torrents_invalid(self):
options = {}
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
- val = yield self.core.remove_torrents(["invalidid1", "invalidid2", torrent_id], False)
+ val = yield self.core.remove_torrents(['invalidid1', 'invalidid2', torrent_id], False)
self.assertEqual(len(val), 2)
self.assertEqual(val[0], ('invalidid1', "torrent_id 'invalidid1' not in session."))
self.assertEqual(val[1], ('invalidid2', "torrent_id 'invalidid2' not in session."))
def test_get_session_status(self):
- status = self.core.get_session_status(["upload_rate", "download_rate"])
+ status = self.core.get_session_status(['upload_rate', 'download_rate'])
self.assertEquals(type(status), dict)
- self.assertEquals(status["upload_rate"], 0.0)
+ self.assertEquals(status['upload_rate'], 0.0)
def test_get_cache_status(self):
status = self.core.get_cache_status()
self.assertEquals(type(status), dict)
- self.assertEquals(status["write_hit_ratio"], 0.0)
- self.assertEquals(status["read_hit_ratio"], 0.0)
+ self.assertEquals(status['write_hit_ratio'], 0.0)
+ self.assertEquals(status['read_hit_ratio'], 0.0)
def test_get_free_space(self):
- space = self.core.get_free_space(".")
+ space = self.core.get_free_space('.')
# get_free_space returns long on Python 2 (32-bit).
if sys.version_info >= (3, 0):
self.assertTrue(isinstance(space, int))
else:
self.assertTrue(isinstance(space, (int, long)))
self.assertTrue(space >= 0)
- self.assertEquals(self.core.get_free_space("/someinvalidpath"), -1)
+ self.assertEquals(self.core.get_free_space('/someinvalidpath'), -1)
@pytest.mark.slow
def test_test_listen_port(self):
@@ -295,11 +295,11 @@ class CoreTestCase(BaseTestCase):
self.assertEquals(deluge.core.torrent.sanitize_filepath(key, folder=True), pathlist[key] + '/')
def test_get_set_config_values(self):
- self.assertEquals(self.core.get_config_values(["abc", "foo"]), {"foo": None, "abc": None})
- self.assertEquals(self.core.get_config_value("foobar"), None)
- self.core.set_config({"abc": "def", "foo": 10, "foobar": "barfoo"})
- self.assertEquals(self.core.get_config_values(["foo", "abc"]), {"foo": 10, "abc": "def"})
- self.assertEquals(self.core.get_config_value("foobar"), "barfoo")
+ self.assertEquals(self.core.get_config_values(['abc', 'foo']), {'foo': None, 'abc': None})
+ self.assertEquals(self.core.get_config_value('foobar'), None)
+ self.core.set_config({'abc': 'def', 'foo': 10, 'foobar': 'barfoo'})
+ self.assertEquals(self.core.get_config_values(['foo', 'abc']), {'foo': 10, 'abc': 'def'})
+ self.assertEquals(self.core.get_config_value('foobar'), 'barfoo')
def test_read_only_config_keys(self):
key = 'max_upload_speed'
diff --git a/deluge/tests/test_error.py b/deluge/tests/test_error.py
index 0b71344a8..9bac1c689 100644
--- a/deluge/tests/test_error.py
+++ b/deluge/tests/test_error.py
@@ -11,26 +11,26 @@ class ErrorTestCase(unittest.TestCase):
pass
def test_deluge_error(self):
- msg = "Some message"
+ msg = 'Some message'
e = deluge.error.DelugeError(msg)
self.assertEquals(str(e), msg)
self.assertEquals(e._args, (msg,))
self.assertEquals(e._kwargs, {})
def test_incompatible_client(self):
- version = "1.3.6"
+ version = '1.3.6'
e = deluge.error.IncompatibleClient(version)
- self.assertEquals(str(e), "Your deluge client is not compatible with the daemon. \
-Please upgrade your client to %s" % version)
+ self.assertEquals(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
required_level = 10
e = deluge.error.NotAuthorizedError(current_level, required_level)
- self.assertEquals(str(e), "Auth level too low: %d < %d" % (current_level, required_level))
+ self.assertEquals(str(e), 'Auth level too low: %d < %d' % (current_level, required_level))
def test_bad_login_error(self):
- message = "Login failed"
- username = "deluge"
+ message = 'Login failed'
+ username = 'deluge'
e = deluge.error.BadLoginError(message, username)
self.assertEquals(str(e), message)
diff --git a/deluge/tests/test_files_tab.py b/deluge/tests/test_files_tab.py
index 4b749e5fc..51a3684ba 100644
--- a/deluge/tests/test_files_tab.py
+++ b/deluge/tests/test_files_tab.py
@@ -30,13 +30,13 @@ class FilesTabTestCase(BaseTestCase):
def set_up(self):
if libs_available is False:
- raise unittest.SkipTest("GTKUI dependencies not available")
+ raise unittest.SkipTest('GTKUI dependencies not available')
common.set_tmp_config_dir()
- ConfigManager("gtkui.conf", defaults=DEFAULT_PREFS)
+ ConfigManager('gtkui.conf', defaults=DEFAULT_PREFS)
self.mainwindow = MainWindow()
self.filestab = FilesTab()
- self.t_id = "1"
+ self.t_id = '1'
self.filestab.torrent_id = self.t_id
self.index = 1
@@ -48,7 +48,7 @@ class FilesTabTestCase(BaseTestCase):
level = 1
def p_level(s, l):
- print("%s%s" % (" " * l, s))
+ print('%s%s' % (' ' * l, s))
def _print_treestore_children(i, lvl):
while i:
@@ -57,9 +57,9 @@ class FilesTabTestCase(BaseTestCase):
_print_treestore_children(treestore.iter_children(i), lvl + 2)
i = treestore.iter_next(i)
- print("\n%s" % title)
+ print('\n%s' % title)
_print_treestore_children(root, level)
- print("")
+ print('')
def verify_treestore(self, treestore, tree):
@@ -81,54 +81,54 @@ class FilesTabTestCase(BaseTestCase):
self.filestab.files_list[self.t_id] = ({u'index': 0, u'path': u'1/test_10.txt', u'offset': 0, u'size': 13},
{u'index': 1, u'path': u'test_100.txt', u'offset': 13, u'size': 14})
self.filestab.update_files()
- self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, "2/test_100.txt")
+ self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '2/test_100.txt')
- ret = self.verify_treestore(self.filestab.treestore, [["1/", [["test_10.txt"]]], ["2/", [["test_100.txt"]]]])
+ ret = self.verify_treestore(self.filestab.treestore, [['1/', [['test_10.txt']]], ['2/', [['test_100.txt']]]])
if not ret:
- self.print_treestore("Treestore not expected:", self.filestab.treestore)
+ self.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
def test_files_tab2(self):
self.filestab.files_list[self.t_id] = ({u'index': 0, u'path': u'1/1/test_10.txt', u'offset': 0, u'size': 13},
{u'index': 1, u'path': u'test_100.txt', u'offset': 13, u'size': 14})
self.filestab.update_files()
- self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, "1/1/test_100.txt")
+ self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/1/test_100.txt')
- ret = self.verify_treestore(self.filestab.treestore, [["1/", [["1/", [["test_100.txt"], ["test_10.txt"]]]]]])
+ ret = self.verify_treestore(self.filestab.treestore, [['1/', [['1/', [['test_100.txt'], ['test_10.txt']]]]]])
if not ret:
- self.print_treestore("Treestore not expected:", self.filestab.treestore)
+ self.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
def test_files_tab3(self):
self.filestab.files_list[self.t_id] = ({u'index': 0, u'path': u'1/test_10.txt', u'offset': 0, u'size': 13},
{u'index': 1, u'path': u'test_100.txt', u'offset': 13, u'size': 14})
self.filestab.update_files()
- self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, "1/test_100.txt")
+ self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/test_100.txt')
- ret = self.verify_treestore(self.filestab.treestore, [["1/", [["test_100.txt"], ["test_10.txt"]]]])
+ ret = self.verify_treestore(self.filestab.treestore, [['1/', [['test_100.txt'], ['test_10.txt']]]])
if not ret:
- self.print_treestore("Treestore not expected:", self.filestab.treestore)
+ self.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
def test_files_tab4(self):
self.filestab.files_list[self.t_id] = ({u'index': 0, u'path': u'1/test_10.txt', u'offset': 0, u'size': 13},
{u'index': 1, u'path': u'1/test_100.txt', u'offset': 13, u'size': 14})
self.filestab.update_files()
- self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, "1/2/test_100.txt")
+ 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.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
def test_files_tab5(self):
self.filestab.files_list[self.t_id] = ({u'index': 0, u'path': u'1/test_10.txt', u'offset': 0, u'size': 13},
{u'index': 1, u'path': u'2/test_100.txt', u'offset': 13, u'size': 14})
self.filestab.update_files()
- self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, "1/test_100.txt")
+ self.filestab._on_torrentfilerenamed_event(self.t_id, self.index, '1/test_100.txt')
- ret = self.verify_treestore(self.filestab.treestore, [["1/", [["test_100.txt"], ["test_10.txt"]]]])
+ ret = self.verify_treestore(self.filestab.treestore, [['1/', [['test_100.txt'], ['test_10.txt']]]])
if not ret:
- self.print_treestore("Treestore not expected:", self.filestab.treestore)
+ self.print_treestore('Treestore not expected:', self.filestab.treestore)
self.assertTrue(ret)
diff --git a/deluge/tests/test_httpdownloader.py b/deluge/tests/test_httpdownloader.py
index ae381cc50..a8acd9f47 100644
--- a/deluge/tests/test_httpdownloader.py
+++ b/deluge/tests/test_httpdownloader.py
@@ -19,7 +19,7 @@ temp_dir = tempfile.mkdtemp()
def fname(name):
- return "%s/%s" % (temp_dir, name)
+ return '%s/%s' % (temp_dir, name)
class RedirectResource(Resource):
@@ -32,31 +32,31 @@ class RedirectResource(Resource):
class RenameResource(Resource):
def render(self, request):
- filename = request.args.get("filename", ["renamed_file"])[0]
- request.setHeader("Content-Type", "text/plain")
- request.setHeader("Content-Disposition", "attachment; filename=" +
+ filename = request.args.get('filename', ['renamed_file'])[0]
+ request.setHeader('Content-Type', 'text/plain')
+ request.setHeader('Content-Disposition', 'attachment; filename=' +
filename)
- return "This file should be called " + filename
+ return 'This file should be called ' + filename
class CookieResource(Resource):
def render(self, request):
- request.setHeader("Content-Type", "text/plain")
- if request.getCookie("password") is None:
- return "Password cookie not set!"
+ request.setHeader('Content-Type', 'text/plain')
+ if request.getCookie('password') is None:
+ return 'Password cookie not set!'
- if request.getCookie("password") == "deluge":
- return "COOKIE MONSTER!"
+ if request.getCookie('password') == 'deluge':
+ return 'COOKIE MONSTER!'
- return request.getCookie("password")
+ return request.getCookie('password')
class GzipResource(Resource):
def render(self, request):
- message = request.args.get("msg", ["EFFICIENCY!"])[0]
- request.setHeader("Content-Type", "text/plain")
+ message = request.args.get('msg', ['EFFICIENCY!'])[0]
+ request.setHeader('Content-Type', 'text/plain')
return compress(message, request)
@@ -69,9 +69,9 @@ class PartialDownloadResource(Resource):
def render(self, request):
# encoding = request.requestHeaders._rawHeaders.get("accept-encoding", None)
if self.render_count == 0:
- request.setHeader("content-length", "5")
+ request.setHeader('content-length', '5')
else:
- request.setHeader("content-length", "3")
+ request.setHeader('content-length', '3')
# if encoding == "deflate, gzip, x-gzip":
request.write('abc')
@@ -85,32 +85,32 @@ class TopLevelResource(Resource):
def __init__(self):
Resource.__init__(self)
- self.putChild("cookie", CookieResource())
- self.putChild("gzip", GzipResource())
+ self.putChild('cookie', CookieResource())
+ self.putChild('gzip', GzipResource())
self.redirect_rsrc = RedirectResource()
- self.putChild("redirect", self.redirect_rsrc)
- self.putChild("rename", RenameResource())
- self.putChild("partial", PartialDownloadResource())
+ self.putChild('redirect', self.redirect_rsrc)
+ self.putChild('rename', RenameResource())
+ self.putChild('partial', PartialDownloadResource())
def getChild(self, path, request): # NOQA
- if path == "":
+ if path == '':
return self
else:
return Resource.getChild(self, path, request)
def render(self, request):
- if request.getHeader("If-Modified-Since"):
+ if request.getHeader('If-Modified-Since'):
request.setResponseCode(NOT_MODIFIED)
- return "<h1>Deluge HTTP Downloader tests webserver here</h1>"
+ return '<h1>Deluge HTTP Downloader tests webserver here</h1>'
class DownloadFileTestCase(unittest.TestCase):
- def get_url(self, path=""):
- return "http://localhost:%d/%s" % (self.listen_port, path)
+ def get_url(self, path=''):
+ return 'http://localhost:%d/%s' % (self.listen_port, path)
def setUp(self): # NOQA
- setup_logger("warning", fname("log_file"))
+ setup_logger('warning', fname('log_file'))
self.website = Site(TopLevelResource())
self.listen_port = 51242
self.website.resource.redirect_rsrc.get_url = self.get_url
@@ -145,69 +145,69 @@ class DownloadFileTestCase(unittest.TestCase):
return filename
def test_download(self):
- d = download_file(self.get_url(), fname("index.html"))
- d.addCallback(self.assertEqual, fname("index.html"))
+ d = download_file(self.get_url(), fname('index.html'))
+ d.addCallback(self.assertEqual, fname('index.html'))
return d
def test_download_without_required_cookies(self):
- url = self.get_url("cookie")
- d = download_file(url, fname("none"))
+ url = self.get_url('cookie')
+ d = download_file(url, fname('none'))
d.addCallback(self.fail)
d.addErrback(self.assertIsInstance, Failure)
return d
def test_download_with_required_cookies(self):
- url = self.get_url("cookie")
- cookie = {"cookie": "password=deluge"}
- d = download_file(url, fname("monster"), headers=cookie)
- d.addCallback(self.assertEqual, fname("monster"))
- d.addCallback(self.assertContains, "COOKIE MONSTER!")
+ url = self.get_url('cookie')
+ cookie = {'cookie': 'password=deluge'}
+ d = download_file(url, fname('monster'), headers=cookie)
+ d.addCallback(self.assertEqual, fname('monster'))
+ d.addCallback(self.assertContains, 'COOKIE MONSTER!')
return d
def test_download_with_rename(self):
- url = self.get_url("rename?filename=renamed")
- d = download_file(url, fname("original"))
- d.addCallback(self.assertEqual, fname("renamed"))
- d.addCallback(self.assertContains, "This file should be called renamed")
+ url = self.get_url('rename?filename=renamed')
+ d = download_file(url, fname('original'))
+ d.addCallback(self.assertEqual, fname('renamed'))
+ d.addCallback(self.assertContains, 'This file should be called renamed')
return d
def test_download_with_rename_exists(self):
open(fname('renamed'), 'w').close()
- url = self.get_url("rename?filename=renamed")
- d = download_file(url, fname("original"))
- d.addCallback(self.assertEqual, fname("renamed-1"))
- d.addCallback(self.assertContains, "This file should be called renamed")
+ url = self.get_url('rename?filename=renamed')
+ d = download_file(url, fname('original'))
+ d.addCallback(self.assertEqual, fname('renamed-1'))
+ d.addCallback(self.assertContains, 'This file should be called renamed')
return d
def test_download_with_rename_sanitised(self):
- url = self.get_url("rename?filename=/etc/passwd")
- d = download_file(url, fname("original"))
- d.addCallback(self.assertEqual, fname("passwd"))
- d.addCallback(self.assertContains, "This file should be called /etc/passwd")
+ url = self.get_url('rename?filename=/etc/passwd')
+ d = download_file(url, fname('original'))
+ d.addCallback(self.assertEqual, fname('passwd'))
+ d.addCallback(self.assertContains, 'This file should be called /etc/passwd')
return d
def test_download_with_rename_prevented(self):
- url = self.get_url("rename?filename=spam")
- d = download_file(url, fname("forced"), force_filename=True)
- d.addCallback(self.assertEqual, fname("forced"))
- d.addCallback(self.assertContains, "This file should be called spam")
+ url = self.get_url('rename?filename=spam')
+ d = download_file(url, fname('forced'), force_filename=True)
+ d.addCallback(self.assertEqual, fname('forced'))
+ d.addCallback(self.assertContains, 'This file should be called spam')
return d
def test_download_with_gzip_encoding(self):
- url = self.get_url("gzip?msg=success")
- d = download_file(url, fname("gzip_encoded"))
- d.addCallback(self.assertContains, "success")
+ url = self.get_url('gzip?msg=success')
+ d = download_file(url, fname('gzip_encoded'))
+ d.addCallback(self.assertContains, 'success')
return d
def test_download_with_gzip_encoding_disabled(self):
- url = self.get_url("gzip?msg=fail")
- d = download_file(url, fname("gzip_encoded"), allow_compression=False)
- d.addCallback(self.failIfContains, "fail")
+ url = self.get_url('gzip?msg=fail')
+ d = download_file(url, fname('gzip_encoded'), allow_compression=False)
+ d.addCallback(self.failIfContains, 'fail')
return d
def test_page_redirect_unhandled(self):
- url = self.get_url("redirect")
- d = download_file(url, fname("none"))
+ url = self.get_url('redirect')
+ d = download_file(url, fname('none'))
d.addCallback(self.fail)
def on_redirect(failure):
@@ -216,21 +216,21 @@ class DownloadFileTestCase(unittest.TestCase):
return d
def test_page_redirect(self):
- url = self.get_url("redirect")
- d = download_file(url, fname("none"), handle_redirects=True)
- d.addCallback(self.assertEqual, fname("none"))
+ url = self.get_url('redirect')
+ d = download_file(url, fname('none'), handle_redirects=True)
+ d.addCallback(self.assertEqual, fname('none'))
d.addErrback(self.fail)
return d
def test_page_not_found(self):
- d = download_file(self.get_url("page/not/found"), fname("none"))
+ d = download_file(self.get_url('page/not/found'), fname('none'))
d.addCallback(self.fail)
d.addErrback(self.assertIsInstance, Failure)
return d
def test_page_not_modified(self):
headers = {'If-Modified-Since': formatdate(usegmt=True)}
- d = download_file(self.get_url(), fname("index.html"), headers=headers)
+ d = download_file(self.get_url(), fname('index.html'), headers=headers)
d.addCallback(self.fail)
d.addErrback(self.assertIsInstance, Failure)
return d
diff --git a/deluge/tests/test_json_api.py b/deluge/tests/test_json_api.py
index 87c6f89e7..c3b8e3ea0 100644
--- a/deluge/tests/test_json_api.py
+++ b/deluge/tests/test_json_api.py
@@ -35,8 +35,8 @@ 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", "")
+ 'localhost', self.listen_port, username=kwargs.get('user', ''),
+ password=kwargs.get('password', '')
)
def disconnect_client(self, *args):
@@ -67,27 +67,27 @@ class JSONTestCase(JSONBase):
def test_render_fail_disconnected(self):
json = JSON()
request = MagicMock()
- request.method = "POST"
+ request.method = 'POST'
request._disconnected = True
# When disconnected, returns empty string
- self.assertEquals(json.render(request), "")
+ self.assertEquals(json.render(request), '')
def test_render_fail(self):
json = JSON()
request = MagicMock()
- request.method = "POST"
+ request.method = 'POST'
def compress(contents, request):
return contents
- self.patch(deluge.ui.web.json_api, "compress", compress)
+ self.patch(deluge.ui.web.json_api, 'compress', compress)
def write(response_str):
request.write_was_called = True
response = json_lib.loads(response_str)
- self.assertEquals(response["result"], None)
- self.assertEquals(response["id"], None)
- self.assertEquals(response["error"]["message"], "JSONException: JSON not decodable")
- self.assertEquals(response["error"]["code"], 5)
+ self.assertEquals(response['result'], None)
+ self.assertEquals(response['id'], None)
+ self.assertEquals(response['error']['message'], 'JSONException: JSON not decodable')
+ self.assertEquals(response['error']['code'], 5)
request.write = write
request.write_was_called = False
@@ -98,7 +98,7 @@ class JSONTestCase(JSONBase):
def test_handle_request_invalid_method(self):
json = JSON()
request = MagicMock()
- json_data = {"method": "no-existing-module.test", "id": 0, "params": []}
+ json_data = {'method': 'no-existing-module.test', 'id': 0, 'params': []}
request.json = json_lib.dumps(json_data)
request_id, result, error = json._handle_request(request)
self.assertEquals(error, {'message': 'Unknown method', 'code': 2})
@@ -106,11 +106,11 @@ class JSONTestCase(JSONBase):
def test_handle_request_invalid_json_request(self):
json = JSON()
request = MagicMock()
- request.json = json_lib.dumps({"id": 0, "params": []})
+ request.json = json_lib.dumps({'id': 0, 'params': []})
self.assertRaises(JSONException, json._handle_request, request)
- request.json = json_lib.dumps({"method": "some.method", "params": []})
+ request.json = json_lib.dumps({'method': 'some.method', 'params': []})
self.assertRaises(JSONException, json._handle_request, request)
- request.json = json_lib.dumps({"method": "some.method", "id": 0})
+ request.json = json_lib.dumps({'method': 'some.method', 'id': 0})
self.assertRaises(JSONException, json._handle_request, request)
@@ -125,15 +125,15 @@ class JSONCustomUserTestCase(JSONBase):
def test_handle_request_auth_error(self):
yield self.connect_client()
json = JSON()
- auth_conf = {"session_timeout": 10, "sessions": []}
+ auth_conf = {'session_timeout': 10, 'sessions': []}
Auth(auth_conf) # Must create the component
# Must be called to update remote methods in json object
yield json.get_remote_methods()
request = MagicMock()
- request.getCookie = MagicMock(return_value="bad_value")
- json_data = {"method": "core.get_libtorrent_version", "id": 0, "params": []}
+ request.getCookie = MagicMock(return_value='bad_value')
+ json_data = {'method': 'core.get_libtorrent_version', 'id': 0, 'params': []}
request.json = json_lib.dumps(json_data)
request_id, result, error = json._handle_request(request)
self.assertEquals(error, {'message': 'Not authenticated', 'code': 1})
@@ -164,19 +164,19 @@ class RPCRaiseDelugeErrorJSONTestCase(JSONBase):
def get_session_id(s_id):
return s_id
- self.patch(deluge.ui.web.auth, "get_session_id", get_session_id)
- auth_conf = {"session_timeout": 10, "sessions": []}
+ self.patch(deluge.ui.web.auth, 'get_session_id', get_session_id)
+ auth_conf = {'session_timeout': 10, 'sessions': []}
auth = Auth(auth_conf)
request = Request(MagicMock(), False)
- request.base = ""
+ request.base = ''
auth._create_session(request)
methods = yield json.get_remote_methods()
# Verify the function has been registered
- self.assertTrue("testclass.test" in methods)
+ self.assertTrue('testclass.test' in methods)
request = MagicMock()
- request.getCookie = MagicMock(return_value=auth.config["sessions"].keys()[0])
- json_data = {"method": "testclass.test", "id": 0, "params": []}
+ request.getCookie = MagicMock(return_value=auth.config['sessions'].keys()[0])
+ json_data = {'method': 'testclass.test', 'id': 0, 'params': []}
request.json = json_lib.dumps(json_data)
request_id, result, error = json._handle_request(request)
result.addCallback(self.fail)
@@ -207,16 +207,16 @@ 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)
+ 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)
+ extra_callback['deferred'].addCallback(on_test_raise)
d.addCallback(self.start_core, custom_script=custom_script, print_stderr=False,
timeout=5, extra_callbacks=[extra_callback])
d.addCallbacks(self.connect_client, self.terminate_core)
@@ -228,7 +228,7 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
methods = yield json.get_remote_methods()
# Verify the function has been registered
- self.assertTrue("testclass.test" in methods)
+ self.assertTrue('testclass.test' in methods)
request = MagicMock()
@@ -240,17 +240,17 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
def write(response_str):
request.write_was_called = True
response = json_lib.loads(response_str)
- self.assertEquals(response["result"], None, "BAD RESULT")
- self.assertEquals(response["id"], 0)
- self.assertEquals(response["error"]["message"],
- "Failure: [Failure instance: Traceback (failure with no frames):"
+ self.assertEquals(response['result'], None, 'BAD RESULT')
+ self.assertEquals(response['id'], 0)
+ self.assertEquals(response['error']['message'],
+ 'Failure: [Failure instance: Traceback (failure with no frames):'
" <class 'deluge.error.DelugeError'>: DelugeERROR\n]")
- self.assertEquals(response["error"]["code"], 4)
+ self.assertEquals(response['error']['code'], 4)
request.write = write
request.write_was_called = False
request._disconnected = False
- json_data = {"method": "testclass.test", "id": 0, "params": []}
+ json_data = {'method': 'testclass.test', 'id': 0, 'params': []}
request.json = json_lib.dumps(json_data)
d = json._on_json_request(request)
diff --git a/deluge/tests/test_log.py b/deluge/tests/test_log.py
index 52564177b..c300f991f 100644
--- a/deluge/tests/test_log.py
+++ b/deluge/tests/test_log.py
@@ -21,14 +21,14 @@ class LogTestCase(BaseTestCase):
setup_logger(logging.DEBUG)
def tear_down(self):
- setup_logger("none")
+ setup_logger('none')
def test_old_log_deprecation_warning(self):
from deluge.log import LOG
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
- warnings.simplefilter("always")
- LOG.debug("foo")
+ warnings.simplefilter('always')
+ LOG.debug('foo')
self.assertEqual(w[-1].category, DeprecationWarning)
# def test_twisted_error_log(self):
diff --git a/deluge/tests/test_maketorrent.py b/deluge/tests/test_maketorrent.py
index 24f8b6f43..6011dd99f 100644
--- a/deluge/tests/test_maketorrent.py
+++ b/deluge/tests/test_maketorrent.py
@@ -20,34 +20,34 @@ class MakeTorrentTestCase(unittest.TestCase):
def test_save_multifile(self):
# Create a temporary folder for torrent creation
tmp_path = tempfile.mkdtemp()
- with open(os.path.join(tmp_path, "file_A"), "wb") as _file:
- _file.write("a" * (312 * 1024))
- with open(os.path.join(tmp_path, "file_B"), "wb") as _file:
- _file.write("b" * (2354 * 1024))
- with open(os.path.join(tmp_path, "file_C"), "wb") as _file:
- _file.write("c" * (11 * 1024))
+ with open(os.path.join(tmp_path, 'file_A'), 'wb') as _file:
+ _file.write('a' * (312 * 1024))
+ with open(os.path.join(tmp_path, 'file_B'), 'wb') as _file:
+ _file.write('b' * (2354 * 1024))
+ with open(os.path.join(tmp_path, 'file_C'), 'wb') as _file:
+ _file.write('c' * (11 * 1024))
t = maketorrent.TorrentMetadata()
t.data_path = tmp_path
- tmp_fd, tmp_file = tempfile.mkstemp(".torrent")
+ tmp_fd, tmp_file = tempfile.mkstemp('.torrent')
t.save(tmp_file)
check_torrent(tmp_file)
- os.remove(os.path.join(tmp_path, "file_A"))
- os.remove(os.path.join(tmp_path, "file_B"))
- os.remove(os.path.join(tmp_path, "file_C"))
+ os.remove(os.path.join(tmp_path, 'file_A'))
+ os.remove(os.path.join(tmp_path, 'file_B'))
+ os.remove(os.path.join(tmp_path, 'file_C'))
os.rmdir(tmp_path)
os.close(tmp_fd)
os.remove(tmp_file)
def test_save_singlefile(self):
- tmp_data = tempfile.mkstemp("testdata")[1]
- with open(tmp_data, "wb") as _file:
- _file.write("a" * (2314 * 1024))
+ tmp_data = tempfile.mkstemp('testdata')[1]
+ with open(tmp_data, 'wb') as _file:
+ _file.write('a' * (2314 * 1024))
t = maketorrent.TorrentMetadata()
t.data_path = tmp_data
- tmp_fd, tmp_file = tempfile.mkstemp(".torrent")
+ tmp_fd, tmp_file = tempfile.mkstemp('.torrent')
t.save(tmp_file)
check_torrent(tmp_file)
@@ -59,24 +59,24 @@ class MakeTorrentTestCase(unittest.TestCase):
def test_save_multifile_padded(self):
# Create a temporary folder for torrent creation
tmp_path = tempfile.mkdtemp()
- with open(os.path.join(tmp_path, "file_A"), "wb") as _file:
- _file.write("a" * (312 * 1024))
- with open(os.path.join(tmp_path, "file_B"), "wb") as _file:
- _file.write("b" * (2354 * 1024))
- with open(os.path.join(tmp_path, "file_C"), "wb") as _file:
- _file.write("c" * (11 * 1024))
+ with open(os.path.join(tmp_path, 'file_A'), 'wb') as _file:
+ _file.write('a' * (312 * 1024))
+ with open(os.path.join(tmp_path, 'file_B'), 'wb') as _file:
+ _file.write('b' * (2354 * 1024))
+ with open(os.path.join(tmp_path, 'file_C'), 'wb') as _file:
+ _file.write('c' * (11 * 1024))
t = maketorrent.TorrentMetadata()
t.data_path = tmp_path
t.pad_files = True
- tmp_fd, tmp_file = tempfile.mkstemp(".torrent")
+ tmp_fd, tmp_file = tempfile.mkstemp('.torrent')
t.save(tmp_file)
check_torrent(tmp_file)
- os.remove(os.path.join(tmp_path, "file_A"))
- os.remove(os.path.join(tmp_path, "file_B"))
- os.remove(os.path.join(tmp_path, "file_C"))
+ os.remove(os.path.join(tmp_path, 'file_A'))
+ os.remove(os.path.join(tmp_path, 'file_B'))
+ os.remove(os.path.join(tmp_path, 'file_C'))
os.rmdir(tmp_path)
os.close(tmp_fd)
os.remove(tmp_file)
diff --git a/deluge/tests/test_plugin_metadata.py b/deluge/tests/test_plugin_metadata.py
index ba7f1d0a0..c60ab6cf9 100644
--- a/deluge/tests/test_plugin_metadata.py
+++ b/deluge/tests/test_plugin_metadata.py
@@ -19,12 +19,12 @@ class PluginManagerBaseTestCase(BaseTestCase):
common.set_tmp_config_dir()
def test_get_plugin_info(self):
- pm = PluginManagerBase("core.conf", "deluge.plugin.core")
+ pm = PluginManagerBase('core.conf', 'deluge.plugin.core')
for p in pm.get_available_plugins():
for key, value in pm.get_plugin_info(p).items():
- self.assertTrue(isinstance("%s: %s" % (key, value), basestring))
+ self.assertTrue(isinstance('%s: %s' % (key, value), basestring))
def test_get_plugin_info_invalid_name(self):
- pm = PluginManagerBase("core.conf", "deluge.plugin.core")
- for key, value in pm.get_plugin_info("random").items():
- self.assertEqual(value, "not available")
+ pm = PluginManagerBase('core.conf', 'deluge.plugin.core')
+ for key, value in pm.get_plugin_info('random').items():
+ self.assertEqual(value, 'not available')
diff --git a/deluge/tests/test_rpcserver.py b/deluge/tests/test_rpcserver.py
index 21aa83e93..81acf245e 100644
--- a/deluge/tests/test_rpcserver.py
+++ b/deluge/tests/test_rpcserver.py
@@ -17,7 +17,7 @@ from deluge.ui.common import get_localhost_auth
from .basetest import BaseTestCase
-setup_logger("none")
+setup_logger('none')
class DelugeRPCProtocolTester(DelugeRPCProtocol):
@@ -34,14 +34,14 @@ class RPCServerTestCase(BaseTestCase):
self.rpcserver = RPCServer(listen=False)
self.rpcserver.factory.protocol = DelugeRPCProtocolTester
self.factory = self.rpcserver.factory
- self.session_id = "0"
+ self.session_id = '0'
self.request_id = 11
self.protocol = self.rpcserver.factory.protocol()
self.protocol.factory = self.factory
self.protocol.transport = self.protocol
self.factory.session_protocols[self.session_id] = self.protocol
self.factory.authorized_sessions[self.session_id] = None
- self.factory.interested_events[self.session_id] = ["TorrentFolderRenamedEvent"]
+ self.factory.interested_events[self.session_id] = ['TorrentFolderRenamedEvent']
self.protocol.sessionno = self.session_id
return component.start()
@@ -51,18 +51,18 @@ class RPCServerTestCase(BaseTestCase):
return component.shutdown().addCallback(on_shutdown)
def test_emit_event_for_session_id(self):
- torrent_id = "12"
+ torrent_id = '12'
from deluge.event import TorrentFolderRenamedEvent
- data = [torrent_id, "new name", "old name"]
+ data = [torrent_id, 'new name', 'old name']
e = TorrentFolderRenamedEvent(*data)
self.rpcserver.emit_event_for_session_id(self.session_id, e)
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_EVENT, str(msg))
- self.assertEquals(msg[1], "TorrentFolderRenamedEvent", str(msg))
+ self.assertEquals(msg[1], 'TorrentFolderRenamedEvent', str(msg))
self.assertEquals(msg[2], data, str(msg))
def test_invalid_client_login(self):
- self.protocol.dispatch(self.request_id, "daemon.login", [1], {})
+ self.protocol.dispatch(self.request_id, 'daemon.login', [1], {})
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_ERROR)
self.assertEquals(msg[1], self.request_id)
@@ -70,7 +70,7 @@ class RPCServerTestCase(BaseTestCase):
def test_valid_client_login(self):
self.authmanager = AuthManager()
auth = get_localhost_auth()
- self.protocol.dispatch(self.request_id, "daemon.login", auth, {"client_version": "Test"})
+ self.protocol.dispatch(self.request_id, 'daemon.login', auth, {'client_version': 'Test'})
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_RESPONSE, str(msg))
self.assertEquals(msg[1], self.request_id, str(msg))
@@ -81,25 +81,25 @@ class RPCServerTestCase(BaseTestCase):
self.protocol.transport = None # This should cause AttributeError
self.authmanager = AuthManager()
auth = get_localhost_auth()
- self.protocol.dispatch(self.request_id, "daemon.login", auth, {"client_version": "Test"})
+ self.protocol.dispatch(self.request_id, 'daemon.login', auth, {'client_version': 'Test'})
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_ERROR)
self.assertEquals(msg[1], self.request_id)
- self.assertEquals(msg[2], "WrappedException")
- self.assertEquals(msg[3][1], "AttributeError")
+ self.assertEquals(msg[2], 'WrappedException')
+ self.assertEquals(msg[3][1], 'AttributeError')
def test_client_invalid_method_call(self):
self.authmanager = AuthManager()
auth = get_localhost_auth()
- self.protocol.dispatch(self.request_id, "invalid_function", auth, {})
+ self.protocol.dispatch(self.request_id, 'invalid_function', auth, {})
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_ERROR)
self.assertEquals(msg[1], self.request_id)
- self.assertEquals(msg[2], "WrappedException")
- self.assertEquals(msg[3][1], "AttributeError")
+ self.assertEquals(msg[2], 'WrappedException')
+ self.assertEquals(msg[3][1], 'AttributeError')
def test_daemon_info(self):
- self.protocol.dispatch(self.request_id, "daemon.info", [], {})
+ self.protocol.dispatch(self.request_id, 'daemon.info', [], {})
msg = self.protocol.messages.pop()
self.assertEquals(msg[0], rpcserver.RPC_RESPONSE, str(msg))
self.assertEquals(msg[1], self.request_id, str(msg))
diff --git a/deluge/tests/test_sessionproxy.py b/deluge/tests/test_sessionproxy.py
index 94f6ab786..d8bd393ae 100644
--- a/deluge/tests/test_sessionproxy.py
+++ b/deluge/tests/test_sessionproxy.py
@@ -23,9 +23,9 @@ class Core(object):
def reset(self):
self.torrents = {}
- self.torrents["a"] = {"key1": 1, "key2": 2, "key3": 3}
- self.torrents["b"] = {"key1": 1, "key2": 2, "key3": 3}
- self.torrents["c"] = {"key1": 1, "key2": 2, "key3": 3}
+ self.torrents['a'] = {'key1': 1, 'key2': 2, 'key3': 3}
+ self.torrents['b'] = {'key1': 1, 'key2': 2, 'key3': 3}
+ self.torrents['c'] = {'key1': 1, 'key2': 2, 'key3': 3}
self.prev_status = {}
def get_session_state(self):
@@ -55,12 +55,12 @@ class Core(object):
def get_torrents_status(self, filter_dict, keys, diff=False):
if not filter_dict:
- filter_dict["id"] = self.torrents.keys()
+ filter_dict['id'] = self.torrents.keys()
if not keys:
- keys = self.torrents["a"].keys()
+ keys = self.torrents['a'].keys()
if not diff:
- if "id" in filter_dict:
- torrents = filter_dict["id"]
+ if 'id' in filter_dict:
+ torrents = filter_dict['id']
ret = {}
for torrent in torrents:
ret[torrent] = {}
@@ -68,8 +68,8 @@ class Core(object):
ret[torrent][key] = self.torrents[torrent][key]
return succeed(ret)
else:
- if "id" in filter_dict:
- torrents = filter_dict["id"]
+ if 'id' in filter_dict:
+ torrents = filter_dict['id']
ret = {}
for torrent in torrents:
ret[torrent] = {}
@@ -101,8 +101,8 @@ class SessionProxyTestCase(BaseTestCase):
def set_up(self):
self.clock = Clock()
- self.patch(deluge.ui.sessionproxy, "time", self.clock.seconds)
- self.patch(deluge.ui.sessionproxy, "client", client)
+ self.patch(deluge.ui.sessionproxy, 'time', self.clock.seconds)
+ self.patch(deluge.ui.sessionproxy, 'client', client)
self.sp = deluge.ui.sessionproxy.SessionProxy()
client.core.reset()
d = self.sp.start()
@@ -119,38 +119,38 @@ class SessionProxyTestCase(BaseTestCase):
return component.deregister(self.sp)
def test_startup(self):
- self.assertEquals(client.core.torrents["a"], self.sp.torrents["a"][1])
+ self.assertEquals(client.core.torrents['a'], self.sp.torrents['a'][1])
def test_get_torrent_status_no_change(self):
- d = self.sp.get_torrent_status("a", [])
- d.addCallback(self.assertEquals, client.core.torrents["a"])
+ d = self.sp.get_torrent_status('a', [])
+ d.addCallback(self.assertEquals, client.core.torrents['a'])
return d
def test_get_torrent_status_change_with_cache(self):
- client.core.torrents["a"]["key1"] = 2
- d = self.sp.get_torrent_status("a", ["key1"])
- d.addCallback(self.assertEquals, {"key1": 1})
+ client.core.torrents['a']['key1'] = 2
+ d = self.sp.get_torrent_status('a', ['key1'])
+ d.addCallback(self.assertEquals, {'key1': 1})
return d
def test_get_torrent_status_change_without_cache(self):
- client.core.torrents["a"]["key1"] = 2
+ client.core.torrents['a']['key1'] = 2
self.clock.advance(self.sp.cache_time + 0.1)
- d = self.sp.get_torrent_status("a", [])
- d.addCallback(self.assertEquals, client.core.torrents["a"])
+ d = self.sp.get_torrent_status('a', [])
+ d.addCallback(self.assertEquals, client.core.torrents['a'])
return d
def test_get_torrent_status_key_not_updated(self):
self.clock.advance(self.sp.cache_time + 0.1)
- self.sp.get_torrent_status("a", ["key1"])
- client.core.torrents["a"]["key2"] = 99
- d = self.sp.get_torrent_status("a", ["key2"])
- d.addCallback(self.assertEquals, {"key2": 99})
+ self.sp.get_torrent_status('a', ['key1'])
+ client.core.torrents['a']['key2'] = 99
+ d = self.sp.get_torrent_status('a', ['key2'])
+ d.addCallback(self.assertEquals, {'key2': 99})
return d
def test_get_torrents_status_key_not_updated(self):
self.clock.advance(self.sp.cache_time + 0.1)
- self.sp.get_torrents_status({"id": ["a"]}, ["key1"])
- client.core.torrents["a"]["key2"] = 99
- d = self.sp.get_torrents_status({"id": ["a"]}, ["key2"])
- d.addCallback(self.assertEquals, {"a": {"key2": 99}})
+ self.sp.get_torrents_status({'id': ['a']}, ['key1'])
+ client.core.torrents['a']['key2'] = 99
+ d = self.sp.get_torrents_status({'id': ['a']}, ['key2'])
+ d.addCallback(self.assertEquals, {'a': {'key2': 99}})
return d
diff --git a/deluge/tests/test_torrent.py b/deluge/tests/test_torrent.py
index 7d864c067..cc893fd56 100644
--- a/deluge/tests/test_torrent.py
+++ b/deluge/tests/test_torrent.py
@@ -23,7 +23,7 @@ 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,
+ core_config = deluge.config.Config('core.conf', defaults=deluge.core.preferencesmanager.DEFAULT_PREFS,
config_dir=config_dir)
core_config.save()
@@ -44,7 +44,7 @@ class TorrentTestCase(BaseTestCase):
if i % 100 == 0:
print(tmp)
tmp = ''
- tmp += "%s" % p
+ tmp += '%s' % p
print(tmp)
def assert_state(self, torrent, state):
@@ -55,19 +55,19 @@ class TorrentTestCase(BaseTestCase):
filename = common.get_test_data_file(filename)
with open(filename, 'rb') as _file:
info = lt.torrent_info(lt.bdecode(_file.read()))
- atp = {"ti": info}
- atp["save_path"] = os.getcwd()
- atp["storage_mode"] = lt.storage_mode_t.storage_mode_sparse
- atp["add_paused"] = False
- atp["auto_managed"] = True
- atp["duplicate_is_error"] = True
+ atp = {'ti': info}
+ atp['save_path'] = os.getcwd()
+ atp['storage_mode'] = lt.storage_mode_t.storage_mode_sparse
+ atp['add_paused'] = False
+ atp['auto_managed'] = True
+ atp['duplicate_is_error'] = True
return atp
def test_set_prioritize_first_last_pieces(self):
piece_indexes = [(0, 1), (0, 1), (0, 1), (0, 1), (0, 2), (50, 52),
(51, 53), (110, 112), (111, 114), (200, 203),
(202, 203), (212, 213), (212, 218), (457, 463)]
- self.run_test_set_prioritize_first_last_pieces("dir_with_6_files.torrent", piece_indexes)
+ 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):
atp = self.get_torrent_atp(torrent_file)
@@ -99,7 +99,7 @@ class TorrentTestCase(BaseTestCase):
# self.print_priority_list(priorities)
def test_set_prioritize_first_last_pieces_false(self):
- atp = self.get_torrent_atp("dir_with_6_files.torrent")
+ atp = self.get_torrent_atp('dir_with_6_files.torrent')
handle = self.session.add_torrent(atp)
self.torrent = Torrent(handle, {})
# First set some pieces prioritized
@@ -116,36 +116,36 @@ class TorrentTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_torrent_error_data_missing(self):
- options = {"seed_mode": True}
- filename = common.get_test_data_file("test_torrent.file.torrent")
+ options = {'seed_mode': True}
+ filename = common.get_test_data_file('test_torrent.file.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
torrent = self.core.torrentmanager.torrents[torrent_id]
- self.assert_state(torrent, "Seeding")
+ self.assert_state(torrent, 'Seeding')
# Force an error by reading (non-existant) piece from disk
torrent.handle.read_piece(0)
time.sleep(0.2) # Delay to wait for alert from lt
- self.assert_state(torrent, "Error")
+ self.assert_state(torrent, 'Error')
@defer.inlineCallbacks
def test_torrent_error_resume_original_state(self):
- options = {"seed_mode": True, "add_paused": True}
- filename = common.get_test_data_file("test_torrent.file.torrent")
+ options = {'seed_mode': True, 'add_paused': True}
+ filename = common.get_test_data_file('test_torrent.file.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
torrent = self.core.torrentmanager.torrents[torrent_id]
- orig_state = "Paused"
+ orig_state = 'Paused'
self.assert_state(torrent, orig_state)
# Force an error by reading (non-existant) piece from disk
torrent.handle.read_piece(0)
time.sleep(0.2) # Delay to wait for alert from lt
- self.assert_state(torrent, "Error")
+ self.assert_state(torrent, 'Error')
# Clear error and verify returned to original state
torrent.force_recheck()
@@ -178,7 +178,7 @@ class TorrentTestCase(BaseTestCase):
is_finished=True,
)
- filename = common.get_test_data_file("test_torrent.file.torrent")
+ filename = common.get_test_data_file('test_torrent.file.torrent')
with open(filename) as _file:
filedump = _file.read()
torrent_id = yield self.core.torrentmanager.add(state=torrent_state, filedump=filedump,
@@ -186,7 +186,7 @@ class TorrentTestCase(BaseTestCase):
torrent = self.core.torrentmanager.torrents[torrent_id]
def assert_resume_data():
- self.assert_state(torrent, "Error")
+ self.assert_state(torrent, 'Error')
tm_resume_data = lt.bdecode(self.core.torrentmanager.resume_data[torrent.torrent_id])
self.assertEquals(tm_resume_data, resume_data)
diff --git a/deluge/tests/test_torrentmanager.py b/deluge/tests/test_torrentmanager.py
index b1c90fdbd..3e3be0246 100644
--- a/deluge/tests/test_torrentmanager.py
+++ b/deluge/tests/test_torrentmanager.py
@@ -12,7 +12,7 @@ from deluge.error import InvalidTorrentError
from . import common
from .basetest import BaseTestCase
-warnings.filterwarnings("ignore", category=RuntimeWarning)
+warnings.filterwarnings('ignore', category=RuntimeWarning)
warnings.resetwarnings()
@@ -29,7 +29,7 @@ class TorrentmanagerTestCase(BaseTestCase):
@defer.inlineCallbacks
def test_remove_torrent(self):
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
with open(filename) as _file:
filedump = base64.encodestring(_file.read())
torrent_id = yield self.core.add_torrent_file(filename, filedump, {})
@@ -41,4 +41,4 @@ class TorrentmanagerTestCase(BaseTestCase):
common.todo_test(self)
def test_remove_invalid_torrent(self):
- self.assertRaises(InvalidTorrentError, self.core.torrentmanager.remove, "torrentidthatdoesntexist")
+ self.assertRaises(InvalidTorrentError, self.core.torrentmanager.remove, 'torrentidthatdoesntexist')
diff --git a/deluge/tests/test_torrentview.py b/deluge/tests/test_torrentview.py
index 5579a66ad..0bee72802 100644
--- a/deluge/tests/test_torrentview.py
+++ b/deluge/tests/test_torrentview.py
@@ -13,7 +13,7 @@ try:
from gobject import TYPE_UINT64
except ImportError as err:
libs_available = False
- TYPE_UINT64 = "Whatever"
+ TYPE_UINT64 = 'Whatever'
import traceback
traceback.print_exc()
else:
@@ -53,11 +53,11 @@ class TorrentviewTestCase(BaseTestCase):
def set_up(self):
if libs_available is False:
- raise unittest.SkipTest("GTKUI dependencies not available")
+ raise unittest.SkipTest('GTKUI dependencies not available')
common.set_tmp_config_dir()
# MainWindow loads this config file, so lets make sure it contains the defaults
- ConfigManager("gtkui.conf", defaults=DEFAULT_PREFS)
+ ConfigManager('gtkui.conf', defaults=DEFAULT_PREFS)
self.mainwindow = MainWindow()
self.torrentview = TorrentView()
self.torrentdetails = TorrentDetails()
@@ -70,13 +70,13 @@ class TorrentviewTestCase(BaseTestCase):
self.assertEquals(self.torrentview.column_index, TorrentviewTestCase.default_column_index)
self.assertEquals(self.torrentview.liststore_columns, TorrentviewTestCase.default_liststore_columns)
- self.assertEquals(self.torrentview.columns["Download Folder"].column_indices, [29])
+ self.assertEquals(self.torrentview.columns['Download Folder'].column_indices, [29])
def test_add_column(self):
# Add a text column
- test_col = "Test column"
- self.torrentview.add_text_column(test_col, status_field=["label"])
+ test_col = 'Test column'
+ self.torrentview.add_text_column(test_col, status_field=['label'])
self.assertEquals(len(self.torrentview.liststore_columns),
len(TorrentviewTestCase.default_liststore_columns) + 1)
self.assertEquals(len(self.torrentview.column_index),
@@ -87,12 +87,12 @@ class TorrentviewTestCase(BaseTestCase):
def test_add_columns(self):
# Add a text column
- test_col = "Test column"
- self.torrentview.add_text_column(test_col, status_field=["label"])
+ test_col = 'Test column'
+ self.torrentview.add_text_column(test_col, status_field=['label'])
# Add a second text column
- test_col2 = "Test column2"
- self.torrentview.add_text_column(test_col2, status_field=["label2"])
+ test_col2 = 'Test column2'
+ self.torrentview.add_text_column(test_col2, status_field=['label2'])
self.assertEquals(len(self.torrentview.liststore_columns),
len(TorrentviewTestCase.default_liststore_columns) + 2)
@@ -109,8 +109,8 @@ class TorrentviewTestCase(BaseTestCase):
def test_remove_column(self):
# Add and remove text column
- test_col = "Test column"
- self.torrentview.add_text_column(test_col, status_field=["label"])
+ test_col = 'Test column'
+ self.torrentview.add_text_column(test_col, status_field=['label'])
self.torrentview.remove_column(test_col)
self.assertEquals(len(self.torrentview.liststore_columns), len(TorrentviewTestCase.default_liststore_columns))
@@ -121,10 +121,10 @@ class TorrentviewTestCase(BaseTestCase):
def test_remove_columns(self):
# Add two columns
- test_col = "Test column"
- self.torrentview.add_text_column(test_col, status_field=["label"])
- test_col2 = "Test column2"
- self.torrentview.add_text_column(test_col2, status_field=["label2"])
+ test_col = 'Test column'
+ self.torrentview.add_text_column(test_col, status_field=['label'])
+ test_col2 = 'Test column2'
+ self.torrentview.add_text_column(test_col2, status_field=['label2'])
# Remove test_col
self.torrentview.remove_column(test_col)
@@ -145,8 +145,8 @@ class TorrentviewTestCase(BaseTestCase):
def test_add_remove_column_multiple_types(self):
# 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])
+ test_col3 = 'Test column3'
+ self.torrentview.add_progress_column(test_col3, status_field=['progress', 'label3'], col_types=[float, str])
self.assertEquals(len(self.torrentview.liststore_columns),
len(TorrentviewTestCase.default_liststore_columns) + 2)
self.assertEquals(len(self.torrentview.column_index),
diff --git a/deluge/tests/test_tracker_icons.py b/deluge/tests/test_tracker_icons.py
index ac76a1dcb..90ae875c5 100644
--- a/deluge/tests/test_tracker_icons.py
+++ b/deluge/tests/test_tracker_icons.py
@@ -23,8 +23,8 @@ class TrackerIconsTestCase(BaseTestCase):
def test_get_deluge_png(self):
# Deluge has a png favicon link
- icon = TrackerIcon(common.get_test_data_file("deluge.png"))
- d = self.icons.fetch("deluge-torrent.org")
+ icon = TrackerIcon(common.get_test_data_file('deluge.png'))
+ d = self.icons.fetch('deluge-torrent.org')
d.addCallback(self.assertNotIdentical, None)
d.addCallback(self.assertEquals, icon)
return d
@@ -32,29 +32,29 @@ class TrackerIconsTestCase(BaseTestCase):
def test_get_google_ico(self):
# Google doesn't have any icon links
# So instead we'll grab its favicon.ico
- icon = TrackerIcon(common.get_test_data_file("google.ico"))
- d = self.icons.fetch("www.google.com")
+ icon = TrackerIcon(common.get_test_data_file('google.ico'))
+ d = self.icons.fetch('www.google.com')
d.addCallback(self.assertNotIdentical, None)
d.addCallback(self.assertEquals, icon)
return d
def test_get_google_ico_with_redirect(self):
# google.com redirects to www.google.com
- icon = TrackerIcon(common.get_test_data_file("google.ico"))
- d = self.icons.fetch("google.com")
+ icon = TrackerIcon(common.get_test_data_file('google.ico'))
+ d = self.icons.fetch('google.com')
d.addCallback(self.assertNotIdentical, None)
d.addCallback(self.assertEquals, icon)
return d
def test_get_ubuntu_ico(self):
# ubuntu.com has inline css which causes HTMLParser issues
- icon = TrackerIcon(common.get_test_data_file("ubuntu.png"))
- d = self.icons.fetch("www.ubuntu.com")
+ icon = TrackerIcon(common.get_test_data_file('ubuntu.png'))
+ d = self.icons.fetch('www.ubuntu.com')
d.addCallback(self.assertNotIdentical, None)
d.addCallback(self.assertEquals, icon)
return d
def test_get_empty_string_tracker(self):
- d = self.icons.fetch("")
+ d = self.icons.fetch('')
d.addCallback(self.assertIdentical, None)
return d
diff --git a/deluge/tests/test_transfer.py b/deluge/tests/test_transfer.py
index f91c118b9..0dca6f86c 100644
--- a/deluge/tests/test_transfer.py
+++ b/deluge/tests/test_transfer.py
@@ -17,7 +17,7 @@ import deluge.log
import deluge.rencode as rencode
from deluge.transfer import DelugeTransferProtocol
-deluge.log.setup_logger("none")
+deluge.log.setup_logger('none')
class TransferTestClass(DelugeTransferProtocol):
@@ -44,7 +44,7 @@ class TransferTestClass(DelugeTransferProtocol):
self.messages_in.append(message)
def get_messages_out_joined(self):
- return b"".join(self.messages_out)
+ return b''.join(self.messages_out)
def get_messages_in(self):
return self.messages_in
@@ -57,11 +57,11 @@ class TransferTestClass(DelugeTransferProtocol):
"""
import zlib
- print("\n=== New Data Received ===\nBytes received:", len(data))
+ print('\n=== New Data Received ===\nBytes received:', len(data))
if self._buffer:
# We have some data from the last dataReceived() so lets prepend it
- print("Current buffer:", len(self._buffer) if self._buffer else "0")
+ print('Current buffer:', len(self._buffer) if self._buffer else '0')
data = self._buffer + data
self._buffer = None
@@ -69,10 +69,10 @@ class TransferTestClass(DelugeTransferProtocol):
self._bytes_received += len(data)
while data:
- print("\n-- Handle packet data --")
+ print('\n-- Handle packet data --')
- print("Bytes received:", self._bytes_received)
- print("Current data:", len(data))
+ print('Bytes received:', self._bytes_received)
+ print('Current data:', len(data))
if self._message_length == 0:
# handle_new_message uses _buffer so set data to _buffer.
@@ -81,21 +81,21 @@ class TransferTestClass(DelugeTransferProtocol):
data = self._buffer
self._buffer = None
self.packet_count = 1
- print("New message of length:", self._message_length)
+ print('New message of length:', self._message_length)
dobj = zlib.decompressobj()
try:
request = rencode.loads(dobj.decompress(data))
- print("Successfully loaded message", end=' ')
- print(" - Buffer length: %d, data length: %d, unused length: %d" %
+ print('Successfully loaded message', end=' ')
+ print(' - Buffer length: %d, data length: %d, unused length: %d' %
(len(data), len(data) - len(dobj.unused_data), len(dobj.unused_data)))
- print("Packet count:", self.packet_count)
+ print('Packet count:', self.packet_count)
except Exception as ex:
# log.debug("Received possible invalid message (%r): %s", data, e)
# This could be cut-off data, so we'll save this in the buffer
# and try to prepend it on the next dataReceived()
self._buffer = data
- print("Failed to load buffer (size %d): %s" % (len(self._buffer), str(ex)))
+ print('Failed to load buffer (size %d): %s' % (len(self._buffer), str(ex)))
return
else:
data = dobj.unused_data
@@ -117,19 +117,19 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
"""
self.transfer = TransferTestClass()
- self.msg1 = (0, 1, {"key_int": 1242429423}, {"key_str": "some string"}, {"key_bool": True})
- self.msg2 = (2, 3, {"key_float": 12424.29423},
- {"key_unicode": u"some string"},
- {"key_dict_with_tuple": {"key_tuple": (1, 2, 3)}},
- {"keylist": [4, "5", 6.7]})
+ self.msg1 = (0, 1, {'key_int': 1242429423}, {'key_str': 'some string'}, {'key_bool': True})
+ self.msg2 = (2, 3, {'key_float': 12424.29423},
+ {'key_unicode': u'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"
+ self.msg1_expected_compressed_base64 = 'RAAAADF4nDvKwJjenp1aGZ+ZV+Lgxfv9PYRXXFLU'\
+ 'XZyfm6oAZGTmpad3gAST8vNznAEAJhSQ'
- self.msg2_expected_compressed_base64 = "RAAAAF14nDvGxJzemZ1aGZ+Wk59Y4uTmpKib3g3i"\
- "l+ZlJuenpHYX5+emKhSXFGXmpadPBkmkZCaXxJdn"\
- "lmTEl5QW5KRCdIOZhxmBhrUDuTmZxSWHWRpNnRyu"\
- "paUBAHYlJxI="
+ self.msg2_expected_compressed_base64 = 'RAAAAF14nDvGxJzemZ1aGZ+Wk59Y4uTmpKib3g3i'\
+ 'l+ZlJuenpHYX5+emKhSXFGXmpadPBkmkZCaXxJdn'\
+ 'lmTEl5QW5KRCdIOZhxmBhrUDuTmZxSWHWRpNnRyu'\
+ 'paUBAHYlJxI='
def test_send_one_message(self):
"""
@@ -239,13 +239,13 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
print()
- print("Msg1 size:", len(base64.b64decode(self.msg1_expected_compressed_base64)) - 4)
- print("Msg2 size:", len(base64.b64decode(self.msg2_expected_compressed_base64)) - 4)
- print("Msg3 size:", len(base64.b64decode(self.msg1_expected_compressed_base64)) - 4)
+ print('Msg1 size:', len(base64.b64decode(self.msg1_expected_compressed_base64)) - 4)
+ print('Msg2 size:', len(base64.b64decode(self.msg2_expected_compressed_base64)) - 4)
+ print('Msg3 size:', len(base64.b64decode(self.msg1_expected_compressed_base64)) - 4)
- print("one_message_byte_count:", one_message_byte_count)
- print("two_messages_byte_count:", two_messages_byte_count)
- print("three_messages_byte_count:", three_messages_byte_count)
+ print('one_message_byte_count:', one_message_byte_count)
+ print('two_messages_byte_count:', two_messages_byte_count)
+ print('three_messages_byte_count:', three_messages_byte_count)
for d in self.receive_parts_helper(msg_bytes, packet_size, self.transfer.data_received_old_protocol):
bytes_received = self.transfer.get_bytes_recv()
@@ -260,7 +260,7 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
expected_msgs_received_count = 0
# Verify that the expected number of complete messages has arrived
if expected_msgs_received_count != len(self.transfer.get_messages_in()):
- print("Expected number of messages received is %d, but %d have been received." %
+ print('Expected number of messages received is %d, but %d have been received.' %
(expected_msgs_received_count, len(self.transfer.get_messages_in())))
# Get the data as received by DelugeTransferProtocol
diff --git a/deluge/tests/test_ui_common.py b/deluge/tests/test_ui_common.py
index a2c98c298..eff972527 100644
--- a/deluge/tests/test_ui_common.py
+++ b/deluge/tests/test_ui_common.py
@@ -22,20 +22,20 @@ class UICommonTestCase(unittest.TestCase):
pass
def test_utf8_encoded_paths(self):
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
ti = TorrentInfo(filename)
- self.assertTrue("azcvsupdater_2.6.2.jar" in ti.files_tree)
+ self.assertTrue('azcvsupdater_2.6.2.jar' in ti.files_tree)
def test_utf8_encoded_paths2(self):
- filename = common.get_test_data_file("unicode_filenames.torrent")
+ filename = common.get_test_data_file('unicode_filenames.torrent')
ti = TorrentInfo(filename)
- files = ti.files_tree["unicode_filenames"]
- self.assertTrue("\xe3\x83\x86\xe3\x82\xaf\xe3\x82\xb9\xe3\x83\xbb\xe3\x83"
- "\x86\xe3\x82\xaf\xe3\x82\xb5\xe3\x83\xb3.mkv" in files)
- self.assertTrue("\xd0\x9c\xd0\xb8\xd1\x85\xd0\xb0\xd0\xb8\xd0\xbb \xd0\x93"
- "\xd0\xbe\xd1\x80\xd0\xb1\xd0\xb0\xd1\x87\xd1\x91\xd0\xb2.mkv" in files)
+ files = ti.files_tree['unicode_filenames']
+ self.assertTrue('\xe3\x83\x86\xe3\x82\xaf\xe3\x82\xb9\xe3\x83\xbb\xe3\x83'
+ '\x86\xe3\x82\xaf\xe3\x82\xb5\xe3\x83\xb3.mkv' in files)
+ self.assertTrue('\xd0\x9c\xd0\xb8\xd1\x85\xd0\xb0\xd0\xb8\xd0\xbb \xd0\x93'
+ '\xd0\xbe\xd1\x80\xd0\xb1\xd0\xb0\xd1\x87\xd1\x91\xd0\xb2.mkv' in files)
self.assertTrue("Alisher ibn G'iyosiddin Navoiy.mkv" in files)
- self.assertTrue("Ascii title.mkv" in files)
- self.assertTrue("\xe0\xa6\xb8\xe0\xa7\x81\xe0\xa6\x95\xe0\xa7\x81\xe0\xa6"
- "\xae\xe0\xa6\xbe\xe0\xa6\xb0 \xe0\xa6\xb0\xe0\xa6\xbe\xe0\xa7\x9f.mkv" in files)
+ self.assertTrue('Ascii title.mkv' in files)
+ self.assertTrue('\xe0\xa6\xb8\xe0\xa7\x81\xe0\xa6\x95\xe0\xa7\x81\xe0\xa6'
+ '\xae\xe0\xa6\xbe\xe0\xa6\xb0 \xe0\xa6\xb0\xe0\xa6\xbe\xe0\xa7\x9f.mkv' in files)
diff --git a/deluge/tests/test_ui_console_fields.py b/deluge/tests/test_ui_console_fields.py
index 72680ca87..53520060f 100644
--- a/deluge/tests/test_ui_console_fields.py
+++ b/deluge/tests/test_ui_console_fields.py
@@ -25,5 +25,5 @@ class UICommonTestCase(unittest.TestCase):
self._cursor_row = r
self._cursor_col = c
- t = TextInput(self.parent, "name", "message", move_func, 20, "/text/field/file/path", complete=False)
+ t = TextInput(self.parent, 'name', 'message', move_func, 20, '/text/field/file/path', complete=False)
self.assertTrue(t) # Shut flake8 up (unused variable)
diff --git a/deluge/tests/test_ui_entry.py b/deluge/tests/test_ui_entry.py
index 9b5535c85..681f9169d 100644
--- a/deluge/tests/test_ui_entry.py
+++ b/deluge/tests/test_ui_entry.py
@@ -46,11 +46,11 @@ class StringFileDescriptor(object):
def __init__(self, fd):
self.out = StringIO.StringIO()
self.fd = fd
- for a in ["encoding"]:
+ for a in ['encoding']:
setattr(self, a, getattr(sys_stdout, a))
def write(self, *data, **kwargs):
- print(*data, file=self.out, end="")
+ print(*data, file=self.out, end='')
def flush(self):
self.out.flush()
@@ -63,7 +63,7 @@ class UIBaseTestCase(object):
def set_up(self):
common.set_tmp_config_dir()
- common.setup_test_logger(level="info", prefix=self.id())
+ common.setup_test_logger(level='info', prefix=self.id())
return component.start()
def tear_down(self):
@@ -72,7 +72,7 @@ class UIBaseTestCase(object):
def exec_command(self):
if DEBUG_COMMAND:
print("Executing: '%s'\n" % sys.argv, file=sys_stdout)
- return self.var["start_cmd"]()
+ return self.var['start_cmd']()
class UIWithDaemonBaseTestCase(UIBaseTestCase, DaemonBase):
@@ -83,7 +83,7 @@ class UIWithDaemonBaseTestCase(UIBaseTestCase, DaemonBase):
def set_up(self):
d = self.common_set_up()
- common.setup_test_logger(level="info", prefix=self.id())
+ common.setup_test_logger(level='info', prefix=self.id())
d.addCallback(self.start_core)
return d
@@ -103,58 +103,58 @@ class DelugeEntryTestCase(BaseTestCase):
return component.shutdown()
def test_deluge_help(self):
- self.patch(sys, "argv", ["./deluge", "-h"])
- config = deluge.configmanager.ConfigManager("ui.conf", ui_entry.DEFAULT_PREFS)
- config.config["default_ui"] = "console"
+ self.patch(sys, 'argv', ['./deluge', '-h'])
+ config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
+ config.config['default_ui'] = 'console'
config.save()
fd = StringFileDescriptor(sys.stdout)
- self.patch(argparse._sys, "stdout", fd)
+ self.patch(argparse._sys, 'stdout', fd)
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.assertRaises(exceptions.SystemExit, ui_entry.start_ui)
- self.assertTrue("usage: deluge" in fd.out.getvalue())
- self.assertTrue("UI Options:" in fd.out.getvalue())
- self.assertTrue("* console" in fd.out.getvalue())
+ self.assertTrue('usage: deluge' in fd.out.getvalue())
+ self.assertTrue('UI Options:' in fd.out.getvalue())
+ self.assertTrue('* console' in fd.out.getvalue())
def test_start_default(self):
- self.patch(sys, "argv", ["./deluge"])
- config = deluge.configmanager.ConfigManager("ui.conf", ui_entry.DEFAULT_PREFS)
- config.config["default_ui"] = "console"
+ self.patch(sys, 'argv', ['./deluge'])
+ config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
+ config.config['default_ui'] = 'console'
config.save()
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
# Just test that no exception is raised
ui_entry.start_ui()
def test_start_with_log_level(self):
_level = []
- def setup_logger(level="error", filename=None, filemode="w", logrotate=None, output_stream=sys.stdout):
+ def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
_level.append(level)
- self.patch(deluge.log, "setup_logger", setup_logger)
- self.patch(sys, "argv", ["./deluge", "-L", "info"])
+ self.patch(deluge.log, 'setup_logger', setup_logger)
+ self.patch(sys, 'argv', ['./deluge', '-L', 'info'])
- config = deluge.configmanager.ConfigManager("ui.conf", ui_entry.DEFAULT_PREFS)
- config.config["default_ui"] = "console"
+ config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
+ config.config['default_ui'] = 'console'
config.save()
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
# Just test that no exception is raised
ui_entry.start_ui()
- self.assertEqual(_level[0], "info")
+ self.assertEqual(_level[0], 'info')
class GtkUIBaseTestCase(UIBaseTestCase):
"""Implement all GtkUI tests here"""
def test_start_gtkui(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"])
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'])
from deluge.ui.gtkui import gtkui
- with mock.patch.object(gtkui.GtkUI, "start", autospec=True):
+ with mock.patch.object(gtkui.GtkUI, 'start', autospec=True):
self.exec_command()
@@ -165,9 +165,9 @@ class GtkUIDelugeScriptEntryTestCase(BaseTestCase, GtkUIBaseTestCase):
super(GtkUIDelugeScriptEntryTestCase, self).__init__(testname)
GtkUIBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge gtk"
- self.var["start_cmd"] = ui_entry.start_ui
- self.var["sys_arg_cmd"] = ["./deluge", "gtk"]
+ self.var['cmd_name'] = 'deluge gtk'
+ self.var['start_cmd'] = ui_entry.start_ui
+ self.var['sys_arg_cmd'] = ['./deluge', 'gtk']
def set_up(self):
return GtkUIBaseTestCase.set_up(self)
@@ -183,9 +183,9 @@ class GtkUIScriptEntryTestCase(BaseTestCase, GtkUIBaseTestCase):
super(GtkUIScriptEntryTestCase, self).__init__(testname)
GtkUIBaseTestCase.__init__(self)
from deluge.ui import gtkui
- self.var["cmd_name"] = "deluge-gtk"
- self.var["start_cmd"] = gtkui.start
- self.var["sys_arg_cmd"] = ["./deluge-gtk"]
+ self.var['cmd_name'] = 'deluge-gtk'
+ self.var['start_cmd'] = gtkui.start
+ self.var['sys_arg_cmd'] = ['./deluge-gtk']
def set_up(self):
return GtkUIBaseTestCase.set_up(self)
@@ -196,7 +196,7 @@ class GtkUIScriptEntryTestCase(BaseTestCase, GtkUIBaseTestCase):
class DelugeWebMock(DelugeWeb):
def __init__(self, *args, **kwargs):
- kwargs["daemon"] = False
+ kwargs['daemon'] = False
DelugeWeb.__init__(self, *args, **kwargs)
@@ -204,26 +204,26 @@ class WebUIBaseTestCase(UIBaseTestCase):
"""Implement all WebUI tests here"""
def test_start_webserver(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"])
- self.patch(deluge.ui.web.server, "DelugeWeb", DelugeWebMock)
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'])
+ self.patch(deluge.ui.web.server, 'DelugeWeb', DelugeWebMock)
self.exec_command()
def test_start_web_with_log_level(self):
_level = []
- def setup_logger(level="error", filename=None, filemode="w", logrotate=None, output_stream=sys.stdout):
+ def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
_level.append(level)
- self.patch(deluge.log, "setup_logger", setup_logger)
- self.patch(sys, "argv", self.var["sys_arg_cmd"] + ["-L", "info"])
+ self.patch(deluge.log, 'setup_logger', setup_logger)
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-L', 'info'])
- config = deluge.configmanager.ConfigManager("ui.conf", ui_entry.DEFAULT_PREFS)
- config.config["default_ui"] = "web"
+ config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
+ config.config['default_ui'] = 'web'
config.save()
- self.patch(deluge.ui.web.server, "DelugeWeb", DelugeWebMock)
+ self.patch(deluge.ui.web.server, 'DelugeWeb', DelugeWebMock)
self.exec_command()
- self.assertEqual(_level[0], "info")
+ self.assertEqual(_level[0], 'info')
class WebUIScriptEntryTestCase(BaseTestCase, WebUIBaseTestCase):
@@ -231,9 +231,9 @@ class WebUIScriptEntryTestCase(BaseTestCase, WebUIBaseTestCase):
def __init__(self, testname):
super(WebUIScriptEntryTestCase, self).__init__(testname)
WebUIBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge-web"
- self.var["start_cmd"] = deluge.ui.web.start
- self.var["sys_arg_cmd"] = ["./deluge-web", "--do-not-daemonize"]
+ self.var['cmd_name'] = 'deluge-web'
+ self.var['start_cmd'] = deluge.ui.web.start
+ self.var['sys_arg_cmd'] = ['./deluge-web', '--do-not-daemonize']
def set_up(self):
return WebUIBaseTestCase.set_up(self)
@@ -247,9 +247,9 @@ class WebUIDelugeScriptEntryTestCase(BaseTestCase, WebUIBaseTestCase):
def __init__(self, testname):
super(WebUIDelugeScriptEntryTestCase, self).__init__(testname)
WebUIBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge web"
- self.var["start_cmd"] = ui_entry.start_ui
- self.var["sys_arg_cmd"] = ["./deluge", "web", "--do-not-daemonize"]
+ self.var['cmd_name'] = 'deluge web'
+ self.var['start_cmd'] = ui_entry.start_ui
+ self.var['sys_arg_cmd'] = ['./deluge', 'web', '--do-not-daemonize']
def set_up(self):
return WebUIBaseTestCase.set_up(self)
@@ -262,69 +262,69 @@ class ConsoleUIBaseTestCase(UIBaseTestCase):
"""Implement Console tests that do not require a running daemon"""
def test_start_console(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"])
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'])
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.exec_command()
def test_start_console_with_log_level(self):
_level = []
- def setup_logger(level="error", filename=None, filemode="w", logrotate=None, output_stream=sys.stdout):
+ def setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=sys.stdout):
_level.append(level)
- self.patch(deluge.log, "setup_logger", setup_logger)
- self.patch(sys, "argv", self.var["sys_arg_cmd"] + ["-L", "info"])
+ self.patch(deluge.log, 'setup_logger', setup_logger)
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-L', 'info'])
- config = deluge.configmanager.ConfigManager("ui.conf", ui_entry.DEFAULT_PREFS)
- config.config["default_ui"] = "console"
+ config = deluge.configmanager.ConfigManager('ui.conf', ui_entry.DEFAULT_PREFS)
+ config.config['default_ui'] = 'console'
config.save()
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
# Just test that no exception is raised
self.exec_command()
- self.assertEqual(_level[0], "info")
+ self.assertEqual(_level[0], 'info')
def test_console_help(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"] + ["-h"])
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['-h'])
fd = StringFileDescriptor(sys.stdout)
- self.patch(argparse._sys, "stdout", fd)
+ self.patch(argparse._sys, 'stdout', fd)
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.assertRaises(exceptions.SystemExit, self.exec_command)
std_output = fd.out.getvalue()
- self.assertTrue(("usage: %s" % self.var["cmd_name"]) in std_output) # Check command name
- self.assertTrue("Common Options:" in std_output)
- self.assertTrue("Console Options:" in std_output)
- self.assertTrue("Console commands:\n The following console commands are available:" in std_output)
- self.assertTrue("The following console commands are available:" in std_output)
+ self.assertTrue(('usage: %s' % self.var['cmd_name']) in std_output) # Check command name
+ self.assertTrue('Common Options:' in std_output)
+ self.assertTrue('Console Options:' in std_output)
+ self.assertTrue('Console commands:\n The following console commands are available:' in std_output)
+ self.assertTrue('The following console commands are available:' in std_output)
def test_console_command_info(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"] + ["info"])
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['info'])
fd = StringFileDescriptor(sys.stdout)
- self.patch(argparse._sys, "stdout", fd)
+ self.patch(argparse._sys, 'stdout', fd)
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.exec_command()
def test_console_command_info_help(self):
- self.patch(sys, "argv", self.var["sys_arg_cmd"] + ["info", "-h"])
+ self.patch(sys, 'argv', self.var['sys_arg_cmd'] + ['info', '-h'])
fd = StringFileDescriptor(sys.stdout)
- self.patch(argparse._sys, "stdout", fd)
+ self.patch(argparse._sys, 'stdout', fd)
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.assertRaises(exceptions.SystemExit, self.exec_command)
std_output = fd.out.getvalue()
- self.assertTrue("usage: info" in std_output)
- self.assertTrue("Show information about the torrents" in std_output)
+ self.assertTrue('usage: info' in std_output)
+ self.assertTrue('Show information about the torrents' in std_output)
def test_console_unrecognized_arguments(self):
- self.patch(sys, "argv", ["./deluge", "--ui", "console"]) # --ui is not longer supported
+ self.patch(sys, 'argv', ['./deluge', '--ui', 'console']) # --ui is not longer supported
fd = StringFileDescriptor(sys.stdout)
- self.patch(argparse._sys, "stderr", fd)
- with mock.patch("deluge.ui.console.main.ConsoleUI"):
+ self.patch(argparse._sys, 'stderr', fd)
+ with mock.patch('deluge.ui.console.main.ConsoleUI'):
self.assertRaises(exceptions.SystemExit, self.exec_command)
- self.assertTrue("unrecognized arguments: --ui" in fd.out.getvalue())
+ self.assertTrue('unrecognized arguments: --ui' in fd.out.getvalue())
class ConsoleUIWithDaemonBaseTestCase(UIWithDaemonBaseTestCase):
@@ -332,17 +332,17 @@ class ConsoleUIWithDaemonBaseTestCase(UIWithDaemonBaseTestCase):
def set_up(self):
# Avoid calling reactor.shutdown after commands are executed by main.exec_args()
- self.patch(deluge.ui.console.cmdline.commands.quit, "reactor", common.ReactorOverride())
+ self.patch(deluge.ui.console.cmdline.commands.quit, 'reactor', common.ReactorOverride())
return UIWithDaemonBaseTestCase.set_up(self)
@defer.inlineCallbacks
def test_console_command_status(self):
username, password = deluge.ui.common.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)
- self.patch(deluge.ui.console.main, "reactor", common.ReactorOverride())
+ self.patch(sys, 'stdout', fd)
+ self.patch(deluge.ui.console.main, 'reactor', common.ReactorOverride())
yield self.exec_command()
@@ -368,8 +368,8 @@ class ConsoleScriptEntryWithDaemonTestCase(BaseTestCase, ConsoleUIWithDaemonBase
def __init__(self, testname):
super(ConsoleScriptEntryWithDaemonTestCase, self).__init__(testname)
ConsoleUIWithDaemonBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge-console"
- self.var["sys_arg_cmd"] = ["./deluge-console"]
+ self.var['cmd_name'] = 'deluge-console'
+ self.var['sys_arg_cmd'] = ['./deluge-console']
def set_up(self):
from deluge.ui.console.console import Console
@@ -377,8 +377,8 @@ class ConsoleScriptEntryWithDaemonTestCase(BaseTestCase, ConsoleUIWithDaemonBase
def start_console():
return Console().start()
- self.patch(deluge.ui.console, "start", start_console)
- self.var["start_cmd"] = deluge.ui.console.start
+ self.patch(deluge.ui.console, 'start', start_console)
+ self.var['start_cmd'] = deluge.ui.console.start
return ConsoleUIWithDaemonBaseTestCase.set_up(self)
@@ -391,9 +391,9 @@ class ConsoleScriptEntryTestCase(BaseTestCase, ConsoleUIBaseTestCase):
def __init__(self, testname):
super(ConsoleScriptEntryTestCase, self).__init__(testname)
ConsoleUIBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge-console"
- self.var["start_cmd"] = deluge.ui.console.start
- self.var["sys_arg_cmd"] = ["./deluge-console"]
+ self.var['cmd_name'] = 'deluge-console'
+ self.var['start_cmd'] = deluge.ui.console.start
+ self.var['sys_arg_cmd'] = ['./deluge-console']
def set_up(self):
return ConsoleUIBaseTestCase.set_up(self)
@@ -407,9 +407,9 @@ class ConsoleDelugeScriptEntryTestCase(BaseTestCase, ConsoleUIBaseTestCase):
def __init__(self, testname):
super(ConsoleDelugeScriptEntryTestCase, self).__init__(testname)
ConsoleUIBaseTestCase.__init__(self)
- self.var["cmd_name"] = "deluge console"
- self.var["start_cmd"] = ui_entry.start_ui
- self.var["sys_arg_cmd"] = ["./deluge", "console"]
+ self.var['cmd_name'] = 'deluge console'
+ self.var['start_cmd'] = ui_entry.start_ui
+ self.var['sys_arg_cmd'] = ['./deluge', 'console']
def set_up(self):
return ConsoleUIBaseTestCase.set_up(self)
diff --git a/deluge/tests/test_web_api.py b/deluge/tests/test_web_api.py
index dfcbce77f..147e27f10 100644
--- a/deluge/tests/test_web_api.py
+++ b/deluge/tests/test_web_api.py
@@ -27,7 +27,7 @@ common.disable_new_release_check()
class WebAPITestCase(WebServerTestBase):
def test_connect_invalid_host(self):
- d = self.deluge_web.web_api.connect("id")
+ d = self.deluge_web.web_api.connect('id')
d.addCallback(self.fail)
d.addErrback(self.assertIsInstance, Failure)
return d
@@ -60,24 +60,24 @@ class WebAPITestCase(WebServerTestBase):
def test_get_config(self):
config = self.deluge_web.web_api.get_config()
- self.assertEquals(self.webserver_listen_port, config["port"])
+ self.assertEquals(self.webserver_listen_port, config['port'])
def test_set_config(self):
config = self.deluge_web.web_api.get_config()
- config["pwd_salt"] = "new_salt"
- config["pwd_sha1"] = 'new_sha'
- config["sessions"] = {
- "233f23632af0a74748bc5dd1d8717564748877baa16420e6898e17e8aa365e6e": {
- "login": "skrot",
- "expires": 1460030877.0,
- "level": 10
+ config['pwd_salt'] = 'new_salt'
+ config['pwd_sha1'] = 'new_sha'
+ config['sessions'] = {
+ '233f23632af0a74748bc5dd1d8717564748877baa16420e6898e17e8aa365e6e': {
+ 'login': 'skrot',
+ 'expires': 1460030877.0,
+ 'level': 10
}
}
self.deluge_web.web_api.set_config(config)
- web_config = component.get("DelugeWeb").config.config
- self.assertNotEquals(config["pwd_salt"], web_config["pwd_salt"])
- self.assertNotEquals(config["pwd_sha1"], web_config["pwd_sha1"])
- self.assertNotEquals(config["sessions"], web_config["sessions"])
+ web_config = component.get('DelugeWeb').config.config
+ self.assertNotEquals(config['pwd_salt'], web_config['pwd_salt'])
+ self.assertNotEquals(config['pwd_sha1'], web_config['pwd_sha1'])
+ self.assertNotEquals(config['sessions'], web_config['sessions'])
@defer.inlineCallbacks
def get_host_status(self):
@@ -88,8 +88,8 @@ class WebAPITestCase(WebServerTestBase):
self.assertEquals(status, tuple(status))
def test_get_host(self):
- self.assertFalse(self.deluge_web.web_api._get_host("invalid_id"))
- conn = self.deluge_web.web_api.host_list["hosts"][0]
+ self.assertFalse(self.deluge_web.web_api._get_host('invalid_id'))
+ conn = self.deluge_web.web_api.host_list['hosts'][0]
self.assertEquals(self.deluge_web.web_api._get_host(conn[0]), conn)
def test_add_host(self):
@@ -103,16 +103,16 @@ class WebAPITestCase(WebServerTestBase):
# Add already existing host
ret = self.deluge_web.web_api.add_host(conn[1], conn[2], conn[3], conn[4])
- self.assertEquals(ret, (False, "Host already in the list"))
+ self.assertEquals(ret, (False, 'Host already in the list'))
# Add invalid port
- conn[2] = "bad port"
+ conn[2] = 'bad port'
ret = self.deluge_web.web_api.add_host(conn[1], conn[2], conn[3], conn[4])
- self.assertEquals(ret, (False, "Port is invalid"))
+ self.assertEquals(ret, (False, 'Port is invalid'))
def test_remove_host(self):
conn = ['connection_id', '', 0, '', '']
- self.deluge_web.web_api.host_list["hosts"].append(conn)
+ self.deluge_web.web_api.host_list['hosts'].append(conn)
self.assertEquals(self.deluge_web.web_api._get_host(conn[0]), conn)
# Remove valid host
self.assertTrue(self.deluge_web.web_api.remove_host(conn[0]))
@@ -121,35 +121,35 @@ class WebAPITestCase(WebServerTestBase):
self.assertFalse(self.deluge_web.web_api.remove_host(conn[0]))
def test_get_torrent_info(self):
- filename = common.get_test_data_file("test.torrent")
+ filename = common.get_test_data_file('test.torrent')
ret = self.deluge_web.web_api.get_torrent_info(filename)
- self.assertEquals(ret["name"], "azcvsupdater_2.6.2.jar")
- self.assertEquals(ret["info_hash"], "ab570cdd5a17ea1b61e970bb72047de141bce173")
- self.assertTrue("files_tree" in ret)
+ self.assertEquals(ret['name'], 'azcvsupdater_2.6.2.jar')
+ self.assertEquals(ret['info_hash'], 'ab570cdd5a17ea1b61e970bb72047de141bce173')
+ self.assertTrue('files_tree' in ret)
def test_get_magnet_info(self):
- ret = self.deluge_web.web_api.get_magnet_info("magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN")
- self.assertEquals(ret["name"], "953bad769164e8482c7785a21d12166f94b9e14d")
- self.assertEquals(ret["info_hash"], "953bad769164e8482c7785a21d12166f94b9e14d")
- self.assertTrue("files_tree" in ret)
+ ret = self.deluge_web.web_api.get_magnet_info('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN')
+ self.assertEquals(ret['name'], '953bad769164e8482c7785a21d12166f94b9e14d')
+ self.assertEquals(ret['info_hash'], '953bad769164e8482c7785a21d12166f94b9e14d')
+ self.assertTrue('files_tree' in ret)
@defer.inlineCallbacks
def test_get_torrent_files(self):
yield self.deluge_web.web_api.connect(self.host_id)
- filename = common.get_test_data_file("test.torrent")
- torrents = [{"path": filename, "options": {"download_location": "/home/deluge/"}}]
+ filename = common.get_test_data_file('test.torrent')
+ torrents = [{'path': filename, 'options': {'download_location': '/home/deluge/'}}]
yield self.deluge_web.web_api.add_torrents(torrents)
- ret = yield self.deluge_web.web_api.get_torrent_files("ab570cdd5a17ea1b61e970bb72047de141bce173")
- self.assertEquals(ret["type"], "dir")
- self.assertEquals(ret["contents"], {u'azcvsupdater_2.6.2.jar':
+ ret = yield self.deluge_web.web_api.get_torrent_files('ab570cdd5a17ea1b61e970bb72047de141bce173')
+ self.assertEquals(ret['type'], 'dir')
+ self.assertEquals(ret['contents'], {u'azcvsupdater_2.6.2.jar':
{'priority': 1, u'index': 0, u'offset': 0, 'progress': 0.0, u'path':
u'azcvsupdater_2.6.2.jar', 'type': 'file', u'size': 307949}})
@defer.inlineCallbacks
def test_download_torrent_from_url(self):
- filename = "ubuntu-9.04-desktop-i386.iso.torrent"
+ filename = 'ubuntu-9.04-desktop-i386.iso.torrent'
self.deluge_web.top_level.putChild(filename, File(common.get_test_data_file(filename)))
- url = "http://localhost:%d/%s" % (self.webserver_listen_port, filename)
+ url = 'http://localhost:%d/%s' % (self.webserver_listen_port, filename)
res = yield self.deluge_web.web_api.download_torrent_from_url(url)
self.assertTrue(res.endswith(filename))
diff --git a/deluge/tests/test_webserver.py b/deluge/tests/test_webserver.py
index fb546068b..988d4ed1e 100644
--- a/deluge/tests/test_webserver.py
+++ b/deluge/tests/test_webserver.py
@@ -36,7 +36,7 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
# This torrent file contains an uncommon field 'filehash' which must be hex
# encoded to allow dumping the torrent info to json. Otherwise it will fail with:
# UnicodeDecodeError: 'utf8' codec can't decode byte 0xe5 in position 0: invalid continuation byte
- filename = get_test_data_file("filehash_field.torrent")
+ filename = get_test_data_file('filehash_field.torrent')
d = yield agent.request(
'POST',
@@ -50,4 +50,4 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
raise SkipTest("This test requires 't.w.c.readBody()' in Twisted version >= 13.2")
json = json_lib.loads(body)
- self.assertEqual(None, json["error"])
+ self.assertEqual(None, json['error'])
diff --git a/deluge/tests/twisted/plugins/delugereporter.py b/deluge/tests/twisted/plugins/delugereporter.py
index 76433ef50..ae1959215 100644
--- a/deluge/tests/twisted/plugins/delugereporter.py
+++ b/deluge/tests/twisted/plugins/delugereporter.py
@@ -18,18 +18,18 @@ class _Reporter(object):
self.shortOpt = shortOpt
self.klass = klass
-deluge = _Reporter("Deluge reporter that suppresses Stacktrace from TODO tests",
- "twisted.plugins.delugereporter",
- description="Deluge Reporter",
- longOpt="deluge-reporter",
+deluge = _Reporter('Deluge reporter that suppresses Stacktrace from TODO tests',
+ 'twisted.plugins.delugereporter',
+ description='Deluge Reporter',
+ longOpt='deluge-reporter',
shortOpt=None,
- klass="DelugeReporter")
+ klass='DelugeReporter')
class DelugeReporter(TreeReporter):
def __init__(self, *args, **kwargs):
- os.environ["DELUGE_REPORTER"] = "true"
+ os.environ['DELUGE_REPORTER'] = 'true'
TreeReporter.__init__(self, *args, **kwargs)
def addExpectedFailure(self, *args): # NOQA
diff --git a/deluge/transfer.py b/deluge/transfer.py
index 15f88b088..67cae7e54 100644
--- a/deluge/transfer.py
+++ b/deluge/transfer.py
@@ -31,7 +31,7 @@ class DelugeTransferProtocol(Protocol, object):
"""
def __init__(self):
- self._buffer = ""
+ self._buffer = ''
self._message_length = 0
self._bytes_received = 0
self._bytes_sent = 0
@@ -50,8 +50,8 @@ class DelugeTransferProtocol(Protocol, object):
compressed = zlib.compress(rencode.dumps(data))
size_data = len(compressed)
# Store length as a signed integer (using 4 bytes). "!" denotes network byte order.
- payload_len = struct.pack("!i", size_data)
- header = "D" + payload_len
+ payload_len = struct.pack('!i', size_data)
+ header = 'D' + payload_len
self._bytes_sent += len(header) + len(compressed)
self.transport.write(header)
self.transport.write(compressed)
@@ -94,18 +94,18 @@ class DelugeTransferProtocol(Protocol, object):
header = self._buffer[:MESSAGE_HEADER_SIZE]
payload_len = header[1:MESSAGE_HEADER_SIZE]
if header[0] != 'D':
- raise Exception("Invalid header format. First byte is %d" % ord(header[0]))
+ raise Exception('Invalid header format. First byte is %d' % ord(header[0]))
# Extract the length stored as a signed integer (using 4 bytes)
- self._message_length = struct.unpack("!i", payload_len)[0]
+ self._message_length = struct.unpack('!i', payload_len)[0]
if self._message_length < 0:
- raise Exception("Message length is negative: %d" % self._message_length)
+ raise Exception('Message length is negative: %d' % self._message_length)
# Remove the header from the buffer
self._buffer = self._buffer[MESSAGE_HEADER_SIZE:]
except Exception as ex:
- log.warn("Error occurred when parsing message header: %s.", ex)
- log.warn("This version of Deluge cannot communicate with the sender of this data.")
+ log.warn('Error occurred when parsing message header: %s.', ex)
+ log.warn('This version of Deluge cannot communicate with the sender of this data.')
self._message_length = 0
- self._buffer = ""
+ self._buffer = ''
def _handle_complete_message(self, data):
"""
@@ -117,7 +117,7 @@ class DelugeTransferProtocol(Protocol, object):
try:
self.message_received(rencode.loads(zlib.decompress(data), decode_utf8=True))
except Exception as ex:
- log.warn("Failed to decompress (%d bytes) and load serialized data with rencode: %s", len(data), ex)
+ log.warn('Failed to decompress (%d bytes) and load serialized data with rencode: %s', len(data), ex)
def get_bytes_recv(self):
"""
diff --git a/deluge/ui/Win32IconImagePlugin.py b/deluge/ui/Win32IconImagePlugin.py
index 5e56de798..03f9bf9ee 100644
--- a/deluge/ui/Win32IconImagePlugin.py
+++ b/deluge/ui/Win32IconImagePlugin.py
@@ -131,7 +131,7 @@ class Win32IcoFile(object):
else:
# XOR + AND mask bmp frame
im = PIL.BmpImagePlugin.DibImageFile(self.buf)
- log.debug("Loaded image: %s %s %s %s", im.format, im.mode, im.size, im.info)
+ log.debug('Loaded image: %s %s %s %s', im.format, im.mode, im.size, im.info)
# change tile dimension to only encompass XOR image
im.size = im.size[0], im.size[1] // 2
@@ -146,7 +146,7 @@ class Win32IcoFile(object):
bpp = k
break
# end for
- log.debug("o:%s, w:%s, h:%s, bpp:%s", o, im.size[0], im.size[1], bpp)
+ log.debug('o:%s, w:%s, h:%s, bpp:%s', o, im.size[0], im.size[1], bpp)
and_mask_offset = o + (im.size[0] * im.size[1] * (bpp / 8))
if bpp == 32:
@@ -171,7 +171,7 @@ class Win32IcoFile(object):
# apply mask image as alpha channel
im = im.convert('RGBA')
im.putalpha(mask)
- log.debug("image mode: %s", im.mode)
+ log.debug('image mode: %s', im.mode)
else:
# get AND image from end of bitmap
@@ -181,7 +181,7 @@ class Win32IcoFile(object):
w += 32 - (im.size[0] % 32)
# the total mask data is padded row size * height / bits per char
total_bytes = (w * im.size[1]) // 8
- log.debug("tot=%d, off=%d, w=%d, size=%d", len(data), and_mask_offset, w, total_bytes)
+ log.debug('tot=%d, off=%d, w=%d, size=%d', len(data), and_mask_offset, w, total_bytes)
self.buf.seek(and_mask_offset)
mask_data = self.buf.read(total_bytes)
@@ -199,7 +199,7 @@ class Win32IcoFile(object):
# set mask as alpha channel
im = im.convert('RGBA')
im.putalpha(mask)
- log.debug("image mode: %s", im.mode)
+ log.debug('image mode: %s', im.mode)
# end if !'RGBA'
# end if (png)/else(bmp)
@@ -256,4 +256,4 @@ def _accept(prefix):
# register our decoder with PIL
PIL.Image.register_open(Win32IconImageFile.format, Win32IconImageFile, _accept)
-PIL.Image.register_extension(Win32IconImageFile.format, ".ico")
+PIL.Image.register_extension(Win32IconImageFile.format, '.ico')
diff --git a/deluge/ui/baseargparser.py b/deluge/ui/baseargparser.py
index 4684f1de8..75da06340 100644
--- a/deluge/ui/baseargparser.py
+++ b/deluge/ui/baseargparser.py
@@ -85,14 +85,14 @@ argparse.ArgumentParser.set_default_subparser = set_default_subparser
def get_version():
- version_str = "%s\n" % (common.get_version())
+ version_str = '%s\n' % (common.get_version())
try:
from deluge._libtorrent import lt
- version_str += "libtorrent: %s\n" % lt.__version__
+ version_str += 'libtorrent: %s\n' % lt.__version__
except ImportError:
pass
- version_str += "Python: %s\n" % platform.python_version()
- version_str += "OS: %s %s\n" % (platform.system(), " ".join(common.get_os_version()))
+ version_str += 'Python: %s\n' % platform.python_version()
+ version_str += 'OS: %s %s\n' % (platform.system(), ' '.join(common.get_os_version()))
return version_str
@@ -107,7 +107,7 @@ class DelugeTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
"""
wrapped_lines = []
for l in text.splitlines():
- wrapped_lines.extend(textwrap.wrap(l, width, subsequent_indent=" "))
+ wrapped_lines.extend(textwrap.wrap(l, width, subsequent_indent=' '))
return wrapped_lines
def _format_action_invocation(self, action):
@@ -133,16 +133,16 @@ class DelugeTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
- opt = ", ".join(action.option_strings)
- parts.append("%s %s" % (opt, args_string))
- return ", ".join(parts)
+ opt = ', '.join(action.option_strings)
+ parts.append('%s %s' % (opt, args_string))
+ return ', '.join(parts)
class HelpAction(argparse._HelpAction):
def __call__(self, parser, namespace, values, option_string=None):
- if hasattr(parser, "subparser"):
- subparser = getattr(parser, "subparser")
+ if hasattr(parser, 'subparser'):
+ subparser = getattr(parser, 'subparser')
subparser.print_help()
else:
parser.print_help()
@@ -152,42 +152,42 @@ class HelpAction(argparse._HelpAction):
class BaseArgParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
- if "formatter_class" not in kwargs:
- kwargs["formatter_class"] = lambda prog: DelugeTextHelpFormatter(prog, max_help_position=33, width=90)
+ if 'formatter_class' not in kwargs:
+ kwargs['formatter_class'] = lambda prog: DelugeTextHelpFormatter(prog, max_help_position=33, width=90)
- kwargs["add_help"] = kwargs.get("add_help", False)
- common_help = kwargs.pop("common_help", True)
+ kwargs['add_help'] = kwargs.get('add_help', False)
+ common_help = kwargs.pop('common_help', True)
self.log_stream = sys.stdout
- if "log_stream" in kwargs:
- self.log_stream = kwargs["log_stream"]
- del kwargs["log_stream"]
+ if 'log_stream' in kwargs:
+ self.log_stream = kwargs['log_stream']
+ del kwargs['log_stream']
super(BaseArgParser, self).__init__(*args, **kwargs)
self.common_setup = False
self.process_arg_group = False
- self.group = self.add_argument_group(_("Common Options"))
+ 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(),
+ 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('-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.
@@ -238,14 +238,14 @@ class BaseArgParser(argparse.ArgumentParser):
# Setup the logger
if options.quiet:
- options.loglevel = "none"
+ options.loglevel = 'none'
if options.loglevel:
options.loglevel = options.loglevel.lower()
- logfile_mode = "w"
+ logfile_mode = 'w'
logrotate = options.logrotate
if options.logrotate:
- logfile_mode = "a"
+ logfile_mode = 'a'
logrotate = common.parse_human_size(options.logrotate)
# Setup the logger
@@ -255,7 +255,7 @@ class BaseArgParser(argparse.ArgumentParser):
if options.config:
if not set_config_dir(options.config):
log = logging.getLogger(__name__)
- log.error("There was an error setting the config dir! Exiting..")
+ log.error('There was an error setting the config dir! Exiting..')
sys.exit(1)
else:
if not os.path.exists(common.get_default_config_dir()):
@@ -276,8 +276,8 @@ class BaseArgParser(argparse.ArgumentParser):
# Write pid file before chuid
if options.pidfile:
- with open(options.pidfile, "wb") as _file:
- _file.write("%d\n" % os.getpid())
+ with open(options.pidfile, 'wb') as _file:
+ _file.write('%d\n' % os.getpid())
if not common.windows_check():
if options.user:
@@ -297,15 +297,15 @@ class BaseArgParser(argparse.ArgumentParser):
"""Adds a grouping of common process args to control a daemon to the parser"""
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 = self.add_argument_group(_('Process Control Options'))
+ 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",
+ 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('-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 2ec72b086..a07f21d47 100644
--- a/deluge/ui/client.py
+++ b/deluge/ui/client.py
@@ -28,7 +28,7 @@ log = logging.getLogger(__name__)
def format_kwargs(kwargs):
- return ", ".join([key + "=" + str(value) for key, value in kwargs.items()])
+ return ', '.join([key + '=' + str(value) for key, value in kwargs.items()])
class DelugeRPCRequest(object):
@@ -47,14 +47,14 @@ class DelugeRPCRequest(object):
Returns a string of the RPCRequest in the following form:
method(arg, kwarg=foo, ...)
"""
- s = self.method + "("
+ s = self.method + '('
if self.args:
- s += ", ".join([str(x) for x in self.args])
+ s += ', '.join([str(x) for x in self.args])
if self.kwargs:
if self.args:
- s += ", "
+ s += ', '
s += format_kwargs(self.kwargs)
- s += ")"
+ s += ')'
return s
@@ -66,7 +66,7 @@ class DelugeRPCRequest(object):
:returns: a properly formated RPCRequest
"""
if self.request_id is None or self.method is None or self.args is None or self.kwargs is None:
- raise TypeError("You must set the properties of this object before calling format_message!")
+ raise TypeError('You must set the properties of this object before calling format_message!')
return (self.request_id, self.method, self.args, self.kwargs)
@@ -82,7 +82,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
self.factory.daemon.host = peer.host
self.factory.daemon.port = peer.port
self.factory.daemon.connected = True
- log.debug("Connected to daemon at %s:%s..", peer.host, peer.port)
+ log.debug('Connected to daemon at %s:%s..', peer.host, peer.port)
self.factory.daemon.connect_deferred.callback((peer.host, peer.port))
def message_received(self, request):
@@ -93,11 +93,11 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
"""
if not isinstance(request, tuple):
- log.debug("Received invalid message: type is not tuple")
+ 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]
@@ -129,7 +129,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
exception_cls = getattr(error, request[2])
exception = exception_cls(*request[3], **request[4])
except TypeError:
- log.warn("Received invalid RPC_ERROR (Old daemon?): %s", request[2])
+ log.warn('Received invalid RPC_ERROR (Old daemon?): %s', request[2])
return
# Ideally we would chain the deferreds instead of instance
@@ -140,17 +140,17 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
# So, just do some instance checking and just log rpc error at
# diferent levels.
r = self.__rpc_requests[request_id]
- msg = "RPCError Message Received!"
- msg += "\n" + "-" * 80
- msg += "\n" + "RPCRequest: " + r.__repr__()
- msg += "\n" + "-" * 80
+ msg = 'RPCError Message Received!'
+ msg += '\n' + '-' * 80
+ msg += '\n' + 'RPCRequest: ' + r.__repr__()
+ msg += '\n' + '-' * 80
if isinstance(exception, error.WrappedException):
- msg += "\n" + exception.type + "\n" + exception.message + ": "
+ msg += '\n' + exception.type + '\n' + exception.message + ': '
msg += exception.traceback
else:
- msg += "\n" + request[5] + "\n" + request[2] + ": "
+ msg += '\n' + request[5] + '\n' + request[2] + ': '
msg += str(exception)
- msg += "\n" + "-" * 80
+ msg += '\n' + '-' * 80
if not isinstance(exception, error._ClientSideRecreateError):
# Let's log these as errors
@@ -161,7 +161,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
log.debug(msg)
except Exception:
import traceback
- log.error("Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s",
+ log.error('Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s',
request[2], traceback.format_exc())
d.errback(exception)
del self.__rpc_requests[request_id]
@@ -182,7 +182,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
# Send the request in a tuple because multiple requests can be sent at once
self.transfer_message((request.format_message(),))
except Exception as ex:
- log.warn("Error occurred when sending message: %s", ex)
+ log.warn('Error occurred when sending message: %s', ex)
class DelugeRPCClientFactory(ClientFactory):
@@ -257,7 +257,7 @@ class DaemonSSLProxy(DaemonProxy):
:returns: twisted.Deferred
"""
- log.debug("sslproxy.connect()")
+ log.debug('sslproxy.connect()')
self.host = host
self.port = port
self.__connector = reactor.connectSSL(self.host, self.port,
@@ -273,7 +273,7 @@ class DaemonSSLProxy(DaemonProxy):
return self.daemon_info_deferred
def disconnect(self):
- log.debug("sslproxy.disconnect()")
+ log.debug('sslproxy.disconnect()')
self.disconnect_deferred = defer.Deferred()
self.__connector.disconnect()
return self.disconnect_deferred
@@ -340,7 +340,7 @@ class DaemonSSLProxy(DaemonProxy):
# that we're interested in receiving this type of event
self.__factory.event_handlers[event] = []
if self.connected:
- self.call("daemon.set_event_interest", [event])
+ self.call('daemon.set_event_interest', [event])
# Only add the handler if it's not already registered
if handler not in self.__factory.event_handlers[event]:
@@ -360,43 +360,43 @@ class DaemonSSLProxy(DaemonProxy):
self.__factory.event_handlers[event].remove(handler)
def __on_connect(self, result):
- log.debug("__on_connect called")
+ log.debug('__on_connect called')
def on_info(daemon_info):
self.daemon_info = daemon_info
- log.debug("Got info from daemon: %s", daemon_info)
+ log.debug('Got info from daemon: %s', daemon_info)
self.daemon_info_deferred.callback(daemon_info)
def on_info_fail(reason):
- log.debug("Failed to get info from daemon")
+ log.debug('Failed to get info from daemon')
log.exception(reason)
self.daemon_info_deferred.errback(reason)
- self.call("daemon.info").addCallback(on_info).addErrback(on_info_fail)
+ self.call('daemon.info').addCallback(on_info).addErrback(on_info_fail)
return self.daemon_info_deferred
def __on_connect_fail(self, reason):
self.daemon_info_deferred.errback(reason)
def authenticate(self, username, password):
- log.debug("%s.authenticate: %s", self.__class__.__name__, username)
+ log.debug('%s.authenticate: %s', self.__class__.__name__, username)
login_deferred = defer.Deferred()
- d = self.call("daemon.login", username, password,
+ d = self.call('daemon.login', username, password,
client_version=deluge.common.get_version())
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):
- log.debug("__on_login called: %s %s", username, result)
+ log.debug('__on_login called: %s %s', username, result)
self.username = username
self.authentication_level = result
# We need to tell the daemon what events we're interested in receiving
if self.__factory.event_handlers:
- self.call("daemon.set_event_interest",
+ self.call('daemon.set_event_interest',
self.__factory.event_handlers.keys())
- self.call("core.get_auth_levels_mappings").addCallback(
+ self.call('core.get_auth_levels_mappings').addCallback(
self.__on_auth_levels_mappings
)
@@ -431,15 +431,15 @@ class DaemonStandaloneProxy(DaemonProxy):
from deluge.core import daemon
self.__daemon = daemon.Daemon(standalone=True)
self.__daemon.start()
- log.debug("daemon created!")
+ log.debug('daemon created!')
self.connected = True
- self.host = "localhost"
+ 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)
- self.username = "localclient"
+ self.username = 'localclient'
self.authentication_level = AUTH_LEVEL_ADMIN
self.auth_levels_mapping = AUTH_LEVELS_MAPPING
self.auth_levels_mapping_reverse = AUTH_LEVELS_MAPPING_REVERSE
@@ -506,7 +506,7 @@ class DottedObject(object):
raise Exception("You must make calls in the form of 'component.method'!")
def __getattr__(self, name):
- return RemoteMethod(self.daemon, self.base + "." + name)
+ return RemoteMethod(self.daemon, self.base + '.' + name)
class RemoteMethod(DottedObject):
@@ -530,7 +530,7 @@ class Client(object):
self.disconnect_callback = None
self.__started_standalone = False
- def connect(self, host="127.0.0.1", port=58846, username="", password="",
+ def connect(self, host='127.0.0.1', port=58846, username='', password='',
skip_authentication=False):
"""
Connects to a daemon process.
@@ -550,24 +550,24 @@ class Client(object):
d = self._daemon_proxy.connect(host, port)
def on_connected(daemon_version):
- log.debug("on_connected. Daemon version: %s", daemon_version)
+ log.debug('on_connected. Daemon version: %s', daemon_version)
return daemon_version
def on_connect_fail(reason):
- log.debug("on_connect_fail: %s", reason)
+ log.debug('on_connect_fail: %s', reason)
self.disconnect()
return reason
def on_authenticate(result, daemon_info):
- log.debug("Authentication successful: %s", result)
+ log.debug('Authentication successful: %s', result)
return result
def on_authenticate_fail(reason):
- log.debug("Failed to authenticate: %s", reason.value)
+ log.debug('Failed to authenticate: %s', reason.value)
return reason
def authenticate(daemon_version, username, password):
- if not username and host in ("127.0.0.1", "localhost"):
+ if not username and host in ('127.0.0.1', 'localhost'):
# No username provided and it's localhost, so attempt to get credentials from auth file.
username, password = get_localhost_auth()
@@ -633,7 +633,7 @@ class Client(object):
# subprocess.popen does not work with unicode args (with non-ascii characters) on windows
config = config.encode(sys.getfilesystemencoding())
try:
- subprocess.Popen(["deluged", "--port=%s" % port, "--config=%s" % config])
+ subprocess.Popen(['deluged', '--port=%s' % port, '--config=%s' % config])
except OSError as ex:
from errno import ENOENT
if ex.errno == ENOENT:
@@ -643,7 +643,7 @@ that you forgot to install the deluged package or it's not in your PATH."))
log.exception(ex)
raise ex
except Exception as ex:
- log.error("Unable to start daemon!")
+ log.error('Unable to start daemon!')
log.exception(ex)
return False
else:
@@ -656,7 +656,7 @@ that you forgot to install the deluged package or it's not in your PATH."))
:returns: bool, True if connected to a localhost
"""
- if (self._daemon_proxy and self._daemon_proxy.host in ("127.0.0.1", "localhost") or
+ if (self._daemon_proxy and self._daemon_proxy.host in ('127.0.0.1', 'localhost') or
isinstance(self._daemon_proxy, DaemonStandaloneProxy)):
return True
return False
diff --git a/deluge/ui/common.py b/deluge/ui/common.py
index 81bdd37bb..686963aee 100644
--- a/deluge/ui/common.py
+++ b/deluge/ui/common.py
@@ -33,75 +33,75 @@ def _(message):
return message
STATE_TRANSLATION = {
- "All": _("All"),
- "Active": _("Active"),
- "Allocating": _("Allocating"),
- "Checking": _("Checking"),
- "Downloading": _("Downloading"),
- "Seeding": _("Seeding"),
- "Paused": _("Paused"),
- "Queued": _("Queued"),
- "Error": _("Error"),
+ 'All': _('All'),
+ 'Active': _('Active'),
+ 'Allocating': _('Allocating'),
+ 'Checking': _('Checking'),
+ 'Downloading': _('Downloading'),
+ 'Seeding': _('Seeding'),
+ 'Paused': _('Paused'),
+ 'Queued': _('Queued'),
+ 'Error': _('Error'),
}
TORRENT_DATA_FIELD = {
- "queue": {"name": "#", "status": ["queue"]},
- "name": {"name": _("Name"), "status": ["state", "name"]},
- "progress_state": {"name": _("Progress"), "status": ["progress", "state"]},
- "state": {"name": _("State"), "status": ["state"]},
- "progress": {"name": _("Progress"), "status": ["progress"]},
- "size": {"name": _("Size"), "status": ["total_wanted"]},
- "downloaded": {"name": _("Downloaded"), "status": ["all_time_download"]},
- "uploaded": {"name": _("Uploaded"), "status": ["total_uploaded"]},
- "remaining": {"name": _("Remaining"), "status": ["total_remaining"]},
- "ratio": {"name": _("Ratio"), "status": ["ratio"]},
- "download_speed": {"name": _("Down Speed"), "status": ["download_payload_rate"]},
- "upload_speed": {"name": _("Up Speed"), "status": ["upload_payload_rate"]},
- "max_download_speed": {"name": _("Down Limit"), "status": ["max_download_speed"]},
- "max_upload_speed": {"name": _("Up Limit"), "status": ["max_upload_speed"]},
- "max_connections": {"name": _("Max Connections"), "status": ["max_connections"]},
- "max_upload_slots": {"name": _("Max Upload Slots"), "status": ["max_upload_slots"]},
- "peers": {"name": _("Peers"), "status": ["num_peers", "total_peers"]},
- "seeds": {"name": _("Seeds"), "status": ["num_seeds", "total_seeds"]},
- "avail": {"name": _("Avail"), "status": ["distributed_copies"]},
- "seeds_peers_ratio": {"name": _("Seeds:Peers"), "status": ["seeds_peers_ratio"]},
- "time_added": {"name": _("Added"), "status": ["time_added"]},
- "tracker": {"name": _("Tracker"), "status": ["tracker_host"]},
- "download_location": {"name": _("Download Folder"), "status": ["download_location"]},
- "seeding_time": {"name": _("Seeding Time"), "status": ["seeding_time"]},
- "active_time": {"name": _("Active Time"), "status": ["active_time"]},
- "finished_time": {"name": _("Finished Time"), "status": ["finished_time"]},
- "last_seen_complete": {"name": _("Complete Seen"), "status": ["last_seen_complete"]},
- "completed_time": {"name": _("Completed"), "status": ["completed_time"]},
- "eta": {"name": _("ETA"), "status": ["eta"]},
- "shared": {"name": _("Shared"), "status": ["shared"]},
- "prioritize_first_last": {"name": _("Prioritize First/Last"), "status": ["prioritize_first_last"]},
- "sequential_download": {"name": _("Sequential Download"), "status": ["sequential_download"]},
- "is_auto_managed": {"name": _("Auto Managed"), "status": ["is_auto_managed"]},
- "auto_managed": {"name": _("Auto Managed"), "status": ["auto_managed"]},
- "stop_at_ratio": {"name": _("Stop At Ratio"), "status": ["stop_at_ratio"]},
- "stop_ratio": {"name": _("Stop Ratio"), "status": ["stop_ratio"]},
- "remove_at_ratio": {"name": _("Remove At Ratio"), "status": ["remove_at_ratio"]},
- "move_completed": {"name": _("Move On Completed"), "status": ["move_completed"]},
- "move_completed_path": {"name": _("Move Completed Path"), "status": ["move_completed_path"]},
- "move_on_completed": {"name": _("Move On Completed"), "status": ["move_on_completed"]},
- "move_on_completed_path": {"name": _("Move On Completed Path"), "status": ["move_on_completed_path"]},
- "owner": {"name": _("Owner"), "status": ["owner"]}
+ 'queue': {'name': '#', 'status': ['queue']},
+ 'name': {'name': _('Name'), 'status': ['state', 'name']},
+ 'progress_state': {'name': _('Progress'), 'status': ['progress', 'state']},
+ 'state': {'name': _('State'), 'status': ['state']},
+ 'progress': {'name': _('Progress'), 'status': ['progress']},
+ 'size': {'name': _('Size'), 'status': ['total_wanted']},
+ 'downloaded': {'name': _('Downloaded'), 'status': ['all_time_download']},
+ 'uploaded': {'name': _('Uploaded'), 'status': ['total_uploaded']},
+ 'remaining': {'name': _('Remaining'), 'status': ['total_remaining']},
+ 'ratio': {'name': _('Ratio'), 'status': ['ratio']},
+ 'download_speed': {'name': _('Down Speed'), 'status': ['download_payload_rate']},
+ 'upload_speed': {'name': _('Up Speed'), 'status': ['upload_payload_rate']},
+ 'max_download_speed': {'name': _('Down Limit'), 'status': ['max_download_speed']},
+ 'max_upload_speed': {'name': _('Up Limit'), 'status': ['max_upload_speed']},
+ 'max_connections': {'name': _('Max Connections'), 'status': ['max_connections']},
+ 'max_upload_slots': {'name': _('Max Upload Slots'), 'status': ['max_upload_slots']},
+ 'peers': {'name': _('Peers'), 'status': ['num_peers', 'total_peers']},
+ 'seeds': {'name': _('Seeds'), 'status': ['num_seeds', 'total_seeds']},
+ 'avail': {'name': _('Avail'), 'status': ['distributed_copies']},
+ 'seeds_peers_ratio': {'name': _('Seeds:Peers'), 'status': ['seeds_peers_ratio']},
+ 'time_added': {'name': _('Added'), 'status': ['time_added']},
+ 'tracker': {'name': _('Tracker'), 'status': ['tracker_host']},
+ 'download_location': {'name': _('Download Folder'), 'status': ['download_location']},
+ 'seeding_time': {'name': _('Seeding Time'), 'status': ['seeding_time']},
+ 'active_time': {'name': _('Active Time'), 'status': ['active_time']},
+ 'finished_time': {'name': _('Finished Time'), 'status': ['finished_time']},
+ 'last_seen_complete': {'name': _('Complete Seen'), 'status': ['last_seen_complete']},
+ 'completed_time': {'name': _('Completed'), 'status': ['completed_time']},
+ 'eta': {'name': _('ETA'), 'status': ['eta']},
+ 'shared': {'name': _('Shared'), 'status': ['shared']},
+ 'prioritize_first_last': {'name': _('Prioritize First/Last'), 'status': ['prioritize_first_last']},
+ 'sequential_download': {'name': _('Sequential Download'), 'status': ['sequential_download']},
+ 'is_auto_managed': {'name': _('Auto Managed'), 'status': ['is_auto_managed']},
+ 'auto_managed': {'name': _('Auto Managed'), 'status': ['auto_managed']},
+ 'stop_at_ratio': {'name': _('Stop At Ratio'), 'status': ['stop_at_ratio']},
+ 'stop_ratio': {'name': _('Stop Ratio'), 'status': ['stop_ratio']},
+ 'remove_at_ratio': {'name': _('Remove At Ratio'), 'status': ['remove_at_ratio']},
+ 'move_completed': {'name': _('Move On Completed'), 'status': ['move_completed']},
+ 'move_completed_path': {'name': _('Move Completed Path'), 'status': ['move_completed_path']},
+ 'move_on_completed': {'name': _('Move On Completed'), 'status': ['move_on_completed']},
+ 'move_on_completed_path': {'name': _('Move On Completed Path'), 'status': ['move_on_completed_path']},
+ 'owner': {'name': _('Owner'), 'status': ['owner']}
}
TRACKER_STATUS_TRANSLATION = {
- "Error": _("Error"),
- "Warning": _("Warning"),
- "Announce OK": _("Announce OK"),
- "Announce Sent": _("Announce Sent")
+ 'Error': _('Error'),
+ 'Warning': _('Warning'),
+ 'Announce OK': _('Announce OK'),
+ 'Announce Sent': _('Announce Sent')
}
del _
-DEFAULT_HOST = "127.0.0.1"
+DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 58846
DEFAULT_HOSTS = {
- "hosts": [(sha(str(time.time())).hexdigest(), DEFAULT_HOST, DEFAULT_PORT, "", "")]
+ 'hosts': [(sha(str(time.time())).hexdigest(), DEFAULT_HOST, DEFAULT_PORT, '', '')]
}
@@ -116,73 +116,73 @@ class TorrentInfo(object):
def __init__(self, filename, filetree=1):
# Get the torrent data from the torrent file
try:
- log.debug("Attempting to open %s.", filename)
- with open(filename, "rb") as _file:
+ log.debug('Attempting to open %s.', filename)
+ with open(filename, 'rb') as _file:
self.__m_filedata = _file.read()
except IOError as ex:
- log.warning("Unable to open %s: %s", filename, ex)
+ log.warning('Unable to open %s: %s', filename, ex)
raise ex
try:
self.__m_metadata = bencode.bdecode(self.__m_filedata)
except bencode.BTFailure as ex:
- log.warning("Failed to decode %s: %s", filename, ex)
+ log.warning('Failed to decode %s: %s', filename, ex)
raise ex
- self.__m_info_hash = sha(bencode.bencode(self.__m_metadata["info"])).hexdigest()
+ self.__m_info_hash = sha(bencode.bencode(self.__m_metadata['info'])).hexdigest()
# Get encoding from torrent file if available
self.encoding = None
- if "encoding" in self.__m_metadata:
- self.encoding = self.__m_metadata["encoding"]
- elif "codepage" in self.__m_metadata:
- self.encoding = str(self.__m_metadata["codepage"])
+ if 'encoding' in self.__m_metadata:
+ self.encoding = self.__m_metadata['encoding']
+ elif 'codepage' in self.__m_metadata:
+ self.encoding = str(self.__m_metadata['codepage'])
if not self.encoding:
- self.encoding = "UTF-8"
+ self.encoding = 'UTF-8'
# Check if 'name.utf-8' is in the torrent and if not try to decode the string
# using the encoding found.
- if "name.utf-8" in self.__m_metadata["info"]:
- self.__m_name = utf8_encoded(self.__m_metadata["info"]["name.utf-8"])
+ if 'name.utf-8' in self.__m_metadata['info']:
+ self.__m_name = utf8_encoded(self.__m_metadata['info']['name.utf-8'])
else:
- self.__m_name = utf8_encoded(self.__m_metadata["info"]["name"], self.encoding)
+ self.__m_name = utf8_encoded(self.__m_metadata['info']['name'], self.encoding)
# Get list of files from torrent info
paths = {}
dirs = {}
- if "files" in self.__m_metadata["info"]:
- prefix = ""
- if len(self.__m_metadata["info"]["files"]) > 1:
+ if 'files' in self.__m_metadata['info']:
+ prefix = ''
+ if len(self.__m_metadata['info']['files']) > 1:
prefix = self.__m_name
- for index, f in enumerate(self.__m_metadata["info"]["files"]):
- if "path.utf-8" in f:
- path = os.path.join(prefix, *f["path.utf-8"])
- del f["path.utf-8"]
+ for index, f in enumerate(self.__m_metadata['info']['files']):
+ if 'path.utf-8' in f:
+ path = os.path.join(prefix, *f['path.utf-8'])
+ del f['path.utf-8']
else:
- path = utf8_encoded(os.path.join(prefix, utf8_encoded(os.path.join(*f["path"]),
+ path = utf8_encoded(os.path.join(prefix, utf8_encoded(os.path.join(*f['path']),
self.encoding)), self.encoding)
- f["path"] = path
- f["index"] = index
- if "sha1" in f and len(f["sha1"]) == 20:
- f["sha1"] = f["sha1"].encode('hex')
- if "ed2k" in f and len(f["ed2k"]) == 16:
- f["ed2k"] = f["ed2k"].encode('hex')
- if "filehash" in f and len(f["filehash"]) == 20:
- f["filehash"] = f["filehash"].encode('hex')
+ f['path'] = path
+ f['index'] = index
+ if 'sha1' in f and len(f['sha1']) == 20:
+ f['sha1'] = f['sha1'].encode('hex')
+ if 'ed2k' in f and len(f['ed2k']) == 16:
+ f['ed2k'] = f['ed2k'].encode('hex')
+ if 'filehash' in f and len(f['filehash']) == 20:
+ f['filehash'] = f['filehash'].encode('hex')
paths[path] = f
dirname = os.path.dirname(path)
while dirname:
dirinfo = dirs.setdefault(dirname, {})
- dirinfo["length"] = dirinfo.get("length", 0) + f["length"]
+ dirinfo['length'] = dirinfo.get('length', 0) + f['length']
dirname = os.path.dirname(dirname)
if filetree == 2:
def walk(path, item):
- if item["type"] == "dir":
+ if item['type'] == 'dir':
item.update(dirs[path])
else:
item.update(paths[path])
- item["download"] = True
+ item['download'] = True
file_tree = FileTree2(paths.keys())
file_tree.walk(walk)
@@ -190,7 +190,7 @@ class TorrentInfo(object):
def walk(path, item):
if isinstance(item, dict):
return item
- return [paths[path]["index"], paths[path]["length"], True]
+ return [paths[path]['index'], paths[path]['length'], True]
file_tree = FileTree(paths)
file_tree.walk(walk)
@@ -198,37 +198,37 @@ class TorrentInfo(object):
else:
if filetree == 2:
self.__m_files_tree = {
- "contents": {
+ 'contents': {
self.__m_name: {
- "type": "file",
- "index": 0,
- "length": self.__m_metadata["info"]["length"],
- "download": True
+ 'type': 'file',
+ 'index': 0,
+ 'length': self.__m_metadata['info']['length'],
+ '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 = []
- if "files" in self.__m_metadata["info"]:
- prefix = ""
- if len(self.__m_metadata["info"]["files"]) > 1:
+ if 'files' in self.__m_metadata['info']:
+ prefix = ''
+ if len(self.__m_metadata['info']['files']) > 1:
prefix = self.__m_name
- for f in self.__m_metadata["info"]["files"]:
+ for f in self.__m_metadata['info']['files']:
self.__m_files.append({
- 'path': f["path"],
- 'size': f["length"],
+ 'path': f['path'],
+ 'size': f['length'],
'download': True
})
else:
self.__m_files.append({
- "path": self.__m_name,
- "size": self.__m_metadata["info"]["length"],
- "download": True
+ 'path': self.__m_name,
+ 'size': self.__m_metadata['info']['length'],
+ 'download': True
})
def as_dict(self, *keys):
@@ -314,33 +314,33 @@ class FileTree2(object):
"""
def __init__(self, paths):
- self.tree = {"contents": {}, "type": "dir"}
+ self.tree = {'contents': {}, 'type': 'dir'}
def get_parent(path):
parent = self.tree
- while "/" in path:
- directory, path = path.split("/", 1)
- child = parent["contents"].get(directory)
+ while '/' in path:
+ directory, path = path.split('/', 1)
+ child = parent['contents'].get(directory)
if child is None:
- parent["contents"][directory] = {
- "type": "dir",
- "contents": {}
+ parent['contents'][directory] = {
+ 'type': 'dir',
+ 'contents': {}
}
- parent = parent["contents"][directory]
+ parent = parent['contents'][directory]
return parent, path
for path in paths:
- if path[-1] == "/":
+ if path[-1] == '/':
path = path[:-1]
parent, path = get_parent(path)
- parent["contents"][path] = {
- "type": "dir",
- "contents": {}
+ parent['contents'][path] = {
+ 'type': 'dir',
+ 'contents': {}
}
else:
parent, path = get_parent(path)
- parent["contents"][path] = {
- "type": "file"
+ parent['contents'][path] = {
+ 'type': 'file'
}
def get_tree(self):
@@ -363,29 +363,29 @@ class FileTree2(object):
:type callback: function
"""
def walk(directory, parent_path):
- for path in directory["contents"].keys():
- 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]
- walk(directory["contents"][path], full_path)
+ for path in directory['contents'].keys():
+ 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]
+ walk(directory['contents'][path], full_path)
else:
- directory["contents"][path] = callback(
- full_path, directory["contents"][path]
- ) or directory["contents"][path]
- walk(self.tree, "")
+ directory['contents'][path] = callback(
+ full_path, directory['contents'][path]
+ ) or directory['contents'][path]
+ walk(self.tree, '')
def __str__(self):
lines = []
def write(path, item):
- depth = path.count("/")
+ depth = path.count('/')
path = os.path.basename(path)
- path = path + "/" if item["type"] == "dir" else path
- lines.append(" " * depth + path)
+ path = path + '/' if item['type'] == 'dir' else path
+ lines.append(' ' * depth + path)
self.walk(write)
- return "\n".join(lines)
+ return '\n'.join(lines)
class FileTree(object):
@@ -401,8 +401,8 @@ class FileTree(object):
def get_parent(path):
parent = self.tree
- while "/" in path:
- directory, path = path.split("/", 1)
+ while '/' in path:
+ directory, path = path.split('/', 1)
child = parent.get(directory)
if child is None:
parent[directory] = {}
@@ -410,7 +410,7 @@ class FileTree(object):
return parent, path
for path in paths:
- if path[-1] == "/":
+ if path[-1] == '/':
path = path[:-1]
parent, path = get_parent(path)
parent[path] = {}
@@ -450,18 +450,18 @@ class FileTree(object):
walk(directory[path], full_path)
else:
directory[path] = callback(full_path, directory[path]) or directory[path]
- walk(self.tree, "")
+ walk(self.tree, '')
def __str__(self):
lines = []
def write(path, item):
- depth = path.count("/")
+ depth = path.count('/')
path = os.path.basename(path)
- path = isinstance(item, dict) and path + "/" or path
- lines.append(" " * depth + path)
+ path = isinstance(item, dict) and path + '/' or path
+ lines.append(' ' * depth + path)
self.walk(write)
- return "\n".join(lines)
+ return '\n'.join(lines)
def get_localhost_auth():
@@ -471,7 +471,7 @@ def get_localhost_auth():
:returns: with the username and password to login as
:rtype: tuple
"""
- auth_file = deluge.configmanager.get_config_dir("auth")
+ auth_file = deluge.configmanager.get_config_dir('auth')
if not os.path.exists(auth_file):
from deluge.common import create_localclient_account
create_localclient_account()
@@ -479,19 +479,19 @@ def get_localhost_auth():
with open(auth_file) as auth:
for line in auth:
line = line.strip()
- if line.startswith("#") or not line:
+ if line.startswith('#') or not line:
# This is a comment or blank line
continue
- lsplit = line.split(":")
+ lsplit = line.split(':')
if len(lsplit) == 2:
username, password = lsplit
elif len(lsplit) == 3:
username, password, level = lsplit
else:
- log.error("Your auth file is malformed: Incorrect number of fields!")
+ log.error('Your auth file is malformed: Incorrect number of fields!')
continue
- if username == "localclient":
+ if username == 'localclient':
return (username, password)
diff --git a/deluge/ui/console/cmdline/command.py b/deluge/ui/console/cmdline/command.py
index 2dfe87e84..bacd05ab2 100644
--- a/deluge/ui/console/cmdline/command.py
+++ b/deluge/ui/console/cmdline/command.py
@@ -65,17 +65,17 @@ class Commander(object):
"""
if not cmd_line:
return
- cmd, _, line = cmd_line.partition(" ")
+ cmd, _, line = cmd_line.partition(' ')
try:
parser = self._commands[cmd].create_parser()
except KeyError:
- self.write("{!error!}Unknown command: %s" % cmd)
+ self.write('{!error!}Unknown command: %s' % cmd)
return
try:
args = [cmd] + self._commands[cmd].split(line)
except ValueError as ex:
- self.write("{!error!}Error parsing command: %s" % ex)
+ self.write('{!error!}Error parsing command: %s' % ex)
return
# Do a little hack here to print 'command --help' properly
@@ -89,32 +89,32 @@ class Commander(object):
parser.print_help = print_help
# Only these commands can be run when not connected to a daemon
- not_connected_cmds = ["help", "connect", "quit"]
+ not_connected_cmds = ['help', 'connect', 'quit']
aliases = []
for c in not_connected_cmds:
aliases.extend(self._commands[c].aliases)
not_connected_cmds.extend(aliases)
if not client.connected() and cmd not in not_connected_cmds:
- self.write("{!error!}Not connected to a daemon, please use the connect command first.")
+ self.write('{!error!}Not connected to a daemon, please use the connect command first.')
return
try:
options = parser.parse_args(args=args)
options.command = cmd
except TypeError as ex:
- self.write("{!error!}Error parsing options: %s" % ex)
+ self.write('{!error!}Error parsing options: %s' % ex)
import traceback
- self.write("%s" % traceback.format_exc())
+ self.write('%s' % traceback.format_exc())
return
except OptionParserError as ex:
import traceback
log.warn("Error parsing command '%s': %s", args, ex)
- self.write("{!error!} %s" % ex)
+ self.write('{!error!} %s' % ex)
parser.print_help()
return
- if getattr(parser, "_exit", False):
+ if getattr(parser, '_exit', False):
return
return options
@@ -131,10 +131,10 @@ class Commander(object):
try:
ret = self._commands[options.command].handle(options)
except Exception as ex: # pylint: disable=broad-except
- self.write("{!error!} %s" % ex)
+ self.write('{!error!} %s' % ex)
log.exception(ex)
import traceback
- self.write("%s" % traceback.format_exc())
+ self.write('%s' % traceback.format_exc())
return defer.succeed(True)
else:
return ret
@@ -145,8 +145,8 @@ class BaseCommand(object):
usage = None
interactive_only = False
aliases = []
- _name = "base"
- epilog = ""
+ _name = 'base'
+ epilog = ''
def complete(self, text, *args):
return []
@@ -160,7 +160,7 @@ class BaseCommand(object):
@property
def name_with_alias(self):
- return "/".join([self._name] + self.aliases)
+ return '/'.join([self._name] + self.aliases)
@property
def description(self):
@@ -168,27 +168,27 @@ class BaseCommand(object):
def split(self, text):
if windows_check():
- text = text.replace("\\", "\\\\")
+ text = text.replace('\\', '\\\\')
result = shlex.split(text)
for i, s in enumerate(result):
- result[i] = s.replace(r"\ ", " ")
- result = [s for s in result if s != ""]
+ result[i] = s.replace(r'\ ', ' ')
+ result = [s for s in result if s != '']
return result
def create_parser(self):
- opts = {"prog": self.name_with_alias, "description": self.__doc__, "epilog": self.epilog}
+ opts = {'prog': self.name_with_alias, 'description': self.__doc__, 'epilog': self.epilog}
if self.usage:
- opts["usage"] = self.usage
+ opts['usage'] = self.usage
parser = OptionParser(**opts)
- parser.add_argument(self.name, metavar="")
+ parser.add_argument(self.name, metavar='')
parser.base_parser = parser
self.add_arguments(parser)
return parser
def add_subparser(self, subparsers):
- opts = {"prog": self.name_with_alias, "help": self.__doc__, "description": self.__doc__}
+ opts = {'prog': self.name_with_alias, 'help': self.__doc__, 'description': self.__doc__}
if self.usage:
- opts["usage"] = self.usage
+ opts['usage'] = self.usage
parser = subparsers.add_parser(self.name, **opts)
self.add_arguments(parser)
diff --git a/deluge/ui/console/cmdline/commands/add.py b/deluge/ui/console/cmdline/commands/add.py
index c34eaa492..ee25591e1 100644
--- a/deluge/ui/console/cmdline/commands/add.py
+++ b/deluge/ui/console/cmdline/commands/add.py
@@ -26,25 +26,25 @@ class Command(BaseCommand):
"""Add torrents"""
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('-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'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
t_options = {}
if options.path:
- t_options["download_location"] = os.path.expanduser(options.path)
+ t_options['download_location'] = os.path.expanduser(options.path)
def on_success(result):
if not result:
- self.console.write("{!error!}Torrent was not added: Already in session")
+ self.console.write('{!error!}Torrent was not added: Already in session')
else:
- self.console.write("{!success!}Torrent added!")
+ self.console.write('{!success!}Torrent added!')
def on_fail(result):
- self.console.write("{!error!}Torrent was not added: %s" % result)
+ self.console.write('{!error!}Torrent was not added: %s' % result)
# Keep a list of deferreds to make a DeferredList
deferreds = []
@@ -52,27 +52,27 @@ class Command(BaseCommand):
if not torrent.strip():
continue
if deluge.common.is_url(torrent):
- self.console.write("{!info!}Attempting to add torrent from url: %s" % 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))
elif deluge.common.is_magnet(torrent):
- self.console.write("{!info!}Attempting to add torrent from magnet uri: %s" % 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))
else:
# Just a file
- if urlparse(torrent).scheme == "file":
+ if urlparse(torrent).scheme == 'file':
torrent = url2pathname(urlparse(torrent).path)
path = os.path.abspath(os.path.expanduser(torrent))
if not os.path.exists(path):
self.console.write("{!error!}%s doesn't exist!" % path)
continue
if not os.path.isfile(path):
- self.console.write("{!error!}This is a directory!")
+ self.console.write('{!error!}This is a directory!')
continue
- self.console.write("{!info!}Attempting to add torrent: %s" % path)
+ self.console.write('{!info!}Attempting to add torrent: %s' % path)
filename = os.path.split(path)[-1]
- with open(path, "rb") as _file:
+ with open(path, 'rb') as _file:
filedump = base64.encodestring(_file.read())
deferreds.append(client.core.add_torrent_file(filename, filedump, t_options).addCallback(
on_success).addErrback(on_fail))
@@ -80,4 +80,4 @@ class Command(BaseCommand):
return defer.DeferredList(deferreds)
def complete(self, line):
- return component.get("ConsoleUI").tab_complete_path(line, ext=".torrent", sort="date")
+ return component.get('ConsoleUI').tab_complete_path(line, ext='.torrent', sort='date')
diff --git a/deluge/ui/console/cmdline/commands/cache.py b/deluge/ui/console/cmdline/commands/cache.py
index 158cfca5d..abcce523c 100644
--- a/deluge/ui/console/cmdline/commands/cache.py
+++ b/deluge/ui/console/cmdline/commands/cache.py
@@ -17,11 +17,11 @@ class Command(BaseCommand):
"""Show information about the disk cache"""
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
def on_cache_status(status):
for key, value in status.items():
- self.console.write("{!info!}%s: {!input!}%s" % (key, value))
+ self.console.write('{!info!}%s: {!input!}%s' % (key, value))
d = client.core.get_cache_status()
d.addCallback(on_cache_status)
diff --git a/deluge/ui/console/cmdline/commands/config.py b/deluge/ui/console/cmdline/commands/config.py
index 48333575e..3ac0b94a8 100644
--- a/deluge/ui/console/cmdline/commands/config.py
+++ b/deluge/ui/console/cmdline/commands/config.py
@@ -23,18 +23,18 @@ log = logging.getLogger(__name__)
def atom(src, token):
"""taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm"""
- if token[1] == "(":
+ if token[1] == '(':
out = []
token = next(src)
- while token[1] != ")":
+ while token[1] != ')':
out.append(atom(src, token))
token = next(src)
- if token[1] == ",":
+ if token[1] == ',':
token = next(src)
return tuple(out)
- elif token[0] is tokenize.NUMBER or token[1] == "-":
+ elif token[0] is tokenize.NUMBER or token[1] == '-':
try:
- if token[1] == "-":
+ if token[1] == '-':
return int(token[-1], 0)
else:
return int(token[1], 0)
@@ -43,14 +43,14 @@ def atom(src, token):
return float(token[-1])
except ValueError:
return str(token[-1])
- elif token[1].lower() == "true":
+ elif token[1].lower() == 'true':
return True
- elif token[1].lower() == "false":
+ elif token[1].lower() == 'false':
return False
- elif token[0] is tokenize.STRING or token[1] == "/":
- return token[-1].decode("string-escape")
+ elif token[0] is tokenize.STRING or token[1] == '/':
+ return token[-1].decode('string-escape')
- raise SyntaxError("malformed expression (%s)" % token[1])
+ raise SyntaxError('malformed expression (%s)' % token[1])
def simple_eval(source):
@@ -66,17 +66,17 @@ def simple_eval(source):
class Command(BaseCommand):
"""Show and set configuration values"""
- usage = _("Usage: config [--set <key> <value>] [<key> [<key>...] ]")
+ usage = _('Usage: config [--set <key> <value>] [<key> [<key>...] ]')
def add_arguments(self, parser):
- 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"))
- get_group = parser.add_argument_group("getting values")
- get_group.add_argument("keys", metavar="<keys>", nargs="*", help=_("one or more keys separated by space"))
+ 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'))
+ get_group = parser.add_argument_group('getting values')
+ get_group.add_argument('keys', metavar='<keys>', nargs='*', help=_('one or more keys separated by space'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
if options.set:
return self._set_config(options)
else:
@@ -85,11 +85,11 @@ class Command(BaseCommand):
def _get_config(self, options):
def _on_get_config(config):
keys = sorted(config.keys())
- s = ""
+ s = ''
for key in keys:
if key not in options.values:
continue
- color = "{!white,black,bold!}"
+ color = '{!white,black,bold!}'
value = config[key]
try:
color = colors.type_color[type(value)]
@@ -102,23 +102,23 @@ class Command(BaseCommand):
value = pprint.pformat(value, 2, 80)
new_value = []
for line in value.splitlines():
- new_value.append("%s%s" % (color, line))
- value = "\n".join(new_value)
+ new_value.append('%s%s' % (color, line))
+ value = '\n'.join(new_value)
- s += "%s: %s%s\n" % (key, color, value)
+ s += '%s: %s%s\n' % (key, color, value)
self.console.write(s.strip())
return client.core.get_config().addCallback(_on_get_config)
def _set_config(self, options):
- config = component.get("CoreConfig")
+ config = component.get('CoreConfig')
key = options.set
- val = " ".join(options.values)
+ val = ' '.join(options.values)
try:
val = simple_eval(val)
except SyntaxError as ex:
- self.console.write("{!error!}%s" % ex)
+ self.console.write('{!error!}%s' % ex)
return
if key not in config.keys():
@@ -129,14 +129,14 @@ class Command(BaseCommand):
try:
val = type(config[key])(val)
except TypeError:
- self.config.write("{!error!}Configuration value provided has incorrect type.")
+ self.config.write('{!error!}Configuration value provided has incorrect type.')
return
def on_set_config(result):
- self.console.write("{!success!}Configuration value successfully updated.")
+ self.console.write('{!success!}Configuration value successfully updated.')
self.console.write("Setting '%s' to '%s'" % (key, val))
return client.core.set_config({key: val}).addCallback(on_set_config)
def complete(self, text):
- return [k for k in component.get("CoreConfig").keys() if k.startswith(text)]
+ return [k for k in component.get('CoreConfig').keys() if k.startswith(text)]
diff --git a/deluge/ui/console/cmdline/commands/connect.py b/deluge/ui/console/cmdline/commands/connect.py
index 77fbf0bbc..d7d26e0c7 100644
--- a/deluge/ui/console/cmdline/commands/connect.py
+++ b/deluge/ui/console/cmdline/commands/connect.py
@@ -21,23 +21,23 @@ log = logging.getLogger(__name__)
class Command(BaseCommand):
"""Connect to a new deluge server."""
- usage = _("Usage: connect <host[:port]> [<username>] [<password>]")
+ usage = _('Usage: connect <host[:port]> [<username>] [<password>]')
def add_arguments(self, parser):
- parser.add_argument("host", help=_("Daemon host and port"), metavar="<host[:port]>")
- parser.add_argument("username", help=_("Username"), metavar="<username>", nargs="?", default="")
- parser.add_argument("password", help=_("Password"), metavar="<password>", nargs="?", default="")
+ parser.add_argument('host', help=_('Daemon host and port'), metavar='<host[:port]>')
+ parser.add_argument('username', help=_('Username'), metavar='<username>', nargs='?', default='')
+ parser.add_argument('password', help=_('Password'), metavar='<password>', nargs='?', default='')
def add_parser(self, subparsers):
- parser = subparsers.add_parser(self.name, help=self.__doc__, description=self.__doc__, prog="connect")
+ parser = subparsers.add_parser(self.name, help=self.__doc__, description=self.__doc__, prog='connect')
self.add_arguments(parser)
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
host = options.host
try:
- host, port = host.split(":")
+ host, port = host.split(':')
port = int(port)
except ValueError:
port = 58846
@@ -47,7 +47,7 @@ class Command(BaseCommand):
def on_connect(result):
if self.console.interactive:
- self.console.write("{!success!}Connected to %s:%s!" % (host, port))
+ self.console.write('{!success!}Connected to %s:%s!' % (host, port))
return component.start()
def on_connect_fail(result):
@@ -55,7 +55,7 @@ class Command(BaseCommand):
msg = result.value.exception_msg
except AttributeError:
msg = result.value.message
- self.console.write("{!error!}Failed to connect to %s:%s with reason: %s" % (host, port, msg))
+ self.console.write('{!error!}Failed to connect to %s:%s with reason: %s' % (host, port, msg))
return result
d.addCallbacks(on_connect, on_connect_fail)
diff --git a/deluge/ui/console/cmdline/commands/debug.py b/deluge/ui/console/cmdline/commands/debug.py
index 04a3f47ad..b8647abc1 100644
--- a/deluge/ui/console/cmdline/commands/debug.py
+++ b/deluge/ui/console/cmdline/commands/debug.py
@@ -20,17 +20,17 @@ class Command(BaseCommand):
"""Enable and disable debugging"""
def add_arguments(self, parser):
- parser.add_argument("state", metavar="<on|off>", choices=["on", "off"], help=_("The new state"))
+ parser.add_argument('state', metavar='<on|off>', choices=['on', 'off'], help=_('The new state'))
def handle(self, options):
- if options.state == "on":
- deluge.log.set_logger_level("debug")
- elif options.state == "off":
- deluge.log.set_logger_level("error")
+ if options.state == 'on':
+ deluge.log.set_logger_level('debug')
+ elif options.state == 'off':
+ deluge.log.set_logger_level('error')
else:
- component.get("ConsoleUI").write("{!error!}%s" % self.usage)
+ component.get('ConsoleUI').write('{!error!}%s' % self.usage)
return defer.succeed(True)
def complete(self, text):
- return [x for x in ["on", "off"] if x.startswith(text)]
+ return [x for x in ['on', 'off'] if x.startswith(text)]
diff --git a/deluge/ui/console/cmdline/commands/gui.py b/deluge/ui/console/cmdline/commands/gui.py
index d4726732a..3b91a22a6 100644
--- a/deluge/ui/console/cmdline/commands/gui.py
+++ b/deluge/ui/console/cmdline/commands/gui.py
@@ -21,7 +21,7 @@ class Command(BaseCommand):
interactive_only = True
def handle(self, options):
- console = component.get("ConsoleUI")
- at = console.set_mode("TorrentList")
+ console = component.get('ConsoleUI')
+ at = console.set_mode('TorrentList')
at.go_top = True
at.resume()
diff --git a/deluge/ui/console/cmdline/commands/halt.py b/deluge/ui/console/cmdline/commands/halt.py
index 75bade966..471af73ad 100644
--- a/deluge/ui/console/cmdline/commands/halt.py
+++ b/deluge/ui/console/cmdline/commands/halt.py
@@ -15,15 +15,15 @@ from . import BaseCommand
class Command(BaseCommand):
- "Shutdown the deluge server"
+ 'Shutdown the deluge server'
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
def on_shutdown(result):
- self.console.write("{!success!}Daemon was shutdown")
+ self.console.write('{!success!}Daemon was shutdown')
def on_shutdown_fail(reason):
- self.console.write("{!error!}Unable to shutdown daemon: %s" % reason)
+ self.console.write('{!error!}Unable to shutdown daemon: %s' % reason)
return client.daemon.shutdown().addCallback(on_shutdown).addErrback(on_shutdown_fail)
diff --git a/deluge/ui/console/cmdline/commands/help.py b/deluge/ui/console/cmdline/commands/help.py
index 94690ff68..1e75a3cb3 100644
--- a/deluge/ui/console/cmdline/commands/help.py
+++ b/deluge/ui/console/cmdline/commands/help.py
@@ -23,10 +23,10 @@ class Command(BaseCommand):
"""displays help on other commands"""
def add_arguments(self, parser):
- parser.add_argument("commands", metavar="<command>", nargs="*", help=_("One or more commands"))
+ parser.add_argument('commands', metavar='<command>', nargs='*', help=_('One or more commands'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
self._commands = self.console._commands
deferred = defer.succeed(True)
if options.commands:
@@ -34,30 +34,30 @@ class Command(BaseCommand):
try:
cmd = self._commands[arg]
except KeyError:
- self.console.write("{!error!}Unknown command %s" % arg)
+ self.console.write('{!error!}Unknown command %s' % arg)
continue
try:
parser = cmd.create_parser()
self.console.write(parser.format_help())
except AttributeError:
- self.console.write(cmd.__doc__ or "No help for this command")
- self.console.write(" ")
+ self.console.write(cmd.__doc__ or 'No help for this command')
+ self.console.write(' ')
else:
self.console.set_batch_write(True)
- cmds_doc = ""
+ cmds_doc = ''
for cmd in sorted(self._commands):
if cmd in self._commands[cmd].aliases:
continue
parser = self._commands[cmd].create_parser()
- cmd_doc = "{!info!}" + "%-9s" % self._commands[cmd].name_with_alias + "{!input!} - "\
- + self._commands[cmd].__doc__ + "\n " + parser.format_usage() or ''
+ cmd_doc = '{!info!}' + '%-9s' % self._commands[cmd].name_with_alias + '{!input!} - '\
+ + self._commands[cmd].__doc__ + '\n ' + parser.format_usage() or ''
cmds_doc += parser.formatter.format_colors(cmd_doc)
self.console.write(cmds_doc)
- self.console.write(" ")
+ self.console.write(' ')
self.console.write("For help on a specific command, use '<command> --help'")
self.console.set_batch_write(False)
return deferred
def complete(self, line):
- return [x for x in component.get("ConsoleUI")._commands if x.startswith(line)]
+ return [x for x in component.get('ConsoleUI')._commands if x.startswith(line)]
diff --git a/deluge/ui/console/cmdline/commands/info.py b/deluge/ui/console/cmdline/commands/info.py
index b71f7d2e8..d6fd21fcd 100644
--- a/deluge/ui/console/cmdline/commands/info.py
+++ b/deluge/ui/console/cmdline/commands/info.py
@@ -24,38 +24,38 @@ strwidth = format_utils.strwidth
STATUS_KEYS = [
- "state",
- "download_location",
- "tracker_host",
- "tracker_status",
- "next_announce",
- "name",
- "total_size",
- "progress",
- "num_seeds",
- "total_seeds",
- "num_peers",
- "total_peers",
- "eta",
- "download_payload_rate",
- "upload_payload_rate",
- "ratio",
- "distributed_copies",
- "num_pieces",
- "piece_length",
- "total_done",
- "files",
- "file_priorities",
- "file_progress",
- "peers",
- "is_seed",
- "is_finished",
- "active_time",
- "seeding_time"
+ 'state',
+ 'download_location',
+ 'tracker_host',
+ 'tracker_status',
+ 'next_announce',
+ 'name',
+ 'total_size',
+ 'progress',
+ 'num_seeds',
+ 'total_seeds',
+ 'num_peers',
+ 'total_peers',
+ 'eta',
+ 'download_payload_rate',
+ 'upload_payload_rate',
+ 'ratio',
+ 'distributed_copies',
+ 'num_pieces',
+ 'piece_length',
+ 'total_done',
+ 'files',
+ 'file_priorities',
+ 'file_progress',
+ 'peers',
+ 'is_seed',
+ 'is_finished',
+ 'active_time',
+ 'seeding_time'
]
# Add filter specific state to torrent states
-STATES = ["Active"] + common.TORRENT_STATE
+STATES = ['Active'] + common.TORRENT_STATE
def format_progressbar(progress, width):
@@ -69,11 +69,11 @@ def format_progressbar(progress, width):
"""
w = width - 2 # we use a [] for the beginning and end
- s = "["
+ s = '['
p = int(round((progress / 100) * w))
- s += "#" * p
- s += "-" * (w - p)
- s += "]"
+ s += '#' * p
+ s += '-' * (w - p)
+ s += ']'
return s
@@ -84,13 +84,13 @@ def format_time(seconds):
minutes = minutes - hours * 60
days = hours // 24
hours = hours - days * 24
- return "%d days %02d:%02d:%02d" % (days, hours, minutes, seconds)
+ return '%d days %02d:%02d:%02d' % (days, hours, minutes, seconds)
class Command(BaseCommand):
"""Show information about the torrents"""
- sort_help = "sort items. Possible keys: " + ", ".join(STATUS_KEYS)
+ sort_help = 'sort items. Possible keys: ' + ', '.join(STATUS_KEYS)
epilog = """
You can give the first few characters of a torrent-id to identify the torrent.
@@ -103,17 +103,17 @@ 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("--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('-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'))
def add_subparser(self, subparsers):
parser = subparsers.add_parser(self.name, prog=self.name, help=self.__doc__,
@@ -121,7 +121,7 @@ class Command(BaseCommand):
self.add_arguments(parser)
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
# Compile a list of torrent_ids to request the status of
torrent_ids = []
@@ -129,7 +129,7 @@ class Command(BaseCommand):
for t_id in options.torrent_ids:
torrent_ids.extend(self.console.match_torrent(t_id))
else:
- torrent_ids.extend(self.console.match_torrent(""))
+ torrent_ids.extend(self.console.match_torrent(''))
def on_torrents_status(status):
# Print out the information for each torrent
@@ -139,28 +139,28 @@ class Command(BaseCommand):
sort_key = options.sort_rev
sort_reverse = True
if not sort_key:
- sort_key = "name"
+ sort_key = 'name'
sort_reverse = False
if sort_key not in STATUS_KEYS:
- self.console.write("")
- self.console.write("{!error!}Unknown sort key: " + sort_key + ", will sort on name")
- sort_key = "name"
+ self.console.write('')
+ self.console.write('{!error!}Unknown sort key: ' + sort_key + ', will sort on name')
+ sort_key = 'name'
sort_reverse = False
for key, value in sorted(status.items(), key=lambda x: x[1].get(sort_key), reverse=sort_reverse):
self.show_info(key, status[key], options.verbose, options.detailed)
def on_torrents_status_fail(reason):
- self.console.write("{!error!}Error getting torrent info: %s" % reason)
+ self.console.write('{!error!}Error getting torrent info: %s' % reason)
- status_dict = {"id": torrent_ids}
+ status_dict = {'id': torrent_ids}
if options.state:
options.state = options.state.capitalize()
if options.state in STATES:
status_dict.state = options.state
else:
- self.console.write("Invalid state: %s" % options.state)
- self.console.write("Possible values are: %s." % (", ".join(STATES)))
+ self.console.write('Invalid state: %s' % options.state)
+ self.console.write('Possible values are: %s.' % (', '.join(STATES)))
return
d = client.core.get_torrents_status(status_dict, STATUS_KEYS)
@@ -171,72 +171,72 @@ class Command(BaseCommand):
def show_file_info(self, torrent_id, status):
spaces_per_level = 2
- if hasattr(self.console, "screen"):
+ if hasattr(self.console, 'screen'):
cols = self.console.screen.cols
else:
cols = 80
prevpath = []
- for index, torrent_file in enumerate(status["files"]):
- filename = torrent_file["path"].split(dirsep)[-1]
- filepath = torrent_file["path"].split(dirsep)[:-1]
+ for index, torrent_file in enumerate(status['files']):
+ filename = torrent_file['path'].split(dirsep)[-1]
+ filepath = torrent_file['path'].split(dirsep)[:-1]
for depth, subdir in enumerate(filepath):
- indent = " " * depth * spaces_per_level
+ indent = ' ' * depth * spaces_per_level
if depth >= len(prevpath):
- self.console.write("%s{!cyan!}%s" % (indent, subdir))
+ self.console.write('%s{!cyan!}%s' % (indent, subdir))
elif subdir != prevpath[depth]:
- self.console.write("%s{!cyan!}%s" % (indent, subdir))
+ self.console.write('%s{!cyan!}%s' % (indent, subdir))
depth = len(filepath)
- indent = " " * depth * spaces_per_level
+ indent = ' ' * depth * spaces_per_level
col_filename = indent + filename
- col_size = " ({!cyan!}%s{!input!})" % common.fsize(torrent_file["size"])
- col_progress = " {!input!}%.2f%%" % (status["file_progress"][index] * 100)
+ col_size = ' ({!cyan!}%s{!input!})' % common.fsize(torrent_file['size'])
+ col_progress = ' {!input!}%.2f%%' % (status['file_progress'][index] * 100)
- col_priority = " {!info!}Priority: "
+ col_priority = ' {!info!}Priority: '
- file_priority = common.FILE_PRIORITY[status["file_priorities"][index]].replace("Priority", "")
- if status["file_progress"][index] != 1.0:
- if file_priority == "Do Not Download":
- col_priority += "{!error!}"
+ file_priority = common.FILE_PRIORITY[status['file_priorities'][index]].replace('Priority', '')
+ if status['file_progress'][index] != 1.0:
+ if file_priority == 'Do Not Download':
+ col_priority += '{!error!}'
else:
- col_priority += "{!success!}"
+ col_priority += '{!success!}'
else:
- col_priority += "{!input!}"
+ col_priority += '{!input!}'
col_priority += file_priority
def tlen(string):
return strwidth(format_utils.remove_formatting(string))
if not isinstance(col_filename, unicode):
- col_filename = unicode(col_filename, "utf-8")
+ col_filename = unicode(col_filename, 'utf-8')
col_all_info = col_size + col_progress + col_priority
# Check how much space we've got left after writing all the info
space_left = cols - tlen(col_all_info)
# And how much we will potentially have with the longest possible column
- maxlen_space_left = cols - tlen(" (1000.0 MiB) 100.00% Priority: Do Not Download")
+ maxlen_space_left = cols - tlen(' (1000.0 MiB) 100.00% Priority: Do Not Download')
if maxlen_space_left > tlen(col_filename) + 1:
# If there is enough space, pad it all nicely
- col_all_info = ""
- col_all_info += " ("
- spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size)
- col_all_info += " " * spaces_to_add
+ col_all_info = ''
+ col_all_info += ' ('
+ spaces_to_add = tlen(' (1000.0 MiB)') - tlen(col_size)
+ col_all_info += ' ' * spaces_to_add
col_all_info += col_size[2:]
- spaces_to_add = tlen(" 100.00%") - tlen(col_progress)
- col_all_info += " " * spaces_to_add
+ spaces_to_add = tlen(' 100.00%') - tlen(col_progress)
+ col_all_info += ' ' * spaces_to_add
col_all_info += col_progress
- spaces_to_add = tlen(" Priority: Do Not Download") - tlen(col_priority)
+ spaces_to_add = tlen(' Priority: Do Not Download') - tlen(col_priority)
col_all_info += col_priority
- col_all_info += " " * spaces_to_add
+ col_all_info += ' ' * spaces_to_add
# And remember to put it to the left!
- col_filename = format_utils.pad_string(col_filename, maxlen_space_left - 2, side="right")
+ col_filename = format_utils.pad_string(col_filename, maxlen_space_left - 2, side='right')
elif space_left > tlen(col_filename) + 1:
# If there is enough space, put the info to the right
- col_filename = format_utils.pad_string(col_filename, space_left - 2, side="right")
+ col_filename = format_utils.pad_string(col_filename, space_left - 2, side='right')
else:
# And if there is not, shorten the name
col_filename = format_utils.trim_string(col_filename, space_left, True)
@@ -245,38 +245,38 @@ class Command(BaseCommand):
prevpath = filepath
def show_peer_info(self, torrent_id, status):
- if len(status["peers"]) == 0:
- self.console.write(" None")
+ if len(status['peers']) == 0:
+ self.console.write(' None')
else:
- s = ""
- for peer in status["peers"]:
- if peer["seed"]:
- s += "%sSeed\t{!input!}" % colors.state_color["Seeding"]
+ s = ''
+ for peer in status['peers']:
+ if peer['seed']:
+ s += '%sSeed\t{!input!}' % colors.state_color['Seeding']
else:
- s += "%sPeer\t{!input!}" % colors.state_color["Downloading"]
+ s += '%sPeer\t{!input!}' % colors.state_color['Downloading']
- s += peer["country"] + "\t"
+ s += peer['country'] + '\t'
- if peer["ip"].count(":") == 1:
+ if peer['ip'].count(':') == 1:
# IPv4
- s += peer["ip"]
+ s += peer['ip']
else:
# IPv6
- s += "[%s]:%s" % (":".join(peer["ip"].split(":")[:-1]), peer["ip"].split(":")[-1])
+ s += '[%s]:%s' % (':'.join(peer['ip'].split(':')[:-1]), peer['ip'].split(':')[-1])
- c = peer["client"]
- s += "\t" + c
+ c = peer['client']
+ s += '\t' + c
if len(c) < 16:
- s += "\t\t"
+ s += '\t\t'
else:
- s += "\t"
- s += "%s%s\t%s%s" % (
- colors.state_color["Seeding"],
- common.fspeed(peer["up_speed"]),
- colors.state_color["Downloading"],
- common.fspeed(peer["down_speed"]))
- s += "\n"
+ s += '\t'
+ s += '%s%s\t%s%s' % (
+ colors.state_color['Seeding'],
+ common.fspeed(peer['up_speed']),
+ colors.state_color['Downloading'],
+ common.fspeed(peer['down_speed']))
+ s += '\n'
self.console.write(s[:-1])
@@ -288,82 +288,82 @@ class Command(BaseCommand):
"""
self.console.set_batch_write(True)
- if hasattr(self.console, "screen"):
+ if hasattr(self.console, 'screen'):
cols = self.console.screen.cols
else:
cols = 80
if verbose or detailed:
- self.console.write(" ")
- self.console.write("{!info!}Name: {!input!}%s" % (status["name"]))
- self.console.write("{!info!}ID: {!input!}%s" % (torrent_id))
- s = "{!info!}State: %s%s" % (colors.state_color[status["state"]], status["state"])
+ self.console.write(' ')
+ self.console.write('{!info!}Name: {!input!}%s' % (status['name']))
+ self.console.write('{!info!}ID: {!input!}%s' % (torrent_id))
+ s = '{!info!}State: %s%s' % (colors.state_color[status['state']], status['state'])
# Only show speed if active
- if status["state"] in ("Seeding", "Downloading"):
- if status["state"] != "Seeding":
- s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(status["download_payload_rate"])
- s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(status["upload_payload_rate"])
+ if status['state'] in ('Seeding', 'Downloading'):
+ if status['state'] != 'Seeding':
+ s += ' {!info!}Down Speed: {!input!}%s' % common.fspeed(status['download_payload_rate'])
+ s += ' {!info!}Up Speed: {!input!}%s' % common.fspeed(status['upload_payload_rate'])
- if common.ftime(status["eta"]):
- s += " {!info!}ETA: {!input!}%s" % common.ftime(status["eta"])
+ if common.ftime(status['eta']):
+ s += ' {!info!}ETA: {!input!}%s' % common.ftime(status['eta'])
self.console.write(s)
- if status["state"] in ("Seeding", "Downloading", "Queued"):
- s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"], status["total_seeds"])
- s += " {!info!}Peers: {!input!}%s (%s)" % (status["num_peers"], status["total_peers"])
- s += " {!info!}Availability: {!input!}%.2f" % status["distributed_copies"]
+ if status['state'] in ('Seeding', 'Downloading', 'Queued'):
+ s = '{!info!}Seeds: {!input!}%s (%s)' % (status['num_seeds'], status['total_seeds'])
+ s += ' {!info!}Peers: {!input!}%s (%s)' % (status['num_peers'], status['total_peers'])
+ s += ' {!info!}Availability: {!input!}%.2f' % status['distributed_copies']
self.console.write(s)
- total_done = common.fsize(status["total_done"])
- total_size = common.fsize(status["total_size"])
+ total_done = common.fsize(status['total_done'])
+ total_size = common.fsize(status['total_size'])
if total_done == total_size:
- s = "{!info!}Size: {!input!}%s" % (total_size)
+ s = '{!info!}Size: {!input!}%s' % (total_size)
else:
- s = "{!info!}Size: {!input!}%s/%s" % (total_done, total_size)
- s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"]
- s += " {!info!}Uploaded: {!input!}%s" % common.fsize(status["ratio"] * status["total_done"])
+ s = '{!info!}Size: {!input!}%s/%s' % (total_done, total_size)
+ s += ' {!info!}Ratio: {!input!}%.3f' % status['ratio']
+ s += ' {!info!}Uploaded: {!input!}%s' % common.fsize(status['ratio'] * status['total_done'])
self.console.write(s)
- s = "{!info!}Seed time: {!input!}%s" % format_time(status["seeding_time"])
- s += " {!info!}Active: {!input!}%s" % format_time(status["active_time"])
+ s = '{!info!}Seed time: {!input!}%s' % format_time(status['seeding_time'])
+ s += ' {!info!}Active: {!input!}%s' % format_time(status['active_time'])
self.console.write(s)
- s = "{!info!}Tracker: {!input!}%s" % status["tracker_host"]
+ s = '{!info!}Tracker: {!input!}%s' % status['tracker_host']
self.console.write(s)
- self.console.write("{!info!}Tracker status: {!input!}%s" % status["tracker_status"])
+ self.console.write('{!info!}Tracker status: {!input!}%s' % status['tracker_status'])
- if not status["is_finished"]:
- pbar = format_progressbar(status["progress"], cols - (13 + len("%.2f%%" % status["progress"])))
- s = "{!info!}Progress: {!input!}%.2f%% %s" % (status["progress"], pbar)
+ if not status['is_finished']:
+ pbar = format_progressbar(status['progress'], cols - (13 + len('%.2f%%' % status['progress'])))
+ s = '{!info!}Progress: {!input!}%.2f%% %s' % (status['progress'], pbar)
self.console.write(s)
- s = "{!info!}Download Folder: {!input!}%s" % status["download_location"]
+ s = '{!info!}Download Folder: {!input!}%s' % status['download_location']
self.console.write(s)
if detailed:
- self.console.write("{!info!}Files in torrent")
+ self.console.write('{!info!}Files in torrent')
self.show_file_info(torrent_id, status)
- self.console.write("{!info!}Connected peers")
+ self.console.write('{!info!}Connected peers')
self.show_peer_info(torrent_id, status)
else:
- self.console.write(" ")
- up_color = colors.state_color["Seeding"]
- down_color = colors.state_color["Downloading"]
+ self.console.write(' ')
+ up_color = colors.state_color['Seeding']
+ down_color = colors.state_color['Downloading']
- s = "%s%s" % (colors.state_color[status["state"]], "[" + status["state"][0] + "]")
+ s = '%s%s' % (colors.state_color[status['state']], '[' + status['state'][0] + ']')
- s += " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ")
- s += " {!input!}%s" % (status["name"])
+ s += ' {!info!}' + ('%.2f%%' % status['progress']).ljust(7, ' ')
+ s += ' {!input!}%s' % (status['name'])
# Shorten the ID if it's necessary. Pretty hacky
# I _REALLY_ should make a nice function for it that can partition and shorten stuff
- space_left = cols - strwidth("[s] 100.00% " + status["name"] + " " * 3) - 2
+ space_left = cols - strwidth('[s] 100.00% ' + status['name'] + ' ' * 3) - 2
if space_left >= len(torrent_id) - 2:
# There's enough space, print it
- s += " {!cyan!}%s" % torrent_id
+ s += ' {!cyan!}%s' % torrent_id
else:
# Shorten the ID
a = space_left * 2 // 3
@@ -376,31 +376,31 @@ class Command(BaseCommand):
b = 0
if a > 8:
# Print the shortened ID
- s += " {!cyan!}%s" % (torrent_id[0:a] + ".." + torrent_id[-b - 1:-1])
+ s += ' {!cyan!}%s' % (torrent_id[0:a] + '..' + torrent_id[-b - 1:-1])
else:
# It has wrapped over to the second row anyway
- s += " {!cyan!}%s" % torrent_id
+ s += ' {!cyan!}%s' % torrent_id
self.console.write(s)
- dl_info = "{!info!}DL: {!input!}"
- dl_info += "%s" % common.fsize(status["total_done"])
- if status["total_done"] != status["total_size"]:
- dl_info += "/%s" % common.fsize(status["total_size"])
- if status["download_payload_rate"] > 0:
- dl_info += " @ %s%s" % (down_color, common.fspeed(status["download_payload_rate"]))
+ dl_info = '{!info!}DL: {!input!}'
+ dl_info += '%s' % common.fsize(status['total_done'])
+ if status['total_done'] != status['total_size']:
+ dl_info += '/%s' % common.fsize(status['total_size'])
+ if status['download_payload_rate'] > 0:
+ dl_info += ' @ %s%s' % (down_color, common.fspeed(status['download_payload_rate']))
- ul_info = " {!info!}UL: {!input!}"
- ul_info += "%s" % common.fsize(status["ratio"] * status["total_done"])
- if status["upload_payload_rate"] > 0:
- ul_info += " @ %s%s" % (up_color, common.fspeed(status["upload_payload_rate"]))
+ ul_info = ' {!info!}UL: {!input!}'
+ ul_info += '%s' % common.fsize(status['ratio'] * status['total_done'])
+ if status['upload_payload_rate'] > 0:
+ ul_info += ' @ %s%s' % (up_color, common.fspeed(status['upload_payload_rate']))
- eta = ""
- if common.ftime(status["eta"]):
- eta = " {!info!}ETA: {!magenta!}%s" % common.ftime(status["eta"])
+ eta = ''
+ if common.ftime(status['eta']):
+ eta = ' {!info!}ETA: {!magenta!}%s' % common.ftime(status['eta'])
- self.console.write(" " + dl_info + ul_info + eta)
+ self.console.write(' ' + dl_info + ul_info + eta)
self.console.set_batch_write(False)
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/manage.py b/deluge/ui/console/cmdline/commands/manage.py
index bc5a203ea..9ee9719df 100644
--- a/deluge/ui/console/cmdline/commands/manage.py
+++ b/deluge/ui/console/cmdline/commands/manage.py
@@ -20,37 +20,37 @@ from . import BaseCommand
log = logging.getLogger(__name__)
torrent_options = {
- "max_download_speed": float,
- "max_upload_speed": float,
- "max_connections": int,
- "max_upload_slots": int,
- "private": bool,
- "prioritize_first_last": bool,
- "is_auto_managed": bool,
- "stop_at_ratio": bool,
- "stop_ratio": float,
- "remove_at_ratio": bool,
- "move_completed": bool,
- "move_completed_path": str
+ 'max_download_speed': float,
+ 'max_upload_speed': float,
+ 'max_connections': int,
+ 'max_upload_slots': int,
+ 'private': bool,
+ 'prioritize_first_last': bool,
+ 'is_auto_managed': bool,
+ 'stop_at_ratio': bool,
+ 'stop_ratio': float,
+ 'remove_at_ratio': bool,
+ 'move_completed': bool,
+ 'move_completed_path': str
}
class Command(BaseCommand):
"""Show and manage per-torrent options"""
- usage = _("Usage: manage <torrent-id> [--set <key> <value>] [<key> [<key>...] ]")
+ 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"))
- 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"))
- get_group = parser.add_argument_group("getting values")
- get_group.add_argument("keys", metavar="<keys>", nargs="*", help=_("one or more keys separated by space"))
+ 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'))
+ get_group = parser.add_argument_group('getting values')
+ get_group.add_argument('keys', metavar='<keys>', nargs='*', help=_('one or more keys separated by space'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
if options.set:
return self._set_option(options)
else:
@@ -83,14 +83,14 @@ class Command(BaseCommand):
request_options = [opt for opt in torrent_options.keys()]
request_options.append('name')
- d = client.core.get_torrents_status({"id": torrent_ids}, request_options)
+ d = client.core.get_torrents_status({'id': torrent_ids}, request_options)
d.addCallbacks(on_torrents_status, on_torrents_status_fail)
return d
def _set_option(self, options):
deferred = defer.Deferred()
key = options.set
- val = " " .join(options.values)
+ val = ' ' .join(options.values)
torrent_ids = self.console.match_torrent(options.torrent)
if key not in torrent_options:
@@ -100,13 +100,13 @@ class Command(BaseCommand):
val = torrent_options[key](val)
def on_set_config(result):
- self.console.write("{!success!}Torrent option successfully updated.")
+ self.console.write('{!success!}Torrent option successfully updated.')
deferred.callback(True)
- self.console.write("Setting %s to %s for torrents %s.." % (key, val, torrent_ids))
+ self.console.write('Setting %s to %s for torrents %s..' % (key, val, torrent_ids))
client.core.set_torrent_options(torrent_ids, {key: val}).addCallback(on_set_config)
return deferred
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/move.py b/deluge/ui/console/cmdline/commands/move.py
index 5e1b1715c..f04523258 100644
--- a/deluge/ui/console/cmdline/commands/move.py
+++ b/deluge/ui/console/cmdline/commands/move.py
@@ -22,14 +22,14 @@ class Command(BaseCommand):
"""Move torrents' storage location"""
def add_arguments(self, parser):
- parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", help=_("One or more torrent ids"))
- parser.add_argument("path", metavar="<path>", help=_("The path to move the torrents to"))
+ parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids'))
+ parser.add_argument('path', metavar='<path>', help=_('The path to move the torrents to'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
if os.path.exists(options.path) and not os.path.isdir(options.path):
- self.console.write("{!error!}Cannot Move Download Folder: %s exists and is not a directory" % options.path)
+ self.console.write('{!error!}Cannot Move Download Folder: %s exists and is not a directory' % options.path)
return
ids = []
@@ -40,7 +40,7 @@ class Command(BaseCommand):
names.append(self.console.get_torrent_name(tid))
def on_move(res):
- msg = "Moved \"%s\" to %s" % (", ".join(names), options.path)
+ msg = "Moved \"%s\" to %s" % (', '.join(names), options.path)
self.console.write(msg)
log.info(msg)
@@ -58,11 +58,11 @@ class Command(BaseCommand):
# ret.extend(os.listdir(line))
for f in os.listdir(line):
# Skip hidden
- if f.startswith("."):
+ if f.startswith('.'):
continue
f = os.path.join(line, f)
if os.path.isdir(f):
- f += "/"
+ f += '/'
ret.append(f)
else:
# This is a file, but we could be looking for another file that
@@ -80,6 +80,6 @@ class Command(BaseCommand):
p = os.path.join(os.path.dirname(line), f)
if os.path.isdir(p):
- p += "/"
+ p += '/'
ret.append(p)
return ret
diff --git a/deluge/ui/console/cmdline/commands/pause.py b/deluge/ui/console/cmdline/commands/pause.py
index 34d040792..24e62e2a1 100644
--- a/deluge/ui/console/cmdline/commands/pause.py
+++ b/deluge/ui/console/cmdline/commands/pause.py
@@ -16,16 +16,16 @@ from . import BaseCommand
class Command(BaseCommand):
"""Pause torrents"""
- usage = "pause [ * | <torrent-id> [<torrent-id> ...] ]"
+ usage = 'pause [ * | <torrent-id> [<torrent-id> ...] ]'
def add_arguments(self, parser):
- parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+",
+ parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
help=_("One or more torrent ids. '*' pauses all torrents"))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
- if options.torrent_ids[0] == "*":
+ if options.torrent_ids[0] == '*':
client.core.pause_session()
return
@@ -38,4 +38,4 @@ class Command(BaseCommand):
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/plugin.py b/deluge/ui/console/cmdline/commands/plugin.py
index 4b6e5ad1a..959fdcdaa 100644
--- a/deluge/ui/console/cmdline/commands/plugin.py
+++ b/deluge/ui/console/cmdline/commands/plugin.py
@@ -18,37 +18,37 @@ 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("-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("-i", "--install", help=_("Install a plugin from an .egg file"))
+ 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('-i', '--install', help=_('Install a plugin from an .egg file'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
if options.reload:
client.core.pluginmanager.rescan_plugins()
- self.console.write("{!green!}Plugin list successfully reloaded")
+ self.console.write('{!green!}Plugin list successfully reloaded')
return
elif options.list:
def on_available_plugins(result):
- self.console.write("{!info!}Available Plugins:")
+ self.console.write('{!info!}Available Plugins:')
for p in result:
- self.console.write("{!input!} " + p)
+ self.console.write('{!input!} ' + p)
return client.core.get_available_plugins().addCallback(on_available_plugins)
elif options.show:
def on_enabled_plugins(result):
- self.console.write("{!info!}Enabled Plugins:")
+ self.console.write('{!info!}Enabled Plugins:')
for p in result:
- self.console.write("{!input!} " + p)
+ self.console.write('{!input!} ' + p)
return client.core.get_enabled_plugins().addCallback(on_enabled_plugins)
@@ -82,26 +82,26 @@ class Command(BaseCommand):
filepath = options.install
if not os.path.exists(filepath):
- self.console.write("{!error!}Invalid path: %s" % filepath)
+ self.console.write('{!error!}Invalid path: %s' % filepath)
return
config_dir = deluge.configmanager.get_config_dir()
filename = os.path.split(filepath)[1]
- shutil.copyfile(filepath, os.path.join(config_dir, "plugins", filename))
+ shutil.copyfile(filepath, os.path.join(config_dir, 'plugins', filename))
client.core.rescan_plugins()
if not client.is_localhost():
# We need to send this plugin to the daemon
- with open(filepath, "rb") as _file:
+ with open(filepath, 'rb') as _file:
filedump = base64.encodestring(_file.read())
try:
client.core.upload_plugin(filename, filedump)
client.core.rescan_plugins()
except Exception:
- self.console.write("{!error!}An error occurred, plugin was not installed")
+ self.console.write('{!error!}An error occurred, plugin was not installed')
- self.console.write("{!green!}Plugin was successfully installed: %s" % filename)
+ self.console.write('{!green!}Plugin was successfully installed: %s' % filename)
def complete(self, line):
- return component.get("ConsoleUI").tab_complete_path(line, ext=".egg", sort="name", dirs_first=-1)
+ return component.get('ConsoleUI').tab_complete_path(line, ext='.egg', sort='name', dirs_first=-1)
diff --git a/deluge/ui/console/cmdline/commands/quit.py b/deluge/ui/console/cmdline/commands/quit.py
index d0f577330..374367b5e 100644
--- a/deluge/ui/console/cmdline/commands/quit.py
+++ b/deluge/ui/console/cmdline/commands/quit.py
@@ -17,7 +17,7 @@ from . import BaseCommand
class Command(BaseCommand):
"""Exit the client."""
- aliases = ["exit"]
+ aliases = ['exit']
interactive_only = True
def handle(self, options):
diff --git a/deluge/ui/console/cmdline/commands/recheck.py b/deluge/ui/console/cmdline/commands/recheck.py
index 3aaef4a03..a2f9f71e0 100644
--- a/deluge/ui/console/cmdline/commands/recheck.py
+++ b/deluge/ui/console/cmdline/commands/recheck.py
@@ -15,16 +15,16 @@ from . import BaseCommand
class Command(BaseCommand):
"""Forces a recheck of the torrent data"""
- usage = "recheck [ * | <torrent-id> [<torrent-id> ...] ]"
+ usage = 'recheck [ * | <torrent-id> [<torrent-id> ...] ]'
def add_arguments(self, parser):
- parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", help=_("One or more torrent ids"))
+ parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids'))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
- if options.torrent_ids[0] == "*":
- client.core.force_recheck(self.console.match_torrent(""))
+ if options.torrent_ids[0] == '*':
+ client.core.force_recheck(self.console.match_torrent(''))
return
torrent_ids = []
@@ -36,4 +36,4 @@ class Command(BaseCommand):
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/resume.py b/deluge/ui/console/cmdline/commands/resume.py
index 6fda7e2bb..65da8a8b8 100644
--- a/deluge/ui/console/cmdline/commands/resume.py
+++ b/deluge/ui/console/cmdline/commands/resume.py
@@ -16,16 +16,16 @@ from . import BaseCommand
class Command(BaseCommand):
"""Resume torrents"""
- usage = _("Usage: resume [ * | <torrent-id> [<torrent-id> ...] ]")
+ usage = _('Usage: resume [ * | <torrent-id> [<torrent-id> ...] ]')
def add_arguments(self, parser):
- parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+",
+ parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+',
help=_("One or more torrent ids. '*' resumes all torrents"))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
- if options.torrent_ids[0] == "*":
+ if options.torrent_ids[0] == '*':
client.core.resume_session()
return
@@ -38,4 +38,4 @@ class Command(BaseCommand):
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/rm.py b/deluge/ui/console/cmdline/commands/rm.py
index 62acb51bf..0cbda3b19 100644
--- a/deluge/ui/console/cmdline/commands/rm.py
+++ b/deluge/ui/console/cmdline/commands/rm.py
@@ -20,38 +20,38 @@ log = logging.getLogger(__name__)
class Command(BaseCommand):
"""Remove a torrent"""
- aliases = ["del"]
+ aliases = ['del']
def add_arguments(self, parser):
- parser.add_argument("--remove_data", action="store_true", default=False, help=_("remove the torrent's 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"))
+ parser.add_argument('--remove_data', action='store_true', default=False, help=_("remove the torrent's 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):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
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))
- self.console.write(_("Confirm with -c to remove the listed torrents (Count: %d)") % len(torrent_ids))
+ self.console.write('* %-50s (%s)' % (name, t_id))
+ self.console.write(_('Confirm with -c to remove the listed torrents (Count: %d)') % len(torrent_ids))
return
def on_removed_finished(errors):
if errors:
- self.console.write("Error(s) occured when trying to delete torrent(s).")
+ self.console.write('Error(s) occured when trying to delete torrent(s).')
for t_id, e_msg in errors:
- self.console.write("Error removing torrent %s : %s" % (t_id, e_msg))
+ self.console.write('Error removing torrent %s : %s' % (t_id, e_msg))
- log.info("Removing %d torrents", len(torrent_ids))
+ log.info('Removing %d torrents', len(torrent_ids))
d = client.core.remove_torrents(torrent_ids, options.remove_data)
d.addCallback(on_removed_finished)
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/cmdline/commands/status.py b/deluge/ui/console/cmdline/commands/status.py
index 915054950..9ae8df354 100644
--- a/deluge/ui/console/cmdline/commands/status.py
+++ b/deluge/ui/console/cmdline/commands/status.py
@@ -24,14 +24,14 @@ class Command(BaseCommand):
"""Shows a various status information from the daemon."""
def add_arguments(self, parser):
- parser.add_argument("-r", "--raw", action="store_true", default=False, dest="raw",
+ parser.add_argument('-r', '--raw', action='store_true', default=False, dest='raw',
help=_("Don't format upload/download rates in KiB/s "
- "(useful for scripts that want to do their own parsing)"))
- parser.add_argument("-n", "--no-torrents", action="store_false", default=True, dest="show_torrents",
+ '(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=_("Don't show torrent status (this will make the command a bit faster)"))
def handle(self, options):
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
self.status = None
self.torrents = 1 if options.show_torrents else 0
self.raw = options.raw
@@ -43,17 +43,17 @@ class Command(BaseCommand):
self.torrents = status
def on_torrents_status_fail(reason):
- log.warn("Failed to retrieve session status: %s", reason)
+ log.warn('Failed to retrieve session status: %s', reason)
self.torrents = -2
deferreds = []
- ds = client.core.get_session_status(["num_peers", "payload_upload_rate", "payload_download_rate", "dht_nodes"])
+ ds = client.core.get_session_status(['num_peers', 'payload_upload_rate', 'payload_download_rate', 'dht_nodes'])
ds.addCallback(on_session_status)
deferreds.append(ds)
if options.show_torrents:
- dt = client.core.get_torrents_status({}, ["state"])
+ dt = client.core.get_torrents_status({}, ['state'])
dt.addCallback(on_torrents_status)
dt.addErrback(on_torrents_status_fail)
deferreds.append(dt)
@@ -63,25 +63,25 @@ class Command(BaseCommand):
def print_status(self, *args):
self.console.set_batch_write(True)
if self.raw:
- self.console.write("{!info!}Total upload: %f" % self.status["payload_upload_rate"])
- self.console.write("{!info!}Total download: %f" % self.status["payload_download_rate"])
+ self.console.write('{!info!}Total upload: %f' % self.status['payload_upload_rate'])
+ self.console.write('{!info!}Total download: %f' % self.status['payload_download_rate'])
else:
- self.console.write("{!info!}Total upload: %s" % fspeed(self.status["payload_upload_rate"]))
- self.console.write("{!info!}Total download: %s" % fspeed(self.status["payload_download_rate"]))
- self.console.write("{!info!}DHT Nodes: %i" % self.status["dht_nodes"])
+ self.console.write('{!info!}Total upload: %s' % fspeed(self.status['payload_upload_rate']))
+ self.console.write('{!info!}Total download: %s' % fspeed(self.status['payload_download_rate']))
+ self.console.write('{!info!}DHT Nodes: %i' % self.status['dht_nodes'])
if isinstance(self.torrents, int):
if self.torrents == -2:
- self.console.write("{!error!}Error getting torrent info")
+ self.console.write('{!error!}Error getting torrent info')
else:
- self.console.write("{!info!}Total torrents: %i" % len(self.torrents))
+ self.console.write('{!info!}Total torrents: %i' % len(self.torrents))
state_counts = {}
for state in TORRENT_STATE:
state_counts[state] = 0
for t in self.torrents:
s = self.torrents[t]
- state_counts[s["state"]] += 1
+ state_counts[s['state']] += 1
for state in TORRENT_STATE:
- self.console.write("{!info!} %s: %i" % (state, state_counts[state]))
+ self.console.write('{!info!} %s: %i' % (state, state_counts[state]))
self.console.set_batch_write(False)
diff --git a/deluge/ui/console/cmdline/commands/update_tracker.py b/deluge/ui/console/cmdline/commands/update_tracker.py
index 756075e6e..52e70d8d9 100644
--- a/deluge/ui/console/cmdline/commands/update_tracker.py
+++ b/deluge/ui/console/cmdline/commands/update_tracker.py
@@ -16,18 +16,18 @@ from . import BaseCommand
class Command(BaseCommand):
"""Update tracker for torrent(s)"""
- usage = "update_tracker [ * | <torrent-id> [<torrent-id> ...] ]"
+ usage = 'update_tracker [ * | <torrent-id> [<torrent-id> ...] ]'
aliases = ['reannounce']
def add_arguments(self, parser):
- parser.add_argument('torrent_ids', metavar="<torrent-id>", nargs='+',
+ 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")
+ self.console = component.get('ConsoleUI')
args = options.torrent_ids
- if options.torrent_ids[0] == "*":
- args = [""]
+ if options.torrent_ids[0] == '*':
+ args = ['']
torrent_ids = []
for arg in args:
@@ -37,4 +37,4 @@ class Command(BaseCommand):
def complete(self, line):
# We use the ConsoleUI torrent tab complete method
- return component.get("ConsoleUI").tab_complete_torrent(line)
+ return component.get('ConsoleUI').tab_complete_torrent(line)
diff --git a/deluge/ui/console/console.py b/deluge/ui/console/console.py
index eeec87c9f..058202149 100644
--- a/deluge/ui/console/console.py
+++ b/deluge/ui/console/console.py
@@ -64,30 +64,30 @@ class Console(UI):
cmd_description = """Console or command-line user interface"""
def __init__(self, *args, **kwargs):
- super(Console, self).__init__("console", *args, log_stream=LogStream(), **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", dest="daemon_addr", required=False, default="127.0.0.1")
- group.add_argument("-p", "--port", dest="daemon_port", type=int, required=False, default="58846")
- group.add_argument("-U", "--username", dest="daemon_user", required=False)
- group.add_argument("-P", "--password", dest="daemon_pass", required=False)
+ 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', dest='daemon_addr', required=False, default='127.0.0.1')
+ group.add_argument('-p', '--port', dest='daemon_port', type=int, required=False, default='58846')
+ group.add_argument('-U', '--username', dest='daemon_user', required=False)
+ group.add_argument('-P', '--password', dest='daemon_pass', required=False)
# 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",
+ 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"))
+ self.console_cmds = load_commands(os.path.join(UI_PATH, 'cmdline', 'commands'))
for c in sorted(self.console_cmds):
self.console_cmds[c].add_subparser(subparsers)
diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py
index aeeab5c2a..6328023b0 100644
--- a/deluge/ui/console/main.py
+++ b/deluge/ui/console/main.py
@@ -39,30 +39,30 @@ from deluge.ui.sessionproxy import SessionProxy
log = logging.getLogger(__name__)
DEFAULT_CONSOLE_PREFS = {
- "ring_bell": False,
- "first_run": True,
- "language": "",
- "torrentview": {
- "sort_primary": "queue",
- "sort_secondary": "name",
- "show_sidebar": True,
- "sidebar_width": 25,
- "separate_complete": True,
- "move_selection": True,
- "columns": {}
+ 'ring_bell': False,
+ 'first_run': True,
+ 'language': '',
+ 'torrentview': {
+ 'sort_primary': 'queue',
+ 'sort_secondary': 'name',
+ 'show_sidebar': True,
+ 'sidebar_width': 25,
+ 'separate_complete': True,
+ 'move_selection': True,
+ 'columns': {}
},
- "addtorrents": {
- "show_misc_files": False, # TODO: Showing/hiding this
- "show_hidden_folders": False, # TODO: Showing/hiding this
- "sort_column": "date",
- "reverse_sort": True,
- "last_path": "~",
+ 'addtorrents': {
+ 'show_misc_files': False, # TODO: Showing/hiding this
+ 'show_hidden_folders': False, # TODO: Showing/hiding this
+ 'sort_column': 'date',
+ 'reverse_sort': True,
+ 'last_path': '~',
},
- "cmdline": {
- "ignore_duplicate_lines": False,
- "third_tab_lists_all": False,
- "torrents_per_tab_press": 15,
- "save_command_history": True,
+ 'cmdline': {
+ 'ignore_duplicate_lines': False,
+ 'third_tab_lists_all': False,
+ 'torrents_per_tab_press': 15,
+ 'save_command_history': True,
}
}
@@ -70,7 +70,7 @@ DEFAULT_CONSOLE_PREFS = {
class ConsoleUI(component.Component, TermResizeHandler):
def __init__(self, options, cmds, log_stream):
- component.Component.__init__(self, "ConsoleUI")
+ component.Component.__init__(self, 'ConsoleUI')
TermResizeHandler.__init__(self)
self.options = options
self.log_stream = log_stream
@@ -84,12 +84,12 @@ class ConsoleUI(component.Component, TermResizeHandler):
self.initialized = False
try:
- locale.setlocale(locale.LC_ALL, "")
+ locale.setlocale(locale.LC_ALL, '')
self.encoding = locale.getpreferredencoding()
except locale.Error:
self.encoding = sys.getdefaultencoding()
- log.debug("Using encoding: %s", self.encoding)
+ log.debug('Using encoding: %s', self.encoding)
# start up the session proxy
self.sessionproxy = SessionProxy()
@@ -117,7 +117,7 @@ class ConsoleUI(component.Component, TermResizeHandler):
if self.options.parsed_cmds:
self.interactive = False
if not self._commands:
- print("No valid console commands found")
+ print('No valid console commands found')
return
deferred = self.exec_args(self.options)
@@ -170,10 +170,10 @@ Please use commands from the command line, e.g.:\n
return commander.exec_command(cmd)
d = defer.succeed(None)
for command in options.parsed_cmds:
- if command.command in ("quit", "exit"):
+ if command.command in ('quit', 'exit'):
break
d.addCallback(exec_command, command)
- d.addCallback(do_command, "quit")
+ d.addCallback(do_command, 'quit')
return d
# We need to wait for the rpcs in start() to finish before processing
@@ -189,14 +189,14 @@ Please use commands from the command line, e.g.:\n
rm = reason.getErrorMessage()
else:
rm = reason.value.message
- print("Could not connect to daemon: %s:%s\n %s" % (options.daemon_addr, options.daemon_port, rm))
- commander.do_command("quit")
+ print('Could not connect to daemon: %s:%s\n %s' % (options.daemon_addr, options.daemon_port, rm))
+ commander.do_command('quit')
d = None
- if not self.interactive and options.parsed_cmds[0].command == "connect":
+ if not self.interactive and options.parsed_cmds[0].command == 'connect':
d = commander.do_command(options.parsed_cmds.pop(0))
else:
- log.info("connect: host=%s, port=%s, username=%s, password=%s",
+ 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)
@@ -214,7 +214,7 @@ Please use commands from the command line, e.g.:\n
# pass it the function that handles commands
colors.init_colors()
self.stdscr = stdscr
- self.config = ConfigManager("console.conf", defaults=DEFAULT_CONSOLE_PREFS, file_version=2)
+ self.config = ConfigManager('console.conf', defaults=DEFAULT_CONSOLE_PREFS, file_version=2)
self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
self.statusbars = StatusBars()
@@ -230,8 +230,8 @@ Please use commands from the command line, e.g.:\n
self.eventlog = EventLog()
- self.active_mode.topbar = "{!status!}Deluge " + deluge.common.get_version() + " Console"
- self.active_mode.bottombar = "{!status!}"
+ self.active_mode.topbar = '{!status!}Deluge ' + deluge.common.get_version() + ' Console'
+ self.active_mode.bottombar = '{!status!}'
self.active_mode.refresh()
# Start the twisted mainloop
reactor.run()
@@ -269,7 +269,7 @@ Please use commands from the command line, e.g.:\n
# 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)
+ ' Ensure all popups are removed on pause!', mode.popup.title)
d.addCallback(on_mode_paused, self.active_mode)
reactor.removeReader(self.active_mode)
@@ -281,7 +281,7 @@ Please use commands from the command line, e.g.:\n
reactor.addReader(self.active_mode)
self.stdscr.clear()
- if self.active_mode._component_state == "Stopped":
+ if self.active_mode._component_state == 'Stopped':
component.start([self.active_mode.mode_name])
else:
component.resume([self.active_mode.mode_name])
@@ -296,20 +296,20 @@ Please use commands from the command line, e.g.:\n
if arg and True in arg[0]:
func()
else:
- self.messages.append(("Error", error_smg))
- component.stop(["TorrentList"]).addCallback(on_stop)
+ self.messages.append(('Error', error_smg))
+ component.stop(['TorrentList']).addCallback(on_stop)
def is_active_mode(self, mode):
return mode == self.active_mode
def start_components(self):
def on_started(result):
- component.pause(["TorrentList", "EventView", "AddTorrents", "TorrentDetail", "Preferences"])
+ component.pause(['TorrentList', 'EventView', 'AddTorrents', 'TorrentDetail', 'Preferences'])
if self.interactive:
d = component.start().addCallback(on_started)
else:
- d = component.start(["SessionProxy", "ConsoleUI", "CoreConfig"])
+ d = component.start(['SessionProxy', 'ConsoleUI', 'CoreConfig'])
return d
def start_console(self):
@@ -321,8 +321,8 @@ Please use commands from the command line, e.g.:\n
d = self.start_components()
else:
def on_stopped(result):
- return component.start(["SessionProxy"])
- d = component.stop(["SessionProxy"]).addCallback(on_stopped)
+ return component.start(['SessionProxy'])
+ d = component.stop(['SessionProxy']).addCallback(on_stopped)
return d
def start(self):
@@ -332,22 +332,22 @@ Please use commands from the command line, e.g.:\n
def on_torrents_status(torrents):
for torrent_id, status in torrents.items():
- self.torrents.append((torrent_id, status["name"]))
+ self.torrents.append((torrent_id, status['name']))
self.started_deferred.callback(True)
- client.core.get_torrents_status({"id": result}, ["name"]).addCallback(on_torrents_status)
+ client.core.get_torrents_status({'id': result}, ['name']).addCallback(on_torrents_status)
d = client.core.get_session_state().addCallback(on_session_state)
# Register event handlers to keep the torrent list up-to-date
- client.register_event_handler("TorrentAddedEvent", self.on_torrent_added_event)
- client.register_event_handler("TorrentRemovedEvent", self.on_torrent_removed_event)
+ client.register_event_handler('TorrentAddedEvent', self.on_torrent_added_event)
+ client.register_event_handler('TorrentRemovedEvent', self.on_torrent_removed_event)
return d
def on_torrent_added_event(self, event, from_state=False):
def on_torrent_status(status):
- self.torrents.append((event, status["name"]))
- client.core.get_torrent_status(event, ["name"]).addCallback(on_torrent_status)
+ self.torrents.append((event, status['name']))
+ client.core.get_torrent_status(event, ['name']).addCallback(on_torrent_status)
def on_torrent_removed_event(self, event):
for index, (tid, name) in enumerate(self.torrents):
@@ -374,15 +374,15 @@ Please use commands from the command line, e.g.:\n
if not isinstance(string, unicode):
string = unicode(string, self.encoding)
- if string == "*" or string == "":
+ if string == '*' or string == '':
return [tid for tid, name in self.torrents]
- match_func = "__eq__"
- if string.startswith("*"):
+ match_func = '__eq__'
+ if string.startswith('*'):
string = string[1:]
- match_func = "endswith"
- if string.endswith("*"):
- match_func = "__contains__" if match_func == "endswith" else "startswith"
+ match_func = 'endswith'
+ if string.endswith('*'):
+ match_func = '__contains__' if match_func == 'endswith' else 'startswith'
string = string[:-1]
matches = []
@@ -407,7 +407,7 @@ Please use commands from the command line, e.g.:\n
if self.interactive and isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine):
return self.active_mode.tab_complete_torrent(line)
- def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=True):
+ def tab_complete_path(self, line, path_type='file', ext='', sort='name', dirs_first=True):
if self.interactive and isinstance(self.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)
@@ -420,7 +420,7 @@ Please use commands from the command line, e.g.:\n
if isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine):
self.active_mode.write(s)
else:
- component.get("CmdLine").add_line(s, False)
+ component.get('CmdLine').add_line(s, False)
self.events.append(s)
else:
print(colors.strip_colors(deluge.common.utf8_encoded(s)))
@@ -431,7 +431,7 @@ Please use commands from the command line, e.g.:\n
self.events.append(s)
self.active_mode.write(s)
else:
- component.get("CmdLine").add_line(s, False)
+ component.get('CmdLine').add_line(s, False)
self.events.append(s)
else:
print(colors.strip_colors(deluge.common.utf8_encoded(s)))
@@ -448,50 +448,50 @@ Please use commands from the command line, e.g.:\n
del source[source_key]
# These are moved to 'torrentview' sub dict
- for k in ["sort_primary", "sort_secondary", "move_selection", "separate_complete"]:
- move_key(config, config["torrentview"], k)
+ for k in ['sort_primary', 'sort_secondary', 'move_selection', 'separate_complete']:
+ move_key(config, config['torrentview'], k)
# These are moved to 'addtorrents' sub dict
- for k in ["show_misc_files", "show_hidden_folders", "sort_column", "reverse_sort", "last_path"]:
- move_key(config, config["addtorrents"], "addtorrents_%s" % k, dest_key=k)
+ for k in ['show_misc_files', 'show_hidden_folders', 'sort_column', 'reverse_sort', 'last_path']:
+ move_key(config, config['addtorrents'], 'addtorrents_%s' % k, dest_key=k)
# These are moved to 'cmdline' sub dict
- for k in ["ignore_duplicate_lines", "torrents_per_tab_press", "third_tab_lists_all"]:
- move_key(config, config["cmdline"], k)
+ for k in ['ignore_duplicate_lines', 'torrents_per_tab_press', 'third_tab_lists_all']:
+ move_key(config, config['cmdline'], k)
- move_key(config, config["cmdline"], "save_legacy_history", dest_key="save_command_history")
+ move_key(config, config['cmdline'], 'save_legacy_history', dest_key='save_command_history')
# Add key for localization
- config["language"] = DEFAULT_CONSOLE_PREFS["language"]
+ 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",
- "added": "time_added",
- "savepath": "download_location",
- "completed": "completed_time",
- "complete_seen": "last_seen_complete",
- "down_limit": "max_download_speed",
- "up_limit": "max_upload_speed",
- "downloading_time": "active_time"
+ 'downspeed': 'download_speed',
+ 'upspeed': 'upload_speed',
+ 'added': 'time_added',
+ 'savepath': 'download_location',
+ 'completed': 'completed_time',
+ 'complete_seen': 'last_seen_complete',
+ 'down_limit': 'max_download_speed',
+ 'up_limit': 'max_upload_speed',
+ 'downloading_time': 'active_time'
}
from deluge.ui.console.modes.torrentlist.torrentview import default_columns
# These are moved to 'torrentview.columns' sub dict
for k in columns:
column_name = column_name_mapping.get(k, k)
- config["torrentview"]["columns"][column_name] = {}
- if k == "name":
- config["torrentview"]["columns"][column_name]["visible"] = True
+ config['torrentview']['columns'][column_name] = {}
+ if k == 'name':
+ config['torrentview']['columns'][column_name]['visible'] = True
else:
- move_key(config, config["torrentview"]["columns"][column_name], "show_%s" % k, dest_key="visible")
- move_key(config, config["torrentview"]["columns"][column_name], "%s_width" % k, dest_key="width")
- config["torrentview"]["columns"][column_name]["order"] = default_columns[column_name]["order"]
+ move_key(config, config['torrentview']['columns'][column_name], 'show_%s' % k, dest_key='visible')
+ move_key(config, config['torrentview']['columns'][column_name], '%s_width' % k, dest_key='width')
+ config['torrentview']['columns'][column_name]['order'] = default_columns[column_name]['order']
return config
@@ -501,21 +501,21 @@ class EventLog(component.Component):
Prints out certain events as they are received from the core.
"""
def __init__(self):
- component.Component.__init__(self, "EventLog")
- self.console = component.get("ConsoleUI")
- self.prefix = "{!event!}* [%H:%M:%S] "
- self.date_change_format = "On {!yellow!}%a, %d %b %Y{!input!} %Z:"
-
- client.register_event_handler("TorrentAddedEvent", self.on_torrent_added_event)
- client.register_event_handler("PreTorrentRemovedEvent", self.on_torrent_removed_event)
- client.register_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed_event)
- client.register_event_handler("TorrentFinishedEvent", self.on_torrent_finished_event)
- client.register_event_handler("NewVersionAvailableEvent", self.on_new_version_available_event)
- client.register_event_handler("SessionPausedEvent", self.on_session_paused_event)
- client.register_event_handler("SessionResumedEvent", self.on_session_resumed_event)
- client.register_event_handler("ConfigValueChangedEvent", self.on_config_value_changed_event)
- client.register_event_handler("PluginEnabledEvent", self.on_plugin_enabled_event)
- client.register_event_handler("PluginDisabledEvent", self.on_plugin_disabled_event)
+ component.Component.__init__(self, 'EventLog')
+ self.console = component.get('ConsoleUI')
+ self.prefix = '{!event!}* [%H:%M:%S] '
+ self.date_change_format = 'On {!yellow!}%a, %d %b %Y{!input!} %Z:'
+
+ client.register_event_handler('TorrentAddedEvent', self.on_torrent_added_event)
+ client.register_event_handler('PreTorrentRemovedEvent', self.on_torrent_removed_event)
+ client.register_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed_event)
+ client.register_event_handler('TorrentFinishedEvent', self.on_torrent_finished_event)
+ client.register_event_handler('NewVersionAvailableEvent', self.on_new_version_available_event)
+ client.register_event_handler('SessionPausedEvent', self.on_session_paused_event)
+ client.register_event_handler('SessionResumedEvent', self.on_session_resumed_event)
+ client.register_event_handler('ConfigValueChangedEvent', self.on_config_value_changed_event)
+ client.register_event_handler('PluginEnabledEvent', self.on_plugin_enabled_event)
+ client.register_event_handler('PluginDisabledEvent', self.on_plugin_disabled_event)
self.previous_time = time.localtime(0)
@@ -524,15 +524,15 @@ class EventLog(component.Component):
return
def on_torrent_status(status):
- self.write("{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})" %
- (status["name"], torrent_id))
+ self.write('{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})' %
+ (status['name'], torrent_id))
# Write out what state the added torrent took
- self.on_torrent_state_changed_event(torrent_id, status["state"])
+ self.on_torrent_state_changed_event(torrent_id, status['state'])
- client.core.get_torrent_status(torrent_id, ["name", "state"]).addCallback(on_torrent_status)
+ client.core.get_torrent_status(torrent_id, ['name', 'state']).addCallback(on_torrent_status)
def on_torrent_removed_event(self, torrent_id):
- self.write("{!red!}Torrent Removed: {!info!}%s ({!cyan!}%s{!info!})" %
+ self.write('{!red!}Torrent Removed: {!info!}%s ({!cyan!}%s{!info!})' %
(self.console.get_torrent_name(torrent_id), torrent_id))
def on_torrent_state_changed_event(self, torrent_id, state):
@@ -549,40 +549,40 @@ class EventLog(component.Component):
if not t_name:
return
- self.write("%s: {!info!}%s ({!cyan!}%s{!info!})" %
+ self.write('%s: {!info!}%s ({!cyan!}%s{!info!})' %
(state, t_name, torrent_id))
def on_torrent_finished_event(self, torrent_id):
- if not deluge.common.windows_check() and component.get("TorrentList").config["ring_bell"]:
+ if not deluge.common.windows_check() and component.get('TorrentList').config['ring_bell']:
import curses.beep
curses.beep()
- self.write("{!info!}Torrent Finished: %s ({!cyan!}%s{!info!})" %
+ self.write('{!info!}Torrent Finished: %s ({!cyan!}%s{!info!})' %
(self.console.get_torrent_name(torrent_id), torrent_id))
def on_new_version_available_event(self, version):
- self.write("{!input!}New Deluge version available: {!info!}%s" %
+ self.write('{!input!}New Deluge version available: {!info!}%s' %
(version))
def on_session_paused_event(self):
- self.write("{!input!}Session Paused")
+ self.write('{!input!}Session Paused')
def on_session_resumed_event(self):
- self.write("{!green!}Session Resumed")
+ self.write('{!green!}Session Resumed')
def on_config_value_changed_event(self, key, value):
- color = "{!white,black,bold!}"
+ color = '{!white,black,bold!}'
try:
color = colors.type_color[type(value)]
except KeyError:
pass
- self.write("ConfigValueChanged: {!input!}%s: %s%s" % (key, color, value))
+ self.write('ConfigValueChanged: {!input!}%s: %s%s' % (key, color, value))
def write(self, s):
current_time = time.localtime()
date_different = False
- for field in ["tm_mday", "tm_mon", "tm_year"]:
+ for field in ['tm_mday', 'tm_mon', 'tm_year']:
c = getattr(current_time, field)
p = getattr(self.previous_time, field)
if c != p:
@@ -590,7 +590,7 @@ class EventLog(component.Component):
if date_different:
string = time.strftime(self.date_change_format)
- self.console.write_event(" ")
+ self.console.write_event(' ')
self.console.write_event(string)
p = time.strftime(self.prefix)
@@ -599,7 +599,7 @@ class EventLog(component.Component):
self.previous_time = current_time
def on_plugin_enabled_event(self, name):
- self.write("PluginEnabled: {!info!}%s" % name)
+ self.write('PluginEnabled: {!info!}%s' % name)
def on_plugin_disabled_event(self, name):
- self.write("PluginDisabled: {!info!}%s" % name)
+ self.write('PluginDisabled: {!info!}%s' % name)
diff --git a/deluge/ui/console/modes/add_util.py b/deluge/ui/console/modes/add_util.py
index 88756f495..994f77429 100644
--- a/deluge/ui/console/modes/add_util.py
+++ b/deluge/ui/console/modes/add_util.py
@@ -22,7 +22,7 @@ log = logging.getLogger(__name__)
def _bracket_fixup(path):
- if path.find("[") == -1 and path.find("]") == -1:
+ if path.find('[') == -1 and path.find(']') == -1:
return path
sentinal = 256
while path.find(unichr(sentinal)) != -1:
@@ -30,27 +30,27 @@ def _bracket_fixup(path):
if sentinal > 65535:
log.error("Can't fix brackets in path, path contains all possible sentinal characters")
return path
- newpath = path.replace("]", unichr(sentinal))
- newpath = newpath.replace("[", "[[]")
- newpath = newpath.replace(unichr(sentinal), "[]]")
+ newpath = path.replace(']', unichr(sentinal))
+ newpath = newpath.replace('[', '[[]')
+ newpath = newpath.replace(unichr(sentinal), '[]]')
return newpath
def add_torrent(t_file, options, success_cb, fail_cb, ress):
t_options = {}
- if options["path"]:
- t_options["download_location"] = os.path.expanduser(options["path"])
- t_options["add_paused"] = options["add_paused"]
+ if options['path']:
+ t_options['download_location'] = os.path.expanduser(options['path'])
+ t_options['add_paused'] = options['add_paused']
- is_url = (options["path_type"] != 1) and (deluge.common.is_url(t_file) or options["path_type"] == 2)
- is_magnet = not(is_url) and (options["path_type"] != 1) and deluge.common.is_magnet(t_file)
+ is_url = (options['path_type'] != 1) and (deluge.common.is_url(t_file) or options['path_type'] == 2)
+ is_magnet = not(is_url) and (options['path_type'] != 1) and deluge.common.is_magnet(t_file)
if is_url or is_magnet:
files = [t_file]
else:
files = glob.glob(_bracket_fixup(t_file))
num_files = len(files)
- ress["total"] = num_files
+ ress['total'] = num_files
if num_files <= 0:
fail_cb("Doesn't exist", t_file, ress)
@@ -65,7 +65,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
fail_cb("Doesn't exist", f, ress)
continue
if not os.path.isfile(f):
- fail_cb("Is a directory", f, ress)
+ fail_cb('Is a directory', f, ress)
continue
try:
diff --git a/deluge/ui/console/modes/addtorrents.py b/deluge/ui/console/modes/addtorrents.py
index 2b6767b6b..70c202ec8 100644
--- a/deluge/ui/console/modes/addtorrents.py
+++ b/deluge/ui/console/modes/addtorrents.py
@@ -68,9 +68,9 @@ class AddTorrents(BaseMode):
self.marked = set()
self.last_mark = -1
- path = os.path.expanduser(self.console_config["addtorrents"]["last_path"])
+ path = os.path.expanduser(self.console_config['addtorrents']['last_path'])
- self.path_stack = ["/"] + path.strip("/").split("/")
+ self.path_stack = ['/'] + path.strip('/').split('/')
self.path_stack_pos = len(self.path_stack)
self.listing_files = []
self.listing_dirs = []
@@ -80,8 +80,8 @@ class AddTorrents(BaseMode):
self.raw_rows_dirs = []
self.formatted_rows = []
- self.sort_column = self.console_config["addtorrents"]["sort_column"]
- self.reverse_sort = self.console_config["addtorrents"]["reverse_sort"]
+ self.sort_column = self.console_config['addtorrents']['sort_column']
+ self.reverse_sort = self.console_config['addtorrents']['reverse_sort']
BaseMode.__init__(self, stdscr, encoding)
@@ -114,14 +114,14 @@ class AddTorrents(BaseMode):
for f in listing:
if os.path.isdir(os.path.join(path, f)):
- if self.console_config["addtorrents"]["show_hidden_folders"]:
+ if self.console_config['addtorrents']['show_hidden_folders']:
self.listing_dirs.append(f)
- elif f[0] != ".":
+ elif f[0] != '.':
self.listing_dirs.append(f)
elif os.path.isfile(os.path.join(path, f)):
- if self.console_config["addtorrents"]["show_misc_files"]:
+ if self.console_config['addtorrents']['show_misc_files']:
self.listing_files.append(f)
- elif f.endswith(".torrent"):
+ elif f.endswith('.torrent'):
self.listing_files.append(f)
for dirname in self.listing_dirs:
@@ -162,15 +162,15 @@ class AddTorrents(BaseMode):
self.__sort_rows()
def __sort_rows(self):
- self.console_config["addtorrents"]["sort_column"] = self.sort_column
- self.console_config["addtorrents"]["reverse_sort"] = self.reverse_sort
+ self.console_config['addtorrents']['sort_column'] = self.sort_column
+ self.console_config['addtorrents']['reverse_sort'] = self.reverse_sort
self.console_config.save()
self.raw_rows_dirs.sort(key=lambda r: r[0].lower())
- if self.sort_column == "name":
+ if self.sort_column == 'name':
self.raw_rows_files.sort(key=lambda r: r[0].lower(), reverse=self.reverse_sort)
- elif self.sort_column == "date":
+ elif self.sort_column == 'date':
self.raw_rows_files.sort(key=lambda r: r[2], reverse=self.reverse_sort)
self.raw_rows = self.raw_rows_dirs + self.raw_rows_files
self.__refresh_rows()
@@ -185,9 +185,9 @@ class AddTorrents(BaseMode):
if row[4]:
if size != -1:
- size_str = "%i items" % size
+ size_str = '%i items' % size
else:
- size_str = " unknown"
+ size_str = ' unknown'
cols = [filename, size_str, deluge.common.fdate(time)]
widths = [self.cols - 35, 12, 23]
@@ -237,44 +237,44 @@ class AddTorrents(BaseMode):
off = 1
# Render breadcrumbs
- s = "Location: "
+ s = 'Location: '
for i, e in enumerate(self.path_stack):
- if e == "/":
+ if e == '/':
if i == self.path_stack_pos - 1:
- s += "{!black,red,bold!}root"
+ s += '{!black,red,bold!}root'
else:
- s += "{!red,black,bold!}root"
+ s += '{!red,black,bold!}root'
else:
if i == self.path_stack_pos - 1:
- s += "{!black,white,bold!}%s" % e
+ s += '{!black,white,bold!}%s' % e
else:
- s += "{!white,black,bold!}%s" % e
+ s += '{!white,black,bold!}%s' % e
if e != len(self.path_stack) - 1:
- s += "{!white,black!}/"
+ s += '{!white,black!}/'
self.add_string(off, s)
off += 1
# Render header
- cols = ["Name", "Contents", "Modification time"]
+ cols = ['Name', 'Contents', 'Modification time']
widths = [self.cols - 35, 12, 23]
- s = ""
+ s = ''
for i, (c, w) in enumerate(zip(cols, widths)):
- cn = ""
+ cn = ''
if i == 0:
- cn = "name"
+ cn = 'name'
elif i == 2:
- cn = "date"
+ cn = 'date'
if cn == self.sort_column:
- s += "{!black,green,bold!}" + c.ljust(w - 2)
+ s += '{!black,green,bold!}' + c.ljust(w - 2)
if self.reverse_sort:
- s += "^ "
+ s += '^ '
else:
- s += "v "
+ s += 'v '
else:
- s += "{!green,black,bold!}" + c.ljust(w)
+ s += '{!green,black,bold!}' + c.ljust(w)
self.add_string(off, s)
off += 1
@@ -282,26 +282,26 @@ class AddTorrents(BaseMode):
for i, row in enumerate(self.formatted_rows[self.view_offset:]):
i += self.view_offset
# It's a folder
- color_string = ""
+ color_string = ''
if self.raw_rows[i][4]:
if self.raw_rows[i][1] == -1:
if i == self.cursel:
- color_string = "{!black,red,bold!}"
+ color_string = '{!black,red,bold!}'
else:
- color_string = "{!red,black!}"
+ color_string = '{!red,black!}'
else:
if i == self.cursel:
- color_string = "{!black,cyan,bold!}"
+ color_string = '{!black,cyan,bold!}'
else:
- color_string = "{!cyan,black!}"
+ color_string = '{!cyan,black!}'
elif i == self.cursel:
if self.raw_rows[i][0] in self.marked:
- color_string = "{!blue,white,bold!}"
+ color_string = '{!blue,white,bold!}'
else:
- color_string = "{!black,white,bold!}"
+ color_string = '{!black,white,bold!}'
elif self.raw_rows[i][0] in self.marked:
- color_string = "{!white,blue,bold!}"
+ color_string = '{!white,blue,bold!}'
self.add_string(off, color_string + row)
off += 1
@@ -309,7 +309,7 @@ class AddTorrents(BaseMode):
if off > self.rows - 2:
break
- if not component.get("ConsoleUI").is_active_mode(self):
+ if not component.get('ConsoleUI').is_active_mode(self):
return
self.stdscr.noutrefresh()
@@ -321,7 +321,7 @@ class AddTorrents(BaseMode):
def back_to_overview(self):
self.parent_mode.go_top = False
- component.get("ConsoleUI").set_mode(self.parent_mode.mode_name)
+ component.get('ConsoleUI').set_mode(self.parent_mode.mode_name)
def _perform_action(self):
if self.cursel < len(self.listing_dirs):
@@ -346,7 +346,7 @@ class AddTorrents(BaseMode):
if not os.access(path, os.R_OK):
self.path_stack = self.path_stack[:self.path_stack_pos]
- self.popup = MessagePopup(self, "Error", "{!error!}Access denied: %s" % path)
+ self.popup = MessagePopup(self, 'Error', '{!error!}Access denied: %s' % path)
self.__refresh_listing()
return
@@ -362,23 +362,23 @@ class AddTorrents(BaseMode):
def _show_add_dialog(self):
def _do_add(result, **kwargs):
- ress = {"succ": 0, "fail": 0, "total": len(self.marked), "fmsg": []}
+ ress = {'succ': 0, 'fail': 0, 'total': len(self.marked), 'fmsg': []}
def fail_cb(msg, t_file, ress):
- log.debug("failed to add torrent: %s: %s", t_file, msg)
- ress["fail"] += 1
- ress["fmsg"].append("{!input!} * %s: {!error!}%s" % (t_file, msg))
- if (ress["succ"] + ress["fail"]) >= ress["total"]:
- report_add_status(component.get("TorrentList"), ress["succ"], ress["fail"], ress["fmsg"])
+ log.debug('failed to add torrent: %s: %s', t_file, msg)
+ ress['fail'] += 1
+ ress['fmsg'].append('{!input!} * %s: {!error!}%s' % (t_file, msg))
+ if (ress['succ'] + ress['fail']) >= ress['total']:
+ report_add_status(component.get('TorrentList'), ress['succ'], ress['fail'], ress['fmsg'])
def success_cb(tid, t_file, ress):
if tid:
- log.debug("added torrent: %s (%s)", t_file, tid)
- ress["succ"] += 1
- if (ress["succ"] + ress["fail"]) >= ress["total"]:
- report_add_status(component.get("TorrentList"), ress["succ"], ress["fail"], ress["fmsg"])
+ log.debug('added torrent: %s (%s)', t_file, tid)
+ ress['succ'] += 1
+ if (ress['succ'] + ress['fail']) >= ress['total']:
+ report_add_status(component.get('TorrentList'), ress['succ'], ress['fail'], ress['fmsg'])
else:
- fail_cb("Already in session (probably)", t_file, ress)
+ fail_cb('Already in session (probably)', t_file, ress)
for m in self.marked:
filename = m
@@ -387,39 +387,39 @@ class AddTorrents(BaseMode):
with open(path) as _file:
filedump = base64.encodestring(_file.read())
t_options = {}
- if result["location"]["value"]:
- t_options["download_location"] = result["location"]["value"]
- t_options["add_paused"] = result["add_paused"]["value"]
+ if result['location']['value']:
+ t_options['download_location'] = result['location']['value']
+ t_options['add_paused'] = result['add_paused']['value']
d = client.core.add_torrent_file(filename, filedump, t_options)
d.addCallback(success_cb, filename, ress)
d.addErrback(fail_cb, filename, ress)
- self.console_config["addtorrents"]["last_path"] = os.path.join(*self.path_stack[:self.path_stack_pos])
+ self.console_config['addtorrents']['last_path'] = os.path.join(*self.path_stack[:self.path_stack_pos])
self.console_config.save()
self.back_to_overview()
- config = component.get("ConsoleUI").coreconfig
- if config["add_paused"]:
+ config = component.get('ConsoleUI').coreconfig
+ if config['add_paused']:
ap = 0
else:
ap = 1
- self.popup = InputPopup(self, "Add Torrents (Esc to cancel)", close_cb=_do_add, height_req=17)
+ self.popup = InputPopup(self, 'Add Torrents (Esc to cancel)', close_cb=_do_add, height_req=17)
- msg = "Adding torrent files:"
+ msg = 'Adding torrent files:'
for i, m in enumerate(self.marked):
name = m
- msg += "\n * {!input!}%s" % name
+ msg += '\n * {!input!}%s' % name
if i == 5:
if i < len(self.marked):
- msg += "\n {!red!}And %i more" % (len(self.marked) - 5)
+ msg += '\n {!red!}And %i more' % (len(self.marked) - 5)
break
self.popup.add_text(msg)
self.popup.add_spaces(1)
- self.popup.add_text_input("location", "Download Folder:", config["download_location"], complete=True)
- self.popup.add_select_input("add_paused", "Add Paused:", ["Yes", "No"], [True, False], ap)
+ self.popup.add_text_input('location', 'Download Folder:', config['download_location'], complete=True)
+ self.popup.add_select_input('add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], ap)
def _go_up(self):
# Go up in directory hierarchy
@@ -443,7 +443,7 @@ class AddTorrents(BaseMode):
return
if util.is_printable_char(c):
- if chr(c) == "Q":
+ if chr(c) == 'Q':
from twisted.internet import reactor
if client.connected():
def on_disconnect(result):
@@ -452,7 +452,7 @@ class AddTorrents(BaseMode):
else:
reactor.stop()
return
- elif chr(c) == "q":
+ elif chr(c) == 'q':
self.back_to_overview()
return
@@ -480,23 +480,23 @@ class AddTorrents(BaseMode):
self.back_to_overview()
else:
if util.is_printable_char(c):
- if chr(c) == "h":
- self.popup = MessagePopup(self, "Help", HELP_STR, width_req=0.75)
- elif chr(c) == ">":
- if self.sort_column == "date":
+ if chr(c) == 'h':
+ self.popup = MessagePopup(self, 'Help', HELP_STR, width_req=0.75)
+ elif chr(c) == '>':
+ if self.sort_column == 'date':
self.reverse_sort = not self.reverse_sort
else:
- self.sort_column = "date"
+ self.sort_column = 'date'
self.reverse_sort = True
self.__sort_rows()
- elif chr(c) == "<":
- if self.sort_column == "name":
+ elif chr(c) == '<':
+ if self.sort_column == 'name':
self.reverse_sort = not self.reverse_sort
else:
- self.sort_column = "name"
+ self.sort_column = 'name'
self.reverse_sort = False
self.__sort_rows()
- elif chr(c) == "m":
+ elif chr(c) == 'm':
s = self.raw_rows[self.cursel][0]
if s in self.marked:
self.marked.remove(s)
@@ -504,11 +504,11 @@ class AddTorrents(BaseMode):
self.marked.add(s)
self.last_mark = self.cursel
- elif chr(c) == "j":
+ elif chr(c) == 'j':
self.scroll_list_up(1)
- elif chr(c) == "k":
+ elif chr(c) == 'k':
self.scroll_list_down(1)
- elif chr(c) == "M":
+ elif chr(c) == 'M':
if self.last_mark != -1:
if self.last_mark > self.cursel:
m = range(self.cursel, self.last_mark)
diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py
index 416554d80..dffb980a2 100644
--- a/deluge/ui/console/modes/basemode.py
+++ b/deluge/ui/console/modes/basemode.py
@@ -67,11 +67,11 @@ class TermResizeHandler(object):
try:
signal.signal(signal.SIGWINCH, self.on_terminal_size)
except ValueError as ex:
- log.debug("Unable to catch SIGWINCH signal: %s", ex)
+ log.debug('Unable to catch SIGWINCH signal: %s', ex)
def on_terminal_size(self, *args):
# Get the new rows and cols value
- rows, cols = struct.unpack("hhhh", ioctl(0, termios.TIOCGWINSZ, "\000" * 8))[0:2]
+ rows, cols = struct.unpack('hhhh', ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[0:2]
curses.resizeterm(rows, cols)
return rows, cols
@@ -91,7 +91,7 @@ class CursesStdIO(object):
pass
def logPrefix(self): # NOQA
- return "CursesClient"
+ return 'CursesClient'
class BaseMode(CursesStdIO, component.Component):
@@ -125,8 +125,8 @@ class BaseMode(CursesStdIO, component.Component):
self.paused = False
# Strings for the 2 status bars
- self.statusbars = component.get("StatusBars")
- self.help_hstr = "{!status!} Press {!magenta,blue,bold!}[h]{!status!} for help"
+ self.statusbars = component.get('StatusBars')
+ self.help_hstr = '{!status!} Press {!magenta,blue,bold!}[h]{!status!} for help'
# Keep track of the screen size
self.rows, self.cols = self.stdscr.getmaxyx()
@@ -161,7 +161,7 @@ class BaseMode(CursesStdIO, component.Component):
if bottombar_help:
if bottombar_help is True:
bottombar_help = self.help_hstr
- bottombar += " " * (self.cols - len(remove_formatting(bottombar)) -
+ bottombar += ' ' * (self.cols - len(remove_formatting(bottombar)) -
len(remove_formatting(bottombar_help))) + bottombar_help
self.add_string(self.rows + bottom_row, bottombar, scr=scr)
@@ -219,7 +219,7 @@ class BaseMode(CursesStdIO, component.Component):
curses.endwin()
-def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", trim="...", leaveok=0):
+def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=' ', trim='...', leaveok=0):
"""
Adds a string to the desired `:param:row`.
@@ -256,7 +256,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri
try:
parsed = colors.parse_color_string(string, encoding)
except colors.BadColorString as ex:
- log.error("Cannot add bad color string %s: %s", string, ex)
+ log.error('Cannot add bad color string %s: %s', string, ex)
return
if leaveok:
@@ -274,7 +274,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri
if (col + len(s)) > max_x:
if trim:
- s = "%s%s" % (s[0:max_x - len(trim) - col], trim)
+ s = '%s%s' % (s[0:max_x - len(trim) - col], trim)
else:
s = s[0:max_x - col]
@@ -290,7 +290,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri
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)))
+ ''.join(traceback.format_stack(limit=5)))
col += len(s)
@@ -334,4 +334,4 @@ def move_cursor(screen, 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()))
+ 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 a82197a4e..8afd6c39c 100644
--- a/deluge/ui/console/modes/cmdline.py
+++ b/deluge/ui/console/modes/cmdline.py
@@ -36,20 +36,20 @@ MAX_HISTFILE_SIZE = 2000
def complete_line(line, possible_matches):
- "Find the common prefix of possible matches, proritizing matching-case elements"
+ 'Find the common prefix of possible matches, proritizing matching-case elements'
if not possible_matches:
return line
- line = line.replace(r"\ ", " ")
+ line = line.replace(r'\ ', ' ')
matches1 = []
matches2 = []
for match in possible_matches:
match = remove_formatting(match)
- match = match.replace(r"\ ", " ")
- m1, m2 = "", ""
+ match = match.replace(r'\ ', ' ')
+ m1, m2 = '', ''
for i, c in enumerate(line):
if m1 and m2:
break
@@ -76,13 +76,13 @@ def complete_line(line, possible_matches):
maxlen = min(maxlen, i)
break
- return possible_matches[0][:maxlen].replace(" ", r"\ ")
+ return possible_matches[0][:maxlen].replace(' ', r'\ ')
def commonprefix(m):
- "Given a list of pathnames, returns the longest common leading component"
+ 'Given a list of pathnames, returns the longest common leading component'
if not m:
- return ""
+ return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
@@ -95,7 +95,7 @@ class CmdLine(BaseMode, Commander):
def __init__(self, stdscr, encoding=None):
# Get a handle to the main console
- self.console = component.get("ConsoleUI")
+ self.console = component.get('ConsoleUI')
Commander.__init__(self, self.console._commands, interactive=True)
self.batch_write = False
@@ -106,8 +106,8 @@ class CmdLine(BaseMode, Commander):
self.display_lines_offset = 0
# Holds the user input and is cleared on 'enter'
- self.input = u""
- self.input_incomplete = u""
+ self.input = u''
+ self.input_incomplete = u''
# Keep track of where the cursor is
self.input_cursor = 0
@@ -118,7 +118,7 @@ class CmdLine(BaseMode, Commander):
# Keep track of double- and multi-tabs
self.tab_count = 0
- self.console_config = component.get("TorrentList").config
+ self.console_config = component.get('TorrentList').config
# To avoid having to truncate the file every time we're writing
# or doing it on exit(and therefore relying on an error-less
@@ -126,13 +126,13 @@ class CmdLine(BaseMode, Commander):
# that we swap around based on length
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.hist1'),
+ os.path.join(config_dir, 'cmd_line.hist2')
]
self._hf_lines = [0, 0]
- if self.console_config["cmdline"]["save_command_history"]:
+ if self.console_config['cmdline']['save_command_history']:
try:
- with open(self.history_file[0], "r") as _file:
+ with open(self.history_file[0], 'r') as _file:
lines1 = _file.read().splitlines()
self._hf_lines[0] = len(lines1)
except IOError:
@@ -140,7 +140,7 @@ class CmdLine(BaseMode, Commander):
self._hf_lines[0] = 0
try:
- with open(self.history_file[1], "r") as _file:
+ with open(self.history_file[1], 'r') as _file:
lines2 = _file.read().splitlines()
self._hf_lines[1] = len(lines2)
except IOError:
@@ -163,9 +163,9 @@ class CmdLine(BaseMode, Commander):
# line = line.encode(self.encoding)
# self.lines[i] = line
line = remove_formatting(line)
- if line.startswith(">>> "):
+ if line.startswith('>>> '):
console_input = line[4:]
- if self.console_config["cmdline"]["ignore_duplicate_lines"]:
+ if self.console_config['cmdline']['ignore_duplicate_lines']:
if len(self.input_history) > 0:
if self.input_history[-1] != console_input:
self.input_history.append(console_input)
@@ -176,11 +176,11 @@ class CmdLine(BaseMode, Commander):
# show the cursor
util.safe_curs_set(util.Curser.VERY_VISIBLE)
- BaseMode.__init__(self, stdscr, encoding, depend=["SessionProxy"])
+ BaseMode.__init__(self, stdscr, encoding, depend=['SessionProxy'])
@overrides(component.Component)
def update(self):
- if not component.get("ConsoleUI").is_active_mode(self):
+ if not component.get('ConsoleUI').is_active_mode(self):
return
# Update just the status bars
self.draw_statusbars(bottom_row=-2, bottombar_help=False)
@@ -215,16 +215,16 @@ class CmdLine(BaseMode, Commander):
# We clear the input string and send it to the command parser on ENTER
if c in [curses.KEY_ENTER, util.KEY_ENTER2]:
if self.input:
- if self.input.endswith("\\"):
+ if self.input.endswith('\\'):
self.input = self.input[:-1]
self.input_cursor -= 1
- self.add_line("{!yellow,black,bold!}>>>{!input!} %s" % self.input)
+ self.add_line('{!yellow,black,bold!}>>>{!input!} %s' % self.input)
self.do_command(self.input)
if len(self.input_history) == INPUT_HISTORY_SIZE:
# Remove the oldest input history if the max history size
# is reached.
del self.input_history[0]
- if self.console_config["cmdline"]["ignore_duplicate_lines"]:
+ if self.console_config['cmdline']['ignore_duplicate_lines']:
if len(self.input_history) > 0:
if self.input_history[-1] != self.input:
self.input_history.append(self.input)
@@ -233,8 +233,8 @@ class CmdLine(BaseMode, Commander):
else:
self.input_history.append(self.input)
self.input_history_index = len(self.input_history)
- self.input = u""
- self.input_incomplete = u""
+ self.input = u''
+ self.input_incomplete = u''
self.input_cursor = 0
self.stdscr.refresh()
@@ -246,7 +246,7 @@ class CmdLine(BaseMode, Commander):
if self.tab_completer:
# We only call the tab completer function if we're at the end of
# the input string on the cursor is on a space
- if self.input_cursor == len(self.input) or self.input[self.input_cursor] == " ":
+ if self.input_cursor == len(self.input) or self.input[self.input_cursor] == ' ':
self.input, self.input_cursor = self.tab_completer(self.input, self.input_cursor, self.tab_count)
# We use the UP and DOWN keys to cycle through input history
@@ -315,7 +315,7 @@ class CmdLine(BaseMode, Commander):
if c > 31 and c < 256:
# Emulate getwch
stroke = chr(c)
- uchar = ""
+ uchar = ''
while not uchar:
try:
uchar = stroke.decode(self.encoding)
@@ -348,7 +348,7 @@ class CmdLine(BaseMode, Commander):
Updates the lines based on the`:attr:lines` based on the `:attr:display_lines_offset`
attribute and the status bars.
"""
- if not component.get("ConsoleUI").is_active_mode(self):
+ if not component.get('ConsoleUI').is_active_mode(self):
return
self.stdscr.erase()
@@ -367,7 +367,7 @@ class CmdLine(BaseMode, Commander):
elif len(self.lines) == available_lines:
lines = self.lines
else:
- lines = [""] * (available_lines - len(self.lines))
+ lines = [''] * (available_lines - len(self.lines))
lines.extend(self.lines)
# Add the lines to the screen
@@ -408,7 +408,7 @@ class CmdLine(BaseMode, Commander):
"""
- if self.console_config["cmdline"]["save_command_history"]:
+ if self.console_config['cmdline']['save_command_history']:
# Determine which file is the active one
# If both are under maximum, it's first, otherwise it's the one not full
if self._hf_lines[0] < MAX_HISTFILE_SIZE and self._hf_lines[1] < MAX_HISTFILE_SIZE:
@@ -419,7 +419,7 @@ class CmdLine(BaseMode, Commander):
active_file = 0
# Write the line
- with open(self.history_file[active_file], "a") as _file:
+ with open(self.history_file[active_file], 'a') as _file:
if isinstance(text, unicode):
text = text.encode(self.encoding)
_file.write(text)
@@ -432,7 +432,7 @@ class CmdLine(BaseMode, Commander):
# therefore swapping the currently active file
if self._hf_lines[active_file] == MAX_HISTFILE_SIZE:
self._hf_lines[1 - active_file] = 0
- with open(self.history_file[1 - active_file], "w") as _file:
+ with open(self.history_file[1 - active_file], 'w') as _file:
_file.truncate(0)
def get_line_chunks(line):
@@ -440,21 +440,21 @@ class CmdLine(BaseMode, Commander):
Returns a list of 2-tuples (color string, text)
"""
- if not line or line.count("{!") != line.count("!}"):
+ if not line or line.count('{!') != line.count('!}'):
return []
chunks = []
- if not line.startswith("{!"):
- begin = line.find("{!")
+ if not line.startswith('{!'):
+ begin = line.find('{!')
if begin == -1:
begin = len(line)
- chunks.append(("", line[:begin]))
+ chunks.append(('', line[:begin]))
line = line[begin:]
while line:
# We know the line starts with "{!" here
- end_color = line.find("!}")
- next_color = line.find("{!", end_color)
+ end_color = line.find('!}')
+ next_color = line.find('{!', end_color)
if next_color == -1:
next_color = len(line)
chunks.append((line[:end_color + 2], line[end_color + 2:next_color]))
@@ -466,11 +466,11 @@ class CmdLine(BaseMode, Commander):
try:
line_length = colors.get_line_width(line)
except colors.BadColorString:
- log.error("Passed a bad colored line: %s", line)
+ log.error('Passed a bad colored line: %s', line)
continue
if line_length >= (self.cols - 1):
- s = ""
+ s = ''
# The length of the text without the color tags
s_len = 0
# We need to split this over multiple lines
@@ -515,13 +515,13 @@ class CmdLine(BaseMode, Commander):
try:
parsed = colors.parse_color_string(string, self.encoding)
except colors.BadColorString as ex:
- log.error("Cannot add bad color string %s: %s", string, ex)
+ log.error('Cannot add bad color string %s: %s', string, ex)
return
for index, (color, s) in enumerate(parsed):
if index + 1 == len(parsed):
# This is the last string so lets append some " " to it
- s += " " * (self.cols - (col + strwidth(s)) - 1)
+ s += ' ' * (self.cols - (col + strwidth(s)) - 1)
try:
self.stdscr.addstr(row, col, s, color)
except curses.error:
@@ -571,9 +571,9 @@ class CmdLine(BaseMode, Commander):
# We don't want to split by escaped spaces
def split(string):
- return re.split(r"(?<!\\) ", string)
+ return re.split(r'(?<!\\) ', string)
- if " " not in line:
+ if ' ' not in line:
possible_matches = []
# Iterate through the commands looking for ones that startwith the
# line.
@@ -581,13 +581,13 @@ class CmdLine(BaseMode, Commander):
if cmd.startswith(line):
possible_matches.append(cmd)
- line_prefix = ""
+ line_prefix = ''
else:
cmd = split(line)[0]
if cmd in self.console._commands:
# Call the command's complete method to get 'er done
possible_matches = self.console._commands[cmd].complete(split(line)[-1])
- line_prefix = " ".join(split(line)[:-1]) + " "
+ line_prefix = ' '.join(split(line)[:-1]) + ' '
else:
# This is a bogus command
return (line, cursor)
@@ -601,70 +601,70 @@ class CmdLine(BaseMode, Commander):
elif len(possible_matches) == 1:
# Do not append space after directory names
new_line = line_prefix + possible_matches[0]
- if not new_line.endswith("/") and not new_line.endswith(r"\\"):
- new_line += " "
+ if not new_line.endswith('/') and not new_line.endswith(r'\\'):
+ new_line += ' '
# We only want to print eventual colors or other control characters, not return them
new_line = remove_formatting(new_line)
return (new_line, len(new_line))
else:
if hits == 1:
- p = " ".join(split(line)[:-1])
+ p = ' '.join(split(line)[:-1])
try:
l_arg = split(line)[-1]
except IndexError:
- l_arg = ""
+ l_arg = ''
- new_line = " ".join([p, complete_line(l_arg, possible_matches)]).lstrip()
+ new_line = ' '.join([p, complete_line(l_arg, possible_matches)]).lstrip()
if len(remove_formatting(new_line)) > len(line):
line = new_line
cursor = len(line)
elif hits >= 2:
- max_list = self.console_config["cmdline"]["torrents_per_tab_press"]
+ max_list = self.console_config['cmdline']['torrents_per_tab_press']
match_count = len(possible_matches)
listed = (hits - 2) * max_list
pages = (match_count - 1) // max_list + 1
left = match_count - listed
if hits == 2:
- self.write(" ")
+ self.write(' ')
if match_count >= 4:
- self.write("{!green!}Autocompletion matches:")
+ self.write('{!green!}Autocompletion matches:')
# Only list some of the matching torrents as there can be hundreds of them
- if self.console_config["cmdline"]["third_tab_lists_all"]:
+ if self.console_config['cmdline']['third_tab_lists_all']:
if hits == 2 and left > max_list:
for i in range(listed, listed + max_list):
match = possible_matches[i]
- self.write(match.replace(r"\ ", " "))
- self.write("{!error!}And %i more. Press <tab> to list them" % (left - max_list))
+ self.write(match.replace(r'\ ', ' '))
+ self.write('{!error!}And %i more. Press <tab> to list them' % (left - max_list))
else:
self.tab_count = 0
for match in possible_matches[listed:]:
- self.write(match.replace(r"\ ", " "))
+ self.write(match.replace(r'\ ', ' '))
else:
if left > max_list:
for i in range(listed, listed + max_list):
match = possible_matches[i]
- self.write(match.replace(r"\ ", " "))
- self.write("{!error!}And %i more (%i/%i). Press <tab> to view more" % (
+ self.write(match.replace(r'\ ', ' '))
+ self.write('{!error!}And %i more (%i/%i). Press <tab> to view more' % (
left - max_list, hits - 1, pages))
else:
self.tab_count = 0
for match in possible_matches[listed:]:
- self.write(match.replace(r"\ ", " "))
+ self.write(match.replace(r'\ ', ' '))
if hits > 2:
- self.write("{!green!}Finished listing %i torrents (%i/%i)" % (match_count, hits - 1, pages))
+ self.write('{!green!}Finished listing %i torrents (%i/%i)' % (match_count, hits - 1, pages))
# We only want to print eventual colors or other control characters, not return them
line = remove_formatting(line)
cursor = len(line)
return (line, cursor)
- def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=1):
- self.console = component.get("ConsoleUI")
+ def tab_complete_path(self, line, path_type='file', ext='', sort='name', dirs_first=1):
+ self.console = component.get('ConsoleUI')
- line = line.replace("\\ ", " ")
+ line = line.replace('\\ ', ' ')
line = os.path.abspath(os.path.expanduser(line))
ret = []
if os.path.exists(line):
@@ -675,19 +675,19 @@ class CmdLine(BaseMode, Commander):
try:
for f in os.listdir(line):
# Skip hidden
- if f.startswith("."):
+ if f.startswith('.'):
continue
f = os.path.join(line, f)
if os.path.isdir(f):
- if os.sep == "\\": # Windows path support
- f += "\\"
+ if os.sep == '\\': # Windows path support
+ f += '\\'
else: # Unix
- f += "/"
+ f += '/'
elif not f.endswith(ext):
continue
ret.append(f)
except OSError:
- self.console.write("{!error!}Permission denied: {!info!}%s" % line)
+ self.console.write('{!error!}Permission denied: {!info!}%s' % line)
else:
try:
# This is a file, but we could be looking for another file that
@@ -696,7 +696,7 @@ class CmdLine(BaseMode, Commander):
if f.startswith(os.path.split(line)[1]):
ret.append(os.path.join(os.path.dirname(line), f))
except OSError:
- self.console.write("{!error!}Permission denied: {!info!}%s" % line)
+ self.console.write('{!error!}Permission denied: {!info!}%s' % line)
else:
# This path does not exist, so lets do a listdir on it's parent
# and find any matches.
@@ -708,15 +708,15 @@ class CmdLine(BaseMode, Commander):
p = os.path.join(os.path.dirname(line), f)
if os.path.isdir(p):
- if os.sep == "\\": # Windows path support
- p += "\\"
+ if os.sep == '\\': # Windows path support
+ p += '\\'
else: # Unix
- p += "/"
+ p += '/'
ret.append(p)
except OSError:
- self.console.write("{!error!}Permission denied: {!info!}%s" % line)
+ self.console.write('{!error!}Permission denied: {!info!}%s' % line)
- if sort == "date":
+ if sort == 'date':
ret = sorted(ret, key=os.path.getmtime, reverse=True)
if dirs_first == 1:
@@ -727,10 +727,10 @@ class CmdLine(BaseMode, Commander):
# Highlight directory names
for i, filename in enumerate(ret):
if os.path.isdir(filename):
- ret[i] = "{!cyan!}%s" % filename
+ ret[i] = '{!cyan!}%s' % filename
for i in range(0, len(ret)):
- ret[i] = ret[i].replace(" ", r"\ ")
+ ret[i] = ret[i].replace(' ', r'\ ')
return ret
def tab_complete_torrent(self, line):
@@ -746,11 +746,11 @@ class CmdLine(BaseMode, Commander):
empty = len(line) == 0
# Remove dangling backslashes to avoid breaking shlex
- if line.endswith("\\"):
+ if line.endswith('\\'):
line = line[:-1]
raw_line = line
- line = line.replace("\\ ", " ")
+ line = line.replace('\\ ', ' ')
possible_matches = []
possible_matches2 = []
@@ -769,7 +769,7 @@ class CmdLine(BaseMode, Commander):
for torrent_id, torrent_name in self.console.torrents:
# Escape spaces to avoid, for example, expanding "Doc" into "Doctor Who" and removing
# everything containing one of these words
- escaped_name = torrent_name.replace(" ", "\\ ")
+ escaped_name = torrent_name.replace(' ', '\\ ')
# If we only matched one torrent, don't add the full name or it'll also get autocompleted
if match_count == 1:
if torrent_id.startswith(line):
@@ -791,11 +791,11 @@ class CmdLine(BaseMode, Commander):
text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name)
possible_matches.append(text)
if torrent_name.startswith(line):
- text = "{!info!}%s{!input!}%s ({!cyan!}%s{!input!})" % (
+ text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
escaped_name[:l], escaped_name[l:], torrent_id)
possible_matches.append(text)
elif torrent_name.lower().startswith(line.lower()):
- text = "{!info!}%s{!input!}%s ({!cyan!}%s{!input!})" % (
+ text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
escaped_name[:l], escaped_name[l:], torrent_id)
possible_matches2.append(text)
diff --git a/deluge/ui/console/modes/connectionmanager.py b/deluge/ui/console/modes/connectionmanager.py
index 90a7f0665..168d086dd 100644
--- a/deluge/ui/console/modes/connectionmanager.py
+++ b/deluge/ui/console/modes/connectionmanager.py
@@ -33,7 +33,7 @@ class ConnectionManager(BaseMode, PopupsHandler):
PopupsHandler.__init__(self)
self.statuses = {}
self.all_torrents = None
- self.config = ConfigManager("hostlist.conf.1.2", uicommon.DEFAULT_HOSTS)
+ self.config = ConfigManager('hostlist.conf.1.2', uicommon.DEFAULT_HOSTS)
self.update_hosts_status()
BaseMode.__init__(self, stdscr, encoding=encoding)
self.update_select_host_popup()
@@ -43,19 +43,19 @@ class ConnectionManager(BaseMode, PopupsHandler):
if self.popup:
selected_index = self.popup.current_selection()
- popup = SelectablePopup(self, _("Select Host"), self._host_selected, border_off_west=1, active_wrap=True)
+ popup = SelectablePopup(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 new host"), _("delete host")),
+ (_('quit'), _('add new host'), _('delete host')),
space_below=True)
self.push_popup(popup, clear=True)
- for host in self.config["hosts"]:
- args = {"data": host[0], "foreground": "red"}
- state = "Offline"
+ for host in self.config['hosts']:
+ args = {'data': host[0], 'foreground': 'red'}
+ state = 'Offline'
if host[0] in self.statuses:
- state = "Online"
- args.update({"data": self.statuses[host[0]], "foreground": "green"})
- host_str = "%s:%d [%s]" % (host[1], host[2], state)
+ state = 'Online'
+ args.update({'data': self.statuses[host[0]], 'foreground': 'green'})
+ host_str = '%s:%d [%s]' % (host[1], host[2], state)
self.popup.add_line(host[0], host_str, selectable=True, use_underline=True, **args)
if selected_index is not None:
@@ -85,34 +85,34 @@ class ConnectionManager(BaseMode, PopupsHandler):
del self.statuses[host_id]
self.update_select_host_popup()
- for host in self.config["hosts"]:
+ for host in self.config['hosts']:
c = Client()
hadr = host[1]
port = host[2]
user = host[3]
password = host[4]
- log.debug("connect: hadr=%s, port=%s, user=%s, password=%s", hadr, port, user, password)
+ log.debug('connect: hadr=%s, port=%s, user=%s, password=%s', hadr, port, user, password)
d = c.connect(hadr, port, user, password)
d.addCallback(on_connect, c, host[0])
d.addErrback(on_connect_failed, host[0])
def _on_connected(self, result):
- d = component.get("ConsoleUI").start_console()
+ d = component.get('ConsoleUI').start_console()
def on_console_start(result):
- component.get("ConsoleUI").set_mode("TorrentList")
+ component.get('ConsoleUI').set_mode('TorrentList')
d.addCallback(on_console_start)
def _on_connect_fail(self, result):
- self.report_message("Failed to connect!", result)
+ self.report_message('Failed to connect!', result)
self.refresh()
- if hasattr(result, "getTraceback"):
+ if hasattr(result, 'getTraceback'):
log.exception(result)
def _host_selected(self, selected_host, *args, **kwargs):
if selected_host not in self.statuses:
return
- for host in self.config["hosts"]:
+ for host in self.config['hosts']:
if host[0] == selected_host:
d = client.connect(host[1], host[2], host[3], host[4])
d.addCallback(self._on_connected)
@@ -121,44 +121,44 @@ class ConnectionManager(BaseMode, PopupsHandler):
return False
def _do_add(self, result, **kwargs):
- if not result or kwargs.get("close", False):
+ if not result or kwargs.get('close', False):
self.pop_popup()
return
- hostname = result["hostname"]["value"]
+ hostname = result['hostname']['value']
try:
- port = int(result["port"]["value"])
+ port = int(result['port']['value'])
except ValueError:
- self.report_message("Can't add host", "Invalid port. Must be an integer")
+ self.report_message("Can't add host", 'Invalid port. Must be an integer')
return
- username = result["username"]["value"]
- password = result["password"]["value"]
- for host in self.config["hosts"]:
+ username = result['username']['value']
+ password = result['password']['value']
+ for host in self.config['hosts']:
if (host[1], host[2], host[3]) == (hostname, port, username):
- self.report_message("Can't add host", "Host already in list")
+ self.report_message("Can't add host", 'Host already in list')
return
newid = hashlib.sha1(str(time.time())).hexdigest()
- self.config["hosts"].append((newid, hostname, port, username, password))
+ self.config['hosts'].append((newid, hostname, port, username, password))
self.config.save()
self.update_select_host_popup()
def add_popup(self):
self.inlist = False
- popup = InputPopup(self, "Add Host (up & down arrows to navigate, esc to cancel)",
+ popup = InputPopup(self, 'Add Host (up & down arrows to navigate, esc to cancel)',
border_off_north=1, border_off_east=1,
close_cb=self._do_add)
- popup.add_text_input("hostname", "%s:" % _("Hostname"))
- popup.add_text_input("port", "%s:" % _("Port"))
- popup.add_text_input("username", "%s:" % _("Username"))
- popup.add_text_input("password", "%s:" % _("Password"))
+ popup.add_text_input('hostname', '%s:' % _('Hostname'))
+ popup.add_text_input('port', '%s:' % _('Port'))
+ popup.add_text_input('username', '%s:' % _('Username'))
+ popup.add_text_input('password', '%s:' % _('Password'))
self.push_popup(popup, clear=True)
self.refresh()
def delete_current_host(self):
idx, data = self.popup.current_selection()
- log.debug("deleting host: %s", data)
- for host in self.config["hosts"]:
+ log.debug('deleting host: %s', data)
+ for host in self.config['hosts']:
if host[0] == data:
- self.config["hosts"].remove(host)
+ self.config['hosts'].remove(host)
break
self.config.save()
@@ -210,9 +210,9 @@ class ConnectionManager(BaseMode, PopupsHandler):
c = self.stdscr.getch()
if c > 31 and c < 256:
- if chr(c) == "q" and self.inlist:
+ if chr(c) == 'q' and self.inlist:
return
- if chr(c) == "Q":
+ if chr(c) == 'Q':
from twisted.internet import reactor
if client.connected():
def on_disconnect(result):
@@ -221,11 +221,11 @@ class ConnectionManager(BaseMode, PopupsHandler):
else:
reactor.stop()
return
- if chr(c) == "D" and self.inlist:
+ if chr(c) == 'D' and self.inlist:
self.delete_current_host()
self.update_select_host_popup()
return
- if chr(c) == "a" and self.inlist:
+ if chr(c) == 'a' and self.inlist:
self.add_popup()
return
diff --git a/deluge/ui/console/modes/eventview.py b/deluge/ui/console/modes/eventview.py
index dc7601667..534f09ed8 100644
--- a/deluge/ui/console/modes/eventview.py
+++ b/deluge/ui/console/modes/eventview.py
@@ -30,7 +30,7 @@ class EventView(BaseMode):
self.offset = 0
def back_to_overview(self):
- component.get("ConsoleUI").set_mode(self.parent_mode.mode_name)
+ component.get('ConsoleUI').set_mode(self.parent_mode.mode_name)
@overrides(component.Component)
def update(self):
@@ -41,7 +41,7 @@ class EventView(BaseMode):
"""
This method just shows each line of the event log
"""
- events = component.get("ConsoleUI").events
+ events = component.get('ConsoleUI').events
self.stdscr.erase()
self.draw_statusbars()
@@ -51,7 +51,7 @@ class EventView(BaseMode):
if i - self.offset >= self.rows - 2:
more = len(events) - self.offset - self.rows + 2
if more > 0:
- self.add_string(i - self.offset, " (And %i more)" % more)
+ self.add_string(i - self.offset, ' (And %i more)' % more)
break
elif i - self.offset < 0:
@@ -61,9 +61,9 @@ class EventView(BaseMode):
except curses.error:
pass # This'll just cut the line. Note: This seriously should be fixed in a better way
else:
- self.add_string(1, "{!white,black,bold!}No events to show yet")
+ self.add_string(1, '{!white,black,bold!}No events to show yet')
- if not component.get("ConsoleUI").is_active_mode(self):
+ if not component.get('ConsoleUI').is_active_mode(self):
return
self.stdscr.noutrefresh()
@@ -84,7 +84,7 @@ class EventView(BaseMode):
# TODO: Scroll event list
jumplen = self.rows - 3
- num_events = len(component.get("ConsoleUI").events)
+ num_events = len(component.get('ConsoleUI').events)
if c == curses.KEY_UP:
self.offset -= 1
@@ -98,9 +98,9 @@ class EventView(BaseMode):
self.offset += jumplen
elif c == curses.KEY_END:
self.offset += num_events
- elif c == ord("j"):
+ elif c == ord('j'):
self.offset -= 1
- elif c == ord("k"):
+ elif c == ord('k'):
self.offset += 1
if self.offset <= 0:
diff --git a/deluge/ui/console/modes/preferences/preference_panes.py b/deluge/ui/console/modes/preferences/preference_panes.py
index a156398d8..2801ff1ff 100644
--- a/deluge/ui/console/modes/preferences/preference_panes.py
+++ b/deluge/ui/console/modes/preferences/preference_panes.py
@@ -24,7 +24,7 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler):
def __init__(self, name, preferences):
PopupsHandler.__init__(self)
self.preferences = preferences
- BaseWindow.__init__(self, "%s" % name, self.pane_width, preferences.height, posy=1, posx=self.pane_x_pos)
+ BaseWindow.__init__(self, '%s' % name, self.pane_width, preferences.height, posy=1, posx=self.pane_x_pos)
BaseInputPane.__init__(self, preferences, border_off_east=1)
self.name = name
@@ -72,39 +72,39 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler):
for ipt in self.inputs:
if ipt.has_input():
# gross, have to special case in/out ports since they are tuples
- if ipt.name in ("listen_ports_to", "listen_ports_from", "out_ports_from", "out_ports_to",
- "i2p_port", "i2p_hostname", "proxy_type", "proxy_username", "proxy_hostnames",
- "proxy_password", "proxy_hostname", "proxy_port", "proxy_peer_connections",
- "listen_interface"):
- if ipt.name == "listen_ports_to":
- conf_dict["listen_ports"] = (self.infrom.get_value(), self.into.get_value())
- elif ipt.name == "out_ports_to":
- conf_dict["outgoing_ports"] = (self.outfrom.get_value(), self.outto.get_value())
- elif ipt.name == "listen_interface":
+ if ipt.name in ('listen_ports_to', 'listen_ports_from', 'out_ports_from', 'out_ports_to',
+ 'i2p_port', 'i2p_hostname', 'proxy_type', 'proxy_username', 'proxy_hostnames',
+ 'proxy_password', 'proxy_hostname', 'proxy_port', 'proxy_peer_connections',
+ 'listen_interface'):
+ if ipt.name == 'listen_ports_to':
+ conf_dict['listen_ports'] = (self.infrom.get_value(), self.into.get_value())
+ elif ipt.name == 'out_ports_to':
+ conf_dict['outgoing_ports'] = (self.outfrom.get_value(), self.outto.get_value())
+ elif ipt.name == 'listen_interface':
interface = ipt.get_value().strip()
if is_ip(interface) or not interface:
- conf_dict["listen_interface"] = interface
- elif ipt.name == "i2p_port":
- conf_dict.setdefault("i2p_proxy", {})["port"] = ipt.get_value()
- elif ipt.name == "i2p_hostname":
- conf_dict.setdefault("i2p_proxy", {})["hostname"] = ipt.get_value()
- elif ipt.name == "proxy_type":
- conf_dict.setdefault("proxy", {})["type"] = ipt.get_value()
- elif ipt.name == "proxy_username":
- conf_dict.setdefault("proxy", {})["username"] = ipt.get_value()
- elif ipt.name == "proxy_password":
- conf_dict.setdefault("proxy", {})["password"] = ipt.get_value()
- elif ipt.name == "proxy_hostname":
- conf_dict.setdefault("proxy", {})["hostname"] = ipt.get_value()
- elif ipt.name == "proxy_port":
- conf_dict.setdefault("proxy", {})["port"] = ipt.get_value()
- elif ipt.name == "proxy_hostnames":
- conf_dict.setdefault("proxy", {})["proxy_hostnames"] = ipt.get_value()
- elif ipt.name == "proxy_peer_connections":
- conf_dict.setdefault("proxy", {})["proxy_peer_connections"] = ipt.get_value()
+ conf_dict['listen_interface'] = interface
+ elif ipt.name == 'i2p_port':
+ conf_dict.setdefault('i2p_proxy', {})['port'] = ipt.get_value()
+ elif ipt.name == 'i2p_hostname':
+ conf_dict.setdefault('i2p_proxy', {})['hostname'] = ipt.get_value()
+ elif ipt.name == 'proxy_type':
+ conf_dict.setdefault('proxy', {})['type'] = ipt.get_value()
+ elif ipt.name == 'proxy_username':
+ conf_dict.setdefault('proxy', {})['username'] = ipt.get_value()
+ elif ipt.name == 'proxy_password':
+ conf_dict.setdefault('proxy', {})['password'] = ipt.get_value()
+ elif ipt.name == 'proxy_hostname':
+ conf_dict.setdefault('proxy', {})['hostname'] = ipt.get_value()
+ elif ipt.name == 'proxy_port':
+ conf_dict.setdefault('proxy', {})['port'] = ipt.get_value()
+ elif ipt.name == 'proxy_hostnames':
+ conf_dict.setdefault('proxy', {})['proxy_hostnames'] = ipt.get_value()
+ elif ipt.name == 'proxy_peer_connections':
+ conf_dict.setdefault('proxy', {})['proxy_peer_connections'] = ipt.get_value()
else:
conf_dict[ipt.name] = ipt.get_value()
- if hasattr(ipt, "get_child"):
+ if hasattr(ipt, 'get_child'):
c = ipt.get_child()
conf_dict[c.name] = c.get_value()
@@ -115,7 +115,7 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler):
ipt.set_value(conf_dict[ipt.name])
except KeyError: # just ignore if it's not in dict
pass
- if hasattr(ipt, "get_child"):
+ if hasattr(ipt, 'get_child'):
try:
c = ipt.get_child()
c.set_value(conf_dict[c.name])
@@ -145,257 +145,257 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler):
class InterfacePane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Interface"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Interface'), preferences)
@overrides(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_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_header(_('General options'))
+
+ 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'])
from deluge.ui.util import lang
langs = lang.get_languages()
- langs.insert(0, ("", "System Default"))
- 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_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)
+ langs.insert(0, ('', 'System Default'))
+ 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_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)
class DownloadsPane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Downloads"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Downloads'), preferences)
@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_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("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_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_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('add_paused', _('Add Paused'), core_conf['add_paused'])
+ self.add_checked_input('pre_allocate_storage', _('Pre-Allocate disk space'),
+ core_conf['pre_allocate_storage'])
class NetworkPane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Network"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Network'), preferences)
@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.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"])
- listen_ports = core_conf["listen_ports"]
- self.infrom = self.add_int_spin_input("listen_ports_from", " %s:" % _("From"),
+ 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.set_depend(inrand, inverse=True)
- self.into = self.add_int_spin_input("listen_ports_to", " %s:" % _("To"),
+ 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"])
- out_ports = core_conf["outgoing_ports"]
- self.outfrom = self.add_int_spin_input("out_ports_from", " %s:" % _("From"),
+ self.add_header(_('Outgoing Ports'), space_above=True)
+ 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.set_depend(outrand, inverse=True)
- self.outto = self.add_int_spin_input("out_ports_to", " %s:" % _("To"),
+ 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(_("Interface"), space_above=True)
- self.add_text_input("listen_interface", "%s:" % _("IP address of the interface to listen on "
- "(leave empty for default)"),
- core_conf["listen_interface"])
+ self.add_header(_('Interface'), space_above=True)
+ self.add_text_input('listen_interface', '%s:' % _('IP address of the interface to listen on '
+ '(leave empty for default)'),
+ core_conf['listen_interface'])
- self.add_header("TOS", space_above=True)
- self.add_text_input("peer_tos", "Peer TOS Byte:", core_conf["peer_tos"])
+ self.add_header('TOS', space_above=True)
+ self.add_text_input('peer_tos', 'Peer TOS Byte:', core_conf['peer_tos'])
- self.add_header(_("Network Extras"), space_above=True)
- self.add_checked_input("upnp", "UPnP", core_conf["upnp"])
- self.add_checked_input("natpmp", "NAT-PMP", core_conf["natpmp"])
- self.add_checked_input("utpex", "Peer Exchange", core_conf["utpex"])
- self.add_checked_input("lsd", "LSD", core_conf["lsd"])
- self.add_checked_input("dht", "DHT", core_conf["dht"])
+ self.add_header(_('Network Extras'), space_above=True)
+ self.add_checked_input('upnp', 'UPnP', core_conf['upnp'])
+ self.add_checked_input('natpmp', 'NAT-PMP', core_conf['natpmp'])
+ self.add_checked_input('utpex', 'Peer Exchange', core_conf['utpex'])
+ self.add_checked_input('lsd', 'LSD', core_conf['lsd'])
+ 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_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)
class BandwidthPane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Bandwidth"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Bandwidth'), preferences)
@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_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_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_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)
class OtherPane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Other"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Other'), preferences)
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
- self.add_header(_("System Information"))
- self.add_info_field("info1", " Help us improve Deluge by sending us your", "")
- self.add_info_field("info2", " Python version, PyGTK version, OS and processor", "")
- self.add_info_field("info3", " types. Absolutely no other information is sent.", "")
- self.add_checked_input("send_info", _("Yes, please send anonymous statistics."), core_conf["send_info"])
- self.add_header(_("GeoIP Database"), space_above=True)
- self.add_text_input("geoip_db_location", "Location:", core_conf["geoip_db_location"])
+ self.add_header(_('System Information'))
+ self.add_info_field('info1', ' Help us improve Deluge by sending us your', '')
+ self.add_info_field('info2', ' Python version, PyGTK version, OS and processor', '')
+ self.add_info_field('info3', ' types. Absolutely no other information is sent.', '')
+ self.add_checked_input('send_info', _('Yes, please send anonymous statistics.'), core_conf['send_info'])
+ self.add_header(_('GeoIP Database'), space_above=True)
+ self.add_text_input('geoip_db_location', 'Location:', core_conf['geoip_db_location'])
class DaemonPane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Daemon"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Daemon'), preferences)
@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"],
+ 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_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_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'])
class QueuePane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Queue"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Queue'), preferences)
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
- 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"],
+ 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_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"],
+ 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"],
+ 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_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):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Proxy"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Proxy'), preferences)
@overrides(BasePreferencePane)
def create_pane(self, core_conf, console_config):
- self.add_header(_("Proxy Settings"))
- self.add_header(_("Proxy"), space_above=True)
- proxy = core_conf["proxy"]
- self.add_int_spin_input("proxy_type", "%s:" % _("Type"), proxy["type"], min_val=0, max_val=5)
- self.add_info_field("proxy_info_1", " 0: None 1: Socks4 2: Socks5", "")
- self.add_info_field("proxy_info_2", " 3: Socks5 Auth 4: HTTP 5: HTTP Auth", "")
- self.add_text_input("proxy_username", "%s:" % _("Username"), proxy["username"])
- self.add_text_input("proxy_password", "%s:" % _("Password"), proxy["password"])
- self.add_text_input("proxy_hostname", "%s:" % _("Hostname"), proxy["hostname"])
- self.add_int_spin_input("proxy_port", "%s:" % _("Port"), proxy["port"], min_val=0, max_val=65535)
- self.add_checked_input("proxy_hostnames", _("Proxy hostnames"), proxy["proxy_hostnames"])
- self.add_checked_input("proxy_peer_connections", _("Proxy peer connections"), proxy["proxy_peer_connections"])
-
- self.add_header(_("I2P Proxy"), space_above=True)
- self.add_text_input("i2p_hostname", "%s:" % _("Hostname"),
- core_conf["i2p_proxy"]["hostname"])
- self.add_int_spin_input("i2p_port",
- "%s:" % _("Port"), core_conf["i2p_proxy"]["port"], min_val=0, max_val=65535)
- self.add_checked_input("anonymous_mode", _("Anonymous Mode"), core_conf["anonymous_mode"])
+ self.add_header(_('Proxy Settings'))
+ self.add_header(_('Proxy'), space_above=True)
+ proxy = core_conf['proxy']
+ self.add_int_spin_input('proxy_type', '%s:' % _('Type'), proxy['type'], min_val=0, max_val=5)
+ self.add_info_field('proxy_info_1', ' 0: None 1: Socks4 2: Socks5', '')
+ self.add_info_field('proxy_info_2', ' 3: Socks5 Auth 4: HTTP 5: HTTP Auth', '')
+ self.add_text_input('proxy_username', '%s:' % _('Username'), proxy['username'])
+ self.add_text_input('proxy_password', '%s:' % _('Password'), proxy['password'])
+ self.add_text_input('proxy_hostname', '%s:' % _('Hostname'), proxy['hostname'])
+ self.add_int_spin_input('proxy_port', '%s:' % _('Port'), proxy['port'], min_val=0, max_val=65535)
+ self.add_checked_input('proxy_hostnames', _('Proxy hostnames'), proxy['proxy_hostnames'])
+ self.add_checked_input('proxy_peer_connections', _('Proxy peer connections'), proxy['proxy_peer_connections'])
+
+ self.add_header(_('I2P Proxy'), space_above=True)
+ self.add_text_input('i2p_hostname', '%s:' % _('Hostname'),
+ core_conf['i2p_proxy']['hostname'])
+ self.add_int_spin_input('i2p_port',
+ '%s:' % _('Port'), core_conf['i2p_proxy']['port'], min_val=0, max_val=65535)
+ self.add_checked_input('anonymous_mode', _('Anonymous Mode'), core_conf['anonymous_mode'])
class CachePane(BasePreferencePane):
def __init__(self, preferences):
- BasePreferencePane.__init__(self, " %s " % _("Cache"), preferences)
+ BasePreferencePane.__init__(self, ' %s ' % _('Cache'), preferences)
self.created = False
@overrides(BasePreferencePane)
@@ -404,32 +404,32 @@ 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"],
+ 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"],
+ 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["blocks_written"])
- self.add_info_field("writes", " %s:" % _("Writes"), status["writes"])
- 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["blocks_read"])
- self.add_info_field("blocks_read_hit",
- " %s:" % _("Blocks Read hit"), status["blocks_read_hit"])
- self.add_info_field("reads",
- " %s:" % _("Reads"), status["reads"])
- 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["cache_size"])
- self.add_info_field("read_cache_size",
- " %s:" % _("Read Cache Size"), status["read_cache_size"])
+ self.add_header(' %s' % _('Write'), space_above=True)
+ self.add_info_field('blocks_written', ' %s:' % _('Blocks Written'), status['blocks_written'])
+ self.add_info_field('writes', ' %s:' % _('Writes'), status['writes'])
+ 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['blocks_read'])
+ self.add_info_field('blocks_read_hit',
+ ' %s:' % _('Blocks Read hit'), status['blocks_read_hit'])
+ self.add_info_field('reads',
+ ' %s:' % _('Reads'), status['reads'])
+ 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['cache_size'])
+ self.add_info_field('read_cache_size',
+ ' %s:' % _('Read Cache Size'), status['read_cache_size'])
@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 b083cd915..77adc5db0 100644
--- a/deluge/ui/console/modes/preferences/preferences.py
+++ b/deluge/ui/console/modes/preferences/preferences.py
@@ -74,11 +74,11 @@ 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)
@@ -117,7 +117,7 @@ class Preferences(BaseMode, PopupsHandler):
CachePane(self)
]
- self.action_input = SelectInput(self, None, None, [_("Cancel"), _("Apply"), _("OK")], [0, 1, 2], 0)
+ self.action_input = SelectInput(self, None, None, [_('Cancel'), _('Apply'), _('OK')], [0, 1, 2], 0)
def load_config(self):
if self.config_loaded:
@@ -160,7 +160,7 @@ 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.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)
@@ -187,7 +187,7 @@ class Preferences(BaseMode, PopupsHandler):
@overrides(BaseMode)
def refresh(self):
- if not component.get("ConsoleUI").is_active_mode(self) or not self.config_loaded:
+ if not component.get('ConsoleUI').is_active_mode(self) or not self.config_loaded:
return
if self.popup is None and self.messages:
@@ -248,13 +248,13 @@ class Preferences(BaseMode, PopupsHandler):
# are ever reordered, so do it the slightly slower but safer way
if isinstance(pane, InterfacePane):
pane.add_config_values(new_console_config)
- for k in ["ring_bell", "language"]:
+ for k in ['ring_bell', 'language']:
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"]:
- didupdate = update_conf_value(k, new_console_config, self.console_config["cmdline"], 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']:
+ didupdate = update_conf_value(k, new_console_config, self.console_config['cmdline'], didupdate)
if didupdate:
self.parent_mode.on_config_changed()
@@ -278,7 +278,7 @@ class Preferences(BaseMode, PopupsHandler):
self.back_to_parent()
def back_to_parent(self):
- component.get("ConsoleUI").set_mode(self.parent_mode.mode_name)
+ component.get('ConsoleUI').set_mode(self.parent_mode.mode_name)
@overrides(BaseMode)
def read_input(self):
@@ -291,7 +291,7 @@ class Preferences(BaseMode, PopupsHandler):
return
if util.is_printable_char(c):
- if chr(c) == "Q":
+ if chr(c) == 'Q':
from twisted.internet import reactor
if client.connected():
def on_disconnect(result):
@@ -300,8 +300,8 @@ class Preferences(BaseMode, PopupsHandler):
else:
reactor.stop()
return
- elif chr(c) == "h":
- self.push_popup(MessagePopup(self, "Preferences Help", HELP_STR))
+ elif chr(c) == 'h':
+ self.push_popup(MessagePopup(self, 'Preferences Help', HELP_STR))
if self.sidebar.has_focus() and c == util.KEY_ESC:
self.back_to_parent()
diff --git a/deluge/ui/console/modes/torrentdetail.py b/deluge/ui/console/modes/torrentdetail.py
index 7957faf55..95f934ce8 100644
--- a/deluge/ui/console/modes/torrentdetail.py
+++ b/deluge/ui/console/modes/torrentdetail.py
@@ -72,33 +72,33 @@ 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"]
+ 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']
self.file_list = None
self.current_file = None
self.current_file_idx = 0
self.file_off = 0
self.more_to_draw = False
self.full_names = None
- self.column_string = ""
+ self.column_string = ''
self.files_sep = None
self.marked = {}
BaseMode.__init__(self, stdscr, encoding)
- self.column_names = ["Filename", "Size", "Progress", "Priority"]
+ self.column_names = ['Filename', 'Size', 'Progress', 'Priority']
self.__update_columns()
self._listing_start = self.rows // 2
self._listing_space = self._listing_start - self._listing_start
- client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event)
- client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event)
- client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event)
+ client.register_event_handler('TorrentFileRenamedEvent', self._on_torrentfilerenamed_event)
+ client.register_event_handler('TorrentFolderRenamedEvent', self._on_torrentfolderrenamed_event)
+ client.register_event_handler('TorrentRemovedEvent', self._on_torrentremoved_event)
util.safe_curs_set(util.Curser.INVISIBLE)
self.stdscr.notimeout(0)
@@ -108,7 +108,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
self.file_list = None
def back_to_overview(self):
- component.get("ConsoleUI").set_mode(self.parent_mode.mode_name)
+ component.get('ConsoleUI').set_mode(self.parent_mode.mode_name)
@overrides(component.Component)
def start(self):
@@ -120,7 +120,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
self.set_torrent_id(torrentid)
if self.torrentid:
- component.get("SessionProxy").get_torrent_status(self.torrentid,
+ component.get('SessionProxy').get_torrent_status(self.torrentid,
self._status_keys).addCallback(self.set_state)
@overrides(BaseMode)
@@ -139,31 +139,31 @@ 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"]])
+ if state.get('files'):
+ self.full_names = dict([(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"])
+ 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'])
else:
- self.files_sep = "{!green,black,bold,underline!}%s" % (("Files (File list unknown)").center(self.cols))
+ self.files_sep = '{!green,black,bold,underline!}%s' % (('Files (File list unknown)').center(self.cols))
need_prio_update = True
- self.__fill_progress(self.file_list, state["file_progress"])
+ self.__fill_progress(self.file_list, state['file_progress'])
- for i, prio in enumerate(state["file_priorities"]):
+ for i, prio in enumerate(state['file_priorities']):
if self.file_dict[i][6] != prio:
need_prio_update = True
self.file_dict[i][6] = prio
if need_prio_update:
self.__fill_prio(self.file_list)
- del state["file_progress"]
- del state["file_priorities"]
+ del state['file_progress']
+ del state['file_priorities']
self.torrent_state = state
self.refresh()
@@ -186,15 +186,15 @@ class TorrentDetail(BaseMode, PopupsHandler):
dir_idx = len(torrent_files)
for torrent_file in torrent_files:
cur = file_list
- paths = torrent_file["path"].split("/")
+ paths = torrent_file['path'].split('/')
for path in paths:
if not cur or path != cur[-1][0]:
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"]]]
- file_dict[torrent_file["index"]] = entry
+ 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']]]
+ file_dict[torrent_file['index']] = entry
else:
entry = [path, dir_idx, -1, child_list, False, 0, -1]
file_dict[dir_idx] = entry
@@ -261,7 +261,7 @@ 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_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):
@@ -270,31 +270,31 @@ class TorrentDetail(BaseMode, PopupsHandler):
def _on_torrentfilerenamed_event(self, torrent_id, index, new_name):
if torrent_id == self.torrentid:
- self.file_dict[index][0] = new_name.split("/")[-1]
- component.get("SessionProxy").get_torrent_status(
+ self.file_dict[index][0] = new_name.split('/')[-1]
+ component.get('SessionProxy').get_torrent_status(
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:
fe = None
fl = None
- for i in old_folder.strip("/").split("/"):
+ for i in old_folder.strip('/').split('/'):
if not fl:
fe = fl = self.file_list
- s = [files for files in fl if files[0].strip("/") == i][0]
+ s = [files for files in fl if files[0].strip('/') == i][0]
fe = s
fl = s[3]
- fe[0] = new_folder.strip("/").rpartition("/")[-1]
+ fe[0] = new_folder.strip('/').rpartition('/')[-1]
# self.__get_file_by_name(old_folder, self.file_list)[0] = new_folder.strip("/")
- component.get("SessionProxy").get_torrent_status(
+ component.get('SessionProxy').get_torrent_status(
self.torrentid, self._status_keys).addCallback(self.set_state)
def draw_files(self, files, depth, off, idx):
- color_selected = "blue"
- color_partially_selected = "magenta"
- color_highlighted = "white"
+ color_selected = 'blue'
+ color_partially_selected = 'magenta'
+ color_highlighted = 'white'
for fl in files:
# from sys import stderr
# print >> stderr, fl[6]
@@ -304,20 +304,20 @@ class TorrentDetail(BaseMode, PopupsHandler):
return -1, -1
# default color values
- fg = "white"
- bg = "black"
- attr = ""
+ fg = 'white'
+ bg = 'black'
+ attr = ''
if fl[6] == -2:
pass # Mixed
elif fl[6] == 0:
- fg = "red" # Do Not Download
+ fg = 'red' # Do Not Download
elif fl[6] == 1:
pass # Normal
elif fl[6] <= 6:
- fg = "yellow" # High
+ fg = 'yellow' # High
elif fl[6] == 7:
- fg = "green" # Highest
+ fg = 'green' # Highest
if idx >= self.file_off:
# set fg/bg colors based on whether the file is selected/marked or not
@@ -327,7 +327,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
if fl[3]:
if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]):
bg = color_partially_selected
- attr = "bold"
+ attr = 'bold'
if idx == self.current_file_idx:
self.current_file = fl
@@ -338,29 +338,29 @@ class TorrentDetail(BaseMode, PopupsHandler):
if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]):
fg = color_partially_selected
else:
- if fg == "white":
- fg = "black"
- attr = "bold"
+ if fg == 'white':
+ fg = 'black'
+ attr = 'bold'
if attr:
- color_string = "{!%s,%s,%s!}" % (fg, bg, attr)
+ color_string = '{!%s,%s,%s!}' % (fg, bg, attr)
else:
- color_string = "{!%s,%s!}" % (fg, bg)
+ color_string = '{!%s,%s!}' % (fg, bg)
# actually draw the dir/file string
if fl[3] and fl[4]: # this is an expanded directory
- xchar = "v"
+ xchar = 'v'
elif fl[3]: # collapsed directory
- xchar = ">"
+ xchar = '>'
else: # file
- xchar = "-"
+ xchar = '-'
- r = format_row(["%s%s %s" % (" " * depth, xchar, fl[0]),
+ 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)
+ self.add_string(off, '%s%s' % (color_string, r), trim=False)
off += 1
if fl[3] and fl[4]:
@@ -410,12 +410,12 @@ class TorrentDetail(BaseMode, PopupsHandler):
def render_header(self, row):
status = self.torrent_state
- download_color = "{!info!}"
- if status["download_payload_rate"] > 0:
- download_color = colors.state_color["Downloading"]
+ download_color = '{!info!}'
+ if status['download_payload_rate'] > 0:
+ 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"],
+ 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))
if row:
row = self.add_string(row, s)
@@ -423,63 +423,63 @@ class TorrentDetail(BaseMode, PopupsHandler):
return s
# Name
- row = add_field("name", row)
+ row = add_field('name', row)
# State
- row = add_field("state", row)
+ row = add_field('state', row)
# Print DL info and ETA
- s = add_field("downloaded", 0, download_color)
- if status["progress"] != 100.0:
- s += "/%s" % fsize(status["total_wanted"])
- if status["download_payload_rate"] > 0:
- s += " {!yellow!}@ %s%s" % (download_color, fsize(status["download_payload_rate"]))
- s += add_field("eta", 0)
+ s = add_field('downloaded', 0, download_color)
+ if status['progress'] != 100.0:
+ s += '/%s' % fsize(status['total_wanted'])
+ if status['download_payload_rate'] > 0:
+ s += ' {!yellow!}@ %s%s' % (download_color, fsize(status['download_payload_rate']))
+ s += add_field('eta', 0)
if s:
row = self.add_string(row, s)
# Print UL info and ratio
- s = add_field("uploaded", 0, download_color)
- if status["upload_payload_rate"] > 0:
- s += " {!yellow!}@ %s%s" % (colors.state_color["Seeding"], fsize(status["upload_payload_rate"]))
- s += " " + add_field("ratio", 0)
+ s = add_field('uploaded', 0, download_color)
+ if status['upload_payload_rate'] > 0:
+ s += ' {!yellow!}@ %s%s' % (colors.state_color['Seeding'], fsize(status['upload_payload_rate']))
+ s += ' ' + add_field('ratio', 0)
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!}"
+ 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"]))
- if status["distributed_copies"]:
- s += "{!info!}%s: {!input!}%s" % (torrent_data_fields["seed_rank"]["name"], status["seed_rank"])
+ s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % (
+ 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)
# Time added
- row = add_field("time_added", row)
+ row = add_field('time_added', row)
# Time active
- row = add_field("active_time", row)
- if status["seeding_time"]:
- row = add_field("seeding_time", row)
+ row = add_field('active_time', row)
+ if status['seeding_time']:
+ row = add_field('seeding_time', row)
# Download Folder
- row = add_field("download_location", row)
+ row = add_field('download_location', row)
# Seed Rank
- row = add_field("seed_rank", row)
+ row = add_field('seed_rank', row)
# Last seen complete
- row = add_field("last_seen_complete", row)
+ row = add_field('last_seen_complete', row)
# Owner
- if status["owner"]:
- row = add_field("owner", row)
+ if status['owner']:
+ row = add_field('owner', row)
return row
@overrides(BaseMode)
@@ -492,7 +492,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
if self.torrent_state:
row = self.render_header(row)
else:
- self.add_string(1, "Waiting for torrent state")
+ self.add_string(1, 'Waiting for torrent state')
row += 1
@@ -509,7 +509,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
self.more_to_draw = False
self.draw_files(self.file_list, 0, row, 0)
- if not component.get("ConsoleUI").is_active_mode(self):
+ if not component.get('ConsoleUI').is_active_mode(self):
return
self.stdscr.noutrefresh()
@@ -580,14 +580,14 @@ class TorrentDetail(BaseMode, PopupsHandler):
return self.do_priority(data, kwargs[data], was_empty)
if self.marked:
- popup = SelectablePopup(self, "Set File Priority", popup_func, border_off_north=1)
- popup.add_line("do_not_download", "_Do Not Download",
- cb_arg=FILE_PRIORITY["Do Not Download"], foreground="red")
- 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="yellow")
- popup.add_line("highest_priority", "H_ighest Priority",
- cb_arg=FILE_PRIORITY["Highest Priority"], foreground="green")
+ popup = SelectablePopup(self, 'Set File Priority', popup_func, border_off_north=1)
+ popup.add_line('do_not_download', '_Do Not Download',
+ cb_arg=FILE_PRIORITY['Do Not Download'], foreground='red')
+ 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='yellow')
+ popup.add_line('highest_priority', 'H_ighest Priority',
+ cb_arg=FILE_PRIORITY['Highest Priority'], foreground='green')
popup._selected = 1
self.push_popup(popup)
@@ -656,7 +656,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
def __get_file_by_name(self, name, file_list, idx=0):
for element in file_list:
- if element[0].strip("/") == name.strip("/"):
+ if element[0].strip('/') == name.strip('/'):
return element
if element[3] and element[4]:
i = self.__get_file_by_name(name, element[3], idx + 1)
@@ -732,7 +732,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
return (idx, true_idx)
- def _get_full_folder_path(self, num, file_list=None, path="", idx=0):
+ def _get_full_folder_path(self, num, file_list=None, path='', idx=0):
if not file_list:
file_list = self.file_list
@@ -741,9 +741,9 @@ class TorrentDetail(BaseMode, PopupsHandler):
idx += 1
continue
if num == idx:
- return "%s%s/" % (path, element[0])
+ return '%s%s/' % (path, element[0])
if element[4]:
- i = self._get_full_folder_path(num, element[3], path + element[0] + "/", idx + 1)
+ i = self._get_full_folder_path(num, element[3], path + element[0] + '/', idx + 1)
if not isinstance(i, int):
return i
idx = i
@@ -762,7 +762,7 @@ 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)",
+ self.report_message('Error (Enter to close)',
"Sorry, you can't rename multiple files, please clear "
"selection with {!info!}'c'{!normal!} key")
else:
@@ -774,27 +774,27 @@ class TorrentDetail(BaseMode, PopupsHandler):
if _file[3]:
def do_rename(result, **kwargs):
- if not result or not result["new_foldername"]["value"] or kwargs.get("close", False):
+ if not result or not result['new_foldername']['value'] or kwargs.get('close', False):
self.popup.close(None, call_cb=False)
return
old_fname = self._get_full_folder_path(self.current_file_idx)
- new_fname = "%s/%s/" % (old_fname.strip("/").rpartition("/")[0], result["new_foldername"]["value"])
+ new_fname = '%s/%s/' % (old_fname.strip('/').rpartition('/')[0], result['new_foldername']['value'])
self._do_rename_folder(tid, old_fname, new_fname)
- popup = InputPopup(self, "Rename folder (Esc to cancel)", close_cb=do_rename)
- popup.add_text_input("new_foldername", "Enter new folder name:", old_filename.strip("/"), complete=True)
+ popup = InputPopup(self, 'Rename folder (Esc to cancel)', close_cb=do_rename)
+ popup.add_text_input('new_foldername', 'Enter new folder name:', old_filename.strip('/'), complete=True)
self.push_popup(popup)
else:
def do_rename(result, **kwargs):
- if not result or not result["new_filename"]["value"] or kwargs.get("close", False):
+ if not result or not result['new_filename']['value'] or kwargs.get('close', False):
self.popup.close(None, call_cb=False)
return
- fname = "%s/%s" % (self.full_names[idx].rpartition("/")[0], result["new_filename"]["value"])
+ fname = '%s/%s' % (self.full_names[idx].rpartition('/')[0], result['new_filename']['value'])
self._do_rename_file(tid, idx, fname)
- popup = InputPopup(self, " Rename file ", close_cb=do_rename)
- popup.add_text_input("new_filename", "Enter new filename:", old_filename, complete=True)
+ popup = InputPopup(self, ' Rename file ', close_cb=do_rename)
+ popup.add_text_input('new_filename', 'Enter new filename:', old_filename, complete=True)
self.push_popup(popup)
@overrides(BaseMode)
@@ -853,7 +853,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
torrent_actions_popup(self, [self.torrentid], action=ACTION.TORRENT_OPTIONS)
return
elif c == ord('h'):
- self.push_popup(MessagePopup(self, "Help", HELP_STR, width_req=0.75))
+ self.push_popup(MessagePopup(self, 'Help', HELP_STR, width_req=0.75))
elif c == ord('j'):
self.file_list_up()
elif c == ord('k'):
diff --git a/deluge/ui/console/modes/torrentlist/__init__.py b/deluge/ui/console/modes/torrentlist/__init__.py
index bc2952647..2d99252c6 100644
--- a/deluge/ui/console/modes/torrentlist/__init__.py
+++ b/deluge/ui/console/modes/torrentlist/__init__.py
@@ -1,18 +1,18 @@
class ACTION(object):
- PAUSE = "pause"
- RESUME = "resume"
- REANNOUNCE = "update_tracker"
+ PAUSE = 'pause'
+ RESUME = 'resume'
+ REANNOUNCE = 'update_tracker'
EDIT_TRACKERS = 3
- RECHECK = "force_recheck"
- REMOVE = "remove_torrent"
+ RECHECK = 'force_recheck'
+ REMOVE = 'remove_torrent'
REMOVE_DATA = 6
REMOVE_NODATA = 7
- DETAILS = "torrent_details"
- MOVE_STORAGE = ("move_download_folder")
- QUEUE = "queue"
- QUEUE_TOP = "queue_top"
- QUEUE_UP = "queue_up"
- QUEUE_DOWN = "queue_down"
- QUEUE_BOTTOM = "queue_bottom"
- TORRENT_OPTIONS = "torrent_options"
+ DETAILS = 'torrent_details'
+ MOVE_STORAGE = ('move_download_folder')
+ QUEUE = 'queue'
+ QUEUE_TOP = 'queue_top'
+ QUEUE_UP = 'queue_up'
+ QUEUE_DOWN = 'queue_down'
+ QUEUE_BOTTOM = 'queue_bottom'
+ TORRENT_OPTIONS = 'torrent_options'
diff --git a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
index e7d6266b2..40a726495 100644
--- a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
+++ b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py
@@ -18,70 +18,70 @@ log = logging.getLogger(__name__)
def report_add_status(torrentlist, succ_cnt, fail_cnt, fail_msgs):
if fail_cnt == 0:
- torrentlist.report_message("Torrents Added", "{!success!}Successfully added %d torrent(s)" % succ_cnt)
+ torrentlist.report_message('Torrents Added', '{!success!}Successfully added %d torrent(s)' % succ_cnt)
else:
- msg = ("{!error!}Failed to add the following %d torrent(s):\n {!input!}" % fail_cnt) + "\n ".join(fail_msgs)
+ msg = ('{!error!}Failed to add the following %d torrent(s):\n {!input!}' % fail_cnt) + '\n '.join(fail_msgs)
if succ_cnt != 0:
- msg += "\n \n{!success!}Successfully added %d torrent(s)" % succ_cnt
- torrentlist.report_message("Torrent Add Report", msg)
+ msg += '\n \n{!success!}Successfully added %d torrent(s)' % succ_cnt
+ torrentlist.report_message('Torrent Add Report', msg)
def show_torrent_add_popup(torrentlist):
def do_add_from_url(data=None, **kwargs):
torrentlist.pop_popup()
- if not data or kwargs.get("close", False):
+ if not data or kwargs.get('close', False):
return
def fail_cb(msg, url):
- log.debug("failed to add torrent: %s: %s", url, msg)
- error_msg = "{!input!} * %s: {!error!}%s" % (url, msg)
+ log.debug('failed to add torrent: %s: %s', url, msg)
+ error_msg = '{!input!} * %s: {!error!}%s' % (url, msg)
report_add_status(torrentlist, 0, 1, [error_msg])
def success_cb(tid, url):
if tid:
- log.debug("added torrent: %s (%s)", url, tid)
+ log.debug('added torrent: %s (%s)', url, tid)
report_add_status(torrentlist, 1, 0, [])
else:
- fail_cb("Already in session (probably)", url)
+ fail_cb('Already in session (probably)', url)
- url = data["url"]["value"]
+ url = data['url']['value']
if not url:
return
- t_options = {"download_location": data["path"]["value"], "add_paused": data["add_paused"]["value"]}
+ t_options = {'download_location': data['path']['value'], 'add_paused': data['add_paused']['value']}
if deluge.common.is_magnet(url):
client.core.add_torrent_magnet(url, t_options).addCallback(success_cb, url).addErrback(fail_cb, url)
elif deluge.common.is_url(url):
client.core.add_torrent_url(url, t_options).addCallback(success_cb, url).addErrback(fail_cb, url)
else:
- torrentlist.report_message("Error", "{!error!}Invalid URL or magnet link: %s" % url)
+ 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", ""),
+ 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_select_input("add_paused", "Add Paused:", ["Yes", "No"], [True, False], add_paused)
+ popup.add_select_input('add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], add_paused)
torrentlist.push_popup(popup)
def option_chosen(selected, *args, **kwargs):
- if not selected or selected == "cancel":
+ if not selected or selected == 'cancel':
torrentlist.pop_popup()
return
- if selected == "file":
- torrentlist.consoleui.set_mode("AddTorrents")
- elif selected == "url":
+ if selected == 'file':
+ torrentlist.consoleui.set_mode('AddTorrents')
+ elif selected == 'url':
show_add_url_popup()
- popup = SelectablePopup(torrentlist, "Add torrent", option_chosen)
- popup.add_line("file", "- From _File(s)", use_underline=True)
- popup.add_line("url", "- From _URL or Magnet", use_underline=True)
- popup.add_line("cancel", "- _Cancel", use_underline=True)
+ popup = SelectablePopup(torrentlist, 'Add torrent', option_chosen)
+ popup.add_line('file', '- From _File(s)', use_underline=True)
+ popup.add_line('url', '- From _URL or Magnet', use_underline=True)
+ popup.add_line('cancel', '- _Cancel', use_underline=True)
torrentlist.push_popup(popup, clear=True)
diff --git a/deluge/ui/console/modes/torrentlist/filtersidebar.py b/deluge/ui/console/modes/torrentlist/filtersidebar.py
index 6b0a2373e..aff1f826c 100644
--- a/deluge/ui/console/modes/torrentlist/filtersidebar.py
+++ b/deluge/ui/console/modes/torrentlist/filtersidebar.py
@@ -30,22 +30,22 @@ class FilterSidebar(Sidebar, Component):
def __init__(self, torrentlist, config):
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,
+ width = self.config['torrentview']['sidebar_width']
+ Sidebar.__init__(self, torrentlist, width, height, title=' Filter ', border_off_north=1,
allow_resize=True)
- Component.__init__(self, "FilterSidebar")
+ Component.__init__(self, 'FilterSidebar')
self.checked_index = 0
- kwargs = {"checked_char": "*", "unchecked_char": "-", "checkbox_format": " %s ", "col": 0}
- self.add_checked_input("All", "All", checked=True, **kwargs)
- self.add_checked_input("Active", "Active", **kwargs)
- self.add_checked_input("Downloading", "Downloading", color="green,black", **kwargs)
- self.add_checked_input("Seeding", "Seeding", color="cyan,black", **kwargs)
- self.add_checked_input("Paused", "Paused", **kwargs)
- self.add_checked_input("Error", "Error", color="red,black", **kwargs)
- self.add_checked_input("Checking", "Checking", color="blue,black", **kwargs)
- self.add_checked_input("Queued", "Queued", **kwargs)
- self.add_checked_input("Allocating", "Allocating", color="yellow,black", **kwargs)
- self.add_checked_input("Moving", "Moving", color="green,black", **kwargs)
+ kwargs = {'checked_char': '*', 'unchecked_char': '-', 'checkbox_format': ' %s ', 'col': 0}
+ self.add_checked_input('All', 'All', checked=True, **kwargs)
+ self.add_checked_input('Active', 'Active', **kwargs)
+ self.add_checked_input('Downloading', 'Downloading', color='green,black', **kwargs)
+ self.add_checked_input('Seeding', 'Seeding', color='cyan,black', **kwargs)
+ self.add_checked_input('Paused', 'Paused', **kwargs)
+ self.add_checked_input('Error', 'Error', color='red,black', **kwargs)
+ self.add_checked_input('Checking', 'Checking', color='blue,black', **kwargs)
+ self.add_checked_input('Queued', 'Queued', **kwargs)
+ self.add_checked_input('Allocating', 'Allocating', color='yellow,black', **kwargs)
+ self.add_checked_input('Moving', 'Moving', color='green,black', **kwargs)
@overrides(Component)
def update(self):
@@ -59,7 +59,7 @@ class FilterSidebar(Sidebar, Component):
def _cb_update_filter_tree(self, filter_items):
"""Callback function on client.core.get_filter_tree"""
- states = filter_items["state"]
+ states = filter_items['state']
largest_count = 0
largest_state_width = 0
for state in states:
@@ -74,7 +74,7 @@ class FilterSidebar(Sidebar, Component):
for state in states:
field = self.get_input(state[0])
if field:
- txt = ("%%-%ds%%%ds" % (filter_state_width, filter_count_width) % (state[0], state[1]))
+ txt = ('%%-%ds%%%ds' % (filter_state_width, filter_count_width) % (state[0], state[1]))
if field.set_message(txt):
changed = True
return changed
@@ -97,9 +97,9 @@ class FilterSidebar(Sidebar, Component):
@overrides(Sidebar)
def on_resize(self, width):
- sidebar_width = self.config["torrentview"]["sidebar_width"]
+ sidebar_width = self.config['torrentview']['sidebar_width']
if sidebar_width != width:
- self.config["torrentview"]["sidebar_width"] = width
+ self.config['torrentview']['sidebar_width'] = width
self.config.save()
self.resize_window(self.height, width)
self.parent.toggle_sidebar()
diff --git a/deluge/ui/console/modes/torrentlist/queue_mode.py b/deluge/ui/console/modes/torrentlist/queue_mode.py
index 917db396d..6c9cae62a 100644
--- a/deluge/ui/console/modes/torrentlist/queue_mode.py
+++ b/deluge/ui/console/modes/torrentlist/queue_mode.py
@@ -44,8 +44,8 @@ class QueueMode(object):
self.torrent_ids = torrent_ids
def set_statusbar_args(self, statusbar_args):
- statusbar_args["bottombar"] = "{!black,white!}Queue mode: change queue position of selected torrents."
- statusbar_args["bottombar_help"] = " Press [h] for help"
+ statusbar_args['bottombar'] = '{!black,white!}Queue mode: change queue position of selected torrents.'
+ statusbar_args['bottombar_help'] = ' Press [h] for help'
def update_cursor(self):
pass
@@ -57,19 +57,19 @@ class QueueMode(object):
if c in [util.KEY_ESC, util.KEY_BELL]: # If Escape key or CTRL-g, we abort
self.torrentslist.set_minor_mode(None)
elif c == ord('h'):
- popup = MessagePopup(self.torrentslist, "Help", QUEUE_MODE_HELP_STR, width_req=0.65, border_off_west=1)
+ popup = MessagePopup(self.torrentslist, 'Help', QUEUE_MODE_HELP_STR, width_req=0.65, border_off_west=1)
self.torrentslist.push_popup(popup, clear=True)
elif c in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_HOME, curses.KEY_END, curses.KEY_NPAGE, curses.KEY_PPAGE]:
action = key_to_action[c]
self.do_queue(action)
def move_selection(self, cb_arg, qact):
- if self.torrentslist.config["torrentview"]["move_selection"] is False:
+ if self.torrentslist.config['torrentview']['move_selection'] is False:
return
queue_length = 0
selected_num = 0
for tid in self.torrentview.curstate:
- tq = self.torrentview.curstate[tid]["queue"]
+ tq = self.torrentview.curstate[tid]['queue']
if tq != -1:
queue_length += 1
if tq in self.torrentview.marked:
@@ -107,9 +107,9 @@ class QueueMode(object):
client.core.queue_down(self.torrent_ids).addCallback(self.move_selection, qact)
def popup(self, **kwargs):
- popup = SelectablePopup(self.torrentslist, "Queue Action", self.do_queue, cb_args=kwargs, border_off_west=1)
- popup.add_line(ACTION.QUEUE_TOP, "_Top")
- popup.add_line(ACTION.QUEUE_UP, "_Up")
- popup.add_line(ACTION.QUEUE_DOWN, "_Down")
- popup.add_line(ACTION.QUEUE_BOTTOM, "_Bottom")
+ popup = SelectablePopup(self.torrentslist, 'Queue Action', self.do_queue, cb_args=kwargs, border_off_west=1)
+ popup.add_line(ACTION.QUEUE_TOP, '_Top')
+ popup.add_line(ACTION.QUEUE_UP, '_Up')
+ popup.add_line(ACTION.QUEUE_DOWN, '_Down')
+ popup.add_line(ACTION.QUEUE_BOTTOM, '_Bottom')
self.torrentslist.push_popup(popup)
diff --git a/deluge/ui/console/modes/torrentlist/search_mode.py b/deluge/ui/console/modes/torrentlist/search_mode.py
index c0b8eed7d..554a254f1 100644
--- a/deluge/ui/console/modes/torrentlist/search_mode.py
+++ b/deluge/ui/console/modes/torrentlist/search_mode.py
@@ -40,12 +40,12 @@ SEARCH_START_REACHED = 3
SEARCH_END_REACHED = 4
SEARCH_FORMAT = {
- SEARCH_EMPTY: "{!black,white!}Search torrents: %s{!black,white!}",
- SEARCH_SUCCESS: "{!black,white!}Search torrents: {!black,green!}%s{!black,white!}",
- SEARCH_FAILING: "{!black,white!}Search torrents: {!black,red!}%s{!black,white!}",
+ SEARCH_EMPTY: '{!black,white!}Search torrents: %s{!black,white!}',
+ SEARCH_SUCCESS: '{!black,white!}Search torrents: {!black,green!}%s{!black,white!}',
+ 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)"
+ '{!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)'
}
@@ -56,15 +56,15 @@ class SearchMode(InputKeyHandler):
self.torrentlist = torrentlist
self.torrentview = torrentlist.torrentview
self.search_state = SEARCH_EMPTY
- self.search_string = ""
+ self.search_string = ''
def update_cursor(self):
util.safe_curs_set(util.Curser.VERY_VISIBLE)
move_cursor(self.torrentlist.stdscr, self.torrentlist.rows - 1, len(self.search_string) + 17)
def set_statusbar_args(self, statusbar_args):
- statusbar_args["bottombar"] = SEARCH_FORMAT[self.search_state] % self.search_string
- statusbar_args["bottombar_help"] = False
+ statusbar_args['bottombar'] = SEARCH_FORMAT[self.search_state] % self.search_string
+ statusbar_args['bottombar_help'] = False
def update_colors(self, tidx, colors):
if len(self.search_string) > 1:
@@ -74,14 +74,14 @@ class SearchMode(InputKeyHandler):
if tidx == self.torrentview.cursel:
pass
elif tidx in self.torrentview.marked:
- colors["bg"] = "magenta"
+ colors['bg'] = 'magenta'
else:
- colors["bg"] = "green"
- if colors["fg"] == "green":
- colors["fg"] = "black"
- colors["attr"] = "bold"
+ colors['bg'] = 'green'
+ if colors['fg'] == 'green':
+ colors['fg'] = 'black'
+ colors['attr'] = 'bold'
- def do_search(self, direction="first"):
+ def do_search(self, direction='first'):
"""
Performs a search on visible torrent and sets cursor to the match
@@ -91,11 +91,11 @@ class SearchMode(InputKeyHandler):
"""
search_space = list(enumerate(self.torrentview.torrent_names))
- if direction == "last":
+ if direction == 'last':
search_space = reversed(search_space)
- elif direction == "next":
+ elif direction == 'next':
search_space = search_space[self.torrentview.cursel + 1:]
- elif direction == "previous":
+ elif direction == 'previous':
search_space = reversed(search_space[:self.torrentview.cursel])
search_string = self.search_string.lower()
@@ -110,11 +110,11 @@ class SearchMode(InputKeyHandler):
self.torrentview.curoff = max(0, self.torrentview.cursel)
self.search_state = SEARCH_SUCCESS
return
- if direction in ["first", "last"]:
+ if direction in ['first', 'last']:
self.search_state = SEARCH_FAILING
- elif direction == "next":
+ elif direction == 'next':
self.search_state = SEARCH_END_REACHED
- elif direction == "previous":
+ elif direction == 'previous':
self.search_state = SEARCH_START_REACHED
@overrides(InputKeyHandler)
@@ -134,16 +134,16 @@ class SearchMode(InputKeyHandler):
self.torrentlist.set_minor_mode(None)
self.search_state = SEARCH_EMPTY
elif c == curses.KEY_DC:
- self.search_string = ""
+ self.search_string = ''
self.search_state = SEARCH_SUCCESS
elif c == curses.KEY_UP:
- self.do_search("previous")
+ self.do_search('previous')
elif c == curses.KEY_DOWN:
- self.do_search("next")
+ self.do_search('next')
elif c == curses.KEY_LEFT:
self.torrentlist.set_minor_mode(None)
self.search_state = SEARCH_EMPTY
- elif c == ord("/"):
+ elif c == ord('/'):
self.torrentlist.set_minor_mode(None)
self.search_state = SEARCH_EMPTY
elif c == curses.KEY_RIGHT:
@@ -151,21 +151,21 @@ class SearchMode(InputKeyHandler):
self.torrentlist.show_torrent_details(tid)
refresh = False
elif c == curses.KEY_HOME:
- self.do_search("first")
+ self.do_search('first')
elif c == curses.KEY_END:
- self.do_search("last")
+ self.do_search('last')
elif c in [10, curses.KEY_ENTER]:
self.last_mark = -1
tid = self.torrentview.current_torrent_id()
torrent_actions_popup(self.torrentlist, [tid], details=True)
refresh = False
elif c == util.KEY_ESC:
- self.search_string = ""
+ self.search_string = ''
self.search_state = SEARCH_EMPTY
elif c > 31 and c < 256:
old_search_string = self.search_string
stroke = chr(c)
- uchar = ""
+ uchar = ''
while not uchar:
try:
uchar = stroke.decode(self.torrentlist.encoding)
diff --git a/deluge/ui/console/modes/torrentlist/torrentactions.py b/deluge/ui/console/modes/torrentlist/torrentactions.py
index 1f3a034f2..53bc730b8 100644
--- a/deluge/ui/console/modes/torrentlist/torrentactions.py
+++ b/deluge/ui/console/modes/torrentlist/torrentactions.py
@@ -24,14 +24,14 @@ from . import ACTION
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"]
+ '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']
def action_error(error, mode):
rerr = error.value
- mode.report_message("An Error Occurred", "%s got error %s: %s" % (
+ mode.report_message('An Error Occurred', '%s got error %s: %s' % (
rerr.method, rerr.exception_type, rerr.exception_msg))
mode.refresh()
@@ -40,61 +40,61 @@ def action_remove(mode=None, torrent_ids=None, **kwargs):
def do_remove(*args, **kwargs):
data = args[0] if args else None
- if data is None or kwargs.get("close", False):
+ if data is None or kwargs.get('close', False):
mode.pop_popup()
return True
mode.clear_marked()
- remove_data = data["remove_files"]["value"]
+ remove_data = data['remove_files']['value']
def on_removed_finished(errors):
if errors:
- error_msgs = ""
+ error_msgs = ''
for t_id, e_msg in errors:
- error_msgs += "Error removing torrent %s : %s\n" % (t_id, e_msg)
- mode.report_message("Error(s) occured when trying to delete torrent(s).", error_msgs)
+ error_msgs += 'Error removing torrent %s : %s\n' % (t_id, e_msg)
+ mode.report_message('Error(s) occured when trying to delete torrent(s).', error_msgs)
mode.refresh()
d = client.core.remove_torrents(torrent_ids, remove_data)
d.addCallback(on_removed_finished)
def got_status(status):
- return (status["name"], status["state"])
+ return (status['name'], status['state'])
callbacks = []
for tid in torrent_ids:
- d = client.core.get_torrent_status(tid, ["name", "state"])
+ d = client.core.get_torrent_status(tid, ['name', 'state'])
callbacks.append(d.addCallback(got_status))
def remove_dialog(status):
status = [t_status[1] for t_status in status]
if len(torrent_ids) == 1:
- rem_msg = "{!info!}Remove the following torrent?{!input!}"
+ rem_msg = '{!info!}Remove the following torrent?{!input!}'
else:
- rem_msg = "{!info!}Remove the following %d torrents?{!input!}" % len(torrent_ids)
+ rem_msg = '{!info!}Remove the following %d torrents?{!input!}' % len(torrent_ids)
show_max = 6
for i, (name, state) in enumerate(status):
color = colors.state_color[state]
- rem_msg += "\n %s* {!input!}%s" % (color, name)
+ rem_msg += '\n %s* {!input!}%s' % (color, name)
if i == show_max - 1:
if i < len(status) - 1:
- rem_msg += "\n {!red!}And %i more" % (len(status) - show_max)
+ 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,
+ 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)
def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
- popup = MessagePopup(mode, "Torrent options", "Querying core, please wait...")
+ popup = MessagePopup(mode, 'Torrent options', 'Querying core, please wait...')
mode.push_popup(popup)
torrents = torrent_ids
options = {}
@@ -102,8 +102,8 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
def _do_set_torrent_options(torrent_ids, result):
options = {}
for opt, val in result.iteritems():
- if val["value"] not in ["multiple", None]:
- options[opt] = val["value"]
+ if val['value'] not in ['multiple', None]:
+ options[opt] = val['value']
client.core.set_torrent_options(torrent_ids, options)
def on_torrent_status(status):
@@ -111,7 +111,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
if key not in options:
options[key] = status[key]
elif options[key] != status[key]:
- options[key] = "multiple"
+ options[key] = 'multiple'
def create_popup(status):
mode.pop_popup()
@@ -120,14 +120,14 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
if result is None:
return
_do_set_torrent_options(torrent_ids, result)
- if kwargs.get("close", False):
+ if kwargs.get('close', False):
mode.pop_popup()
return True
- option_popup = InputPopup(mode, " Set Torrent Options ", close_cb=cb,
+ 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))
+ base_popup=kwargs.get('base_popup', None))
for field in torrent_options:
- caption = "{!info!}" + TORRENT_DATA_FIELD[field]["name"]
+ caption = '{!info!}' + TORRENT_DATA_FIELD[field]['name']
value = options[field]
field_type = type(value)
if field_type in [str, unicode]:
@@ -135,7 +135,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
value = str(value)
option_popup.add_text_input(field, caption, value)
elif field_type == bool:
- choices = (["Yes", "No"], [True, False], [True, False].index(options[field]))
+ choices = (['Yes', 'No'], [True, False], [True, False].index(options[field]))
option_popup.add_select_input(field, caption, choices[0], choices[1], choices[2])
elif field_type == float:
option_popup.add_float_spin_input(field, caption, value=value, min_val=-1)
@@ -146,7 +146,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
callbacks = []
for tid in torrents:
- deferred = component.get("SessionProxy").get_torrent_status(tid, torrent_options)
+ deferred = component.get('SessionProxy').get_torrent_status(tid, torrent_options)
callbacks.append(deferred.addCallback(on_torrent_status))
callbacks = defer.DeferredList(callbacks)
@@ -155,18 +155,18 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs):
def torrent_action(action, *args, **kwargs):
retval = False
- torrent_ids = kwargs.get("torrent_ids", None)
- mode = kwargs.get("mode", None)
+ torrent_ids = kwargs.get('torrent_ids', None)
+ mode = kwargs.get('mode', None)
if torrent_ids is None:
return
if action == ACTION.PAUSE:
- log.debug("Pausing torrents: %s", torrent_ids)
+ log.debug('Pausing torrents: %s', torrent_ids)
client.core.pause_torrent(torrent_ids).addErrback(action_error, mode)
retval = True
elif action == ACTION.RESUME:
- log.debug("Resuming torrents: %s", torrent_ids)
+ log.debug('Resuming torrents: %s', torrent_ids)
client.core.resume_torrent(torrent_ids).addErrback(action_error, mode)
retval = True
elif action == ACTION.QUEUE:
@@ -178,34 +178,34 @@ def torrent_action(action, *args, **kwargs):
return False
elif action == ACTION.MOVE_STORAGE:
def do_move(res, **kwargs):
- if res is None or kwargs.get("close", False):
+ if res is None or kwargs.get('close', False):
mode.pop_popup()
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"])
+ 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'])
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)
- popup = InputPopup(mode, "Move Download Folder", close_cb=do_move, border_off_east=1)
- popup.add_text_input("path", "Enter path to move to:", complete=True)
+ log.debug('Moving %s to: %s', torrent_ids, res['path']['value'])
+ client.core.move_storage(torrent_ids, res['path']['value']).addErrback(action_error, mode)
+ popup = InputPopup(mode, 'Move Download Folder', close_cb=do_move, border_off_east=1)
+ popup.add_text_input('path', 'Enter path to move to:', complete=True)
mode.push_popup(popup)
elif action == ACTION.RECHECK:
- log.debug("Rechecking torrents: %s", torrent_ids)
+ log.debug('Rechecking torrents: %s', torrent_ids)
client.core.force_recheck(torrent_ids).addErrback(action_error, mode)
retval = True
elif action == ACTION.REANNOUNCE:
- log.debug("Reannouncing torrents: %s", torrent_ids)
+ log.debug('Reannouncing torrents: %s', torrent_ids)
client.core.force_reannounce(torrent_ids).addErrback(action_error, mode)
retval = True
elif action == ACTION.DETAILS:
- log.debug("Torrent details")
+ log.debug('Torrent details')
tid = mode.torrentview.current_torrent_id()
if tid:
mode.show_torrent_details(tid)
else:
- log.error("No current torrent in _torrentaction, this is a bug")
+ log.error('No current torrent in _torrentaction, this is a bug')
elif action == ACTION.TORRENT_OPTIONS:
action_torrent_info(**kwargs)
@@ -219,23 +219,23 @@ 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},
+ 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")
+ popup.add_line(ACTION.PAUSE, '_Pause')
+ popup.add_line(ACTION.RESUME, '_Resume')
if details:
popup.add_divider()
- popup.add_line(ACTION.QUEUE, "Queue")
+ popup.add_line(ACTION.QUEUE, 'Queue')
popup.add_divider()
- popup.add_line(ACTION.REANNOUNCE, "_Update Tracker")
+ popup.add_line(ACTION.REANNOUNCE, '_Update Tracker')
popup.add_divider()
- popup.add_line(ACTION.REMOVE, "Remo_ve Torrent")
- popup.add_line(ACTION.RECHECK, "_Force Recheck")
- popup.add_line(ACTION.MOVE_STORAGE, "_Move Download Folder")
+ popup.add_line(ACTION.REMOVE, 'Remo_ve Torrent')
+ popup.add_line(ACTION.RECHECK, '_Force Recheck')
+ popup.add_line(ACTION.MOVE_STORAGE, '_Move Download Folder')
popup.add_divider()
if details:
- popup.add_line(ACTION.DETAILS, "Torrent _Details")
- popup.add_line(ACTION.TORRENT_OPTIONS, "Torrent _Options")
+ popup.add_line(ACTION.DETAILS, 'Torrent _Details')
+ popup.add_line(ACTION.TORRENT_OPTIONS, 'Torrent _Options')
mode.push_popup(popup)
diff --git a/deluge/ui/console/modes/torrentlist/torrentlist.py b/deluge/ui/console/modes/torrentlist/torrentlist.py
index e537acfdc..8c8faa1c5 100644
--- a/deluge/ui/console/modes/torrentlist/torrentlist.py
+++ b/deluge/ui/console/modes/torrentlist/torrentlist.py
@@ -102,14 +102,14 @@ where you input something
class TorrentList(BaseMode, PopupsHandler):
def __init__(self, stdscr, encoding=None):
- BaseMode.__init__(self, stdscr, encoding=encoding, do_refresh=False, depend=["SessionProxy"])
+ BaseMode.__init__(self, stdscr, encoding=encoding, do_refresh=False, depend=['SessionProxy'])
PopupsHandler.__init__(self)
self.messages = deque()
self.last_mark = -1
self.go_top = False
self.minor_mode = None
- self.consoleui = component.get("ConsoleUI")
+ self.consoleui = component.get('ConsoleUI')
self.coreconfig = self.consoleui.coreconfig
self.config = self.consoleui.config
self.sidebar = FilterSidebar(self, self.config)
@@ -128,7 +128,7 @@ class TorrentList(BaseMode, PopupsHandler):
self.torrentview.on_config_changed()
def toggle_sidebar(self):
- if self.config["torrentview"]["show_sidebar"]:
+ if self.config['torrentview']['show_sidebar']:
self.sidebar.show()
self.sidebar.resize_window(curses.LINES - 2, self.sidebar.width)
self.torrentview_panel.resize(curses.LINES - 1, curses.COLS - self.sidebar.width)
@@ -147,9 +147,9 @@ class TorrentList(BaseMode, PopupsHandler):
self.torrentview.on_config_changed()
self.toggle_sidebar()
- if self.config["first_run"]:
- self.push_popup(MessagePopup(self, "Welcome to Deluge", HELP_STR, width_req=0.65))
- self.config["first_run"] = False
+ if self.config['first_run']:
+ self.push_popup(MessagePopup(self, 'Welcome to Deluge', HELP_STR, width_req=0.65))
+ self.config['first_run'] = False
self.config.save()
if client.connected():
@@ -180,7 +180,7 @@ class TorrentList(BaseMode, PopupsHandler):
self.toggle_sidebar()
def show_torrent_details(self, tid):
- mode = self.consoleui.set_mode("TorrentDetail")
+ mode = self.consoleui.set_mode('TorrentDetail')
mode.update(tid)
def set_minor_mode(self, mode):
@@ -206,9 +206,9 @@ class TorrentList(BaseMode, PopupsHandler):
self.add_string(1, self.torrentview.column_string, scr=self.torrentview_panel)
# Update the status bars
- statusbar_args = {"scr": self.stdscr, "bottombar_help": True}
+ statusbar_args = {'scr': self.stdscr, 'bottombar_help': True}
if self.torrentview.curr_filter is not None:
- statusbar_args["topbar"] = ("%s {!filterstatus!}Current filter: %s"
+ statusbar_args['topbar'] = ('%s {!filterstatus!}Current filter: %s'
% (self.statusbars.topbar, self.torrentview.curr_filter))
if self.minor_mode:
@@ -258,7 +258,7 @@ class TorrentList(BaseMode, PopupsHandler):
self.refresh()
return ret
if util.is_printable_char(c):
- if chr(c) == "Q":
+ if chr(c) == 'Q':
from twisted.internet import reactor
if client.connected():
def on_disconnect(result):
@@ -267,14 +267,14 @@ class TorrentList(BaseMode, PopupsHandler):
else:
reactor.stop()
return
- elif chr(c) == "C":
- self.consoleui.set_mode("ConnectionManager")
+ elif chr(c) == 'C':
+ self.consoleui.set_mode('ConnectionManager')
return
- elif chr(c) == "q":
+ elif chr(c) == 'q':
self.torrentview.update_marked(self.torrentview.cursel)
self.set_minor_mode(QueueMode(self, self.torrentview._selected_torrent_ids()))
return
- elif chr(c) == "/":
+ elif chr(c) == '/':
self.set_minor_mode(SearchMode(self))
return
@@ -311,25 +311,25 @@ class TorrentList(BaseMode, PopupsHandler):
return
elif util.is_printable_char(c):
- if chr(c) == "a":
+ if chr(c) == 'a':
show_torrent_add_popup(self)
- elif chr(c) == "v":
+ elif chr(c) == 'v':
self._show_visible_columns_popup()
- elif chr(c) == "h":
- self.push_popup(MessagePopup(self, "Help", HELP_STR, width_req=0.65))
- elif chr(c) == "p":
- mode = self.consoleui.set_mode("Preferences")
+ elif chr(c) == 'h':
+ self.push_popup(MessagePopup(self, 'Help', HELP_STR, width_req=0.65))
+ elif chr(c) == 'p':
+ mode = self.consoleui.set_mode('Preferences')
mode.load_config()
return
- elif chr(c) == "e":
- self.consoleui.set_mode("EventView")
+ elif chr(c) == 'e':
+ self.consoleui.set_mode('EventView')
return
- elif chr(c) == "S":
- self.config["torrentview"]["show_sidebar"] = self.config["torrentview"]["show_sidebar"] is False
+ elif chr(c) == 'S':
+ self.config['torrentview']['show_sidebar'] = self.config['torrentview']['show_sidebar'] is False
self.config.save()
self.toggle_sidebar()
- elif chr(c) == "l":
- self.consoleui.set_mode("CmdLine", refresh=True)
+ elif chr(c) == 'l':
+ self.consoleui.set_mode('CmdLine', refresh=True)
return
self.refresh(affected_lines)
diff --git a/deluge/ui/console/modes/torrentlist/torrentview.py b/deluge/ui/console/modes/torrentlist/torrentview.py
index 7b35fd8a8..dd54e6dfd 100644
--- a/deluge/ui/console/modes/torrentlist/torrentview.py
+++ b/deluge/ui/console/modes/torrentlist/torrentview.py
@@ -20,12 +20,12 @@ 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):
@@ -42,47 +42,47 @@ def _queue_sort(v1, v2):
reverse_sort_fields = [
- "size",
- "download_speed",
- "upload_speed",
- "num_seeds",
- "num_peers",
- "distributed_copies",
- "time_added",
- "total_uploaded",
- "all_time_download",
- "total_remaining",
- "progress",
- "ratio",
- "seeding_time",
- "active_time"
+ 'size',
+ 'download_speed',
+ 'upload_speed',
+ 'num_seeds',
+ 'num_peers',
+ 'distributed_copies',
+ 'time_added',
+ 'total_uploaded',
+ 'all_time_download',
+ 'total_remaining',
+ 'progress',
+ 'ratio',
+ 'seeding_time',
+ 'active_time'
]
default_column_values = {
- "queue": {"width": 4, "visible": True},
- "name": {"width": -1, "visible": True},
- "size": {"width": 8, "visible": True},
- "progress": {"width": 7, "visible": True},
- "download_speed": {"width": 7, "visible": True},
- "upload_speed": {"width": 7, "visible": True},
- "state": {"width": 13},
- "eta": {"width": 8, "visible": True},
- "time_added": {"width": 15},
- "tracker": {"width": 15},
- "download_location": {"width": 15},
- "downloaded": {"width": 13},
- "uploaded": {"width": 7},
- "remaining": {"width": 13},
- "completed_time": {"width": 15},
- "last_seen_complete": {"width": 15},
- "max_upload_speed": {"width": 7},
+ 'queue': {'width': 4, 'visible': True},
+ 'name': {'width': -1, 'visible': True},
+ 'size': {'width': 8, 'visible': True},
+ 'progress': {'width': 7, 'visible': True},
+ 'download_speed': {'width': 7, 'visible': True},
+ 'upload_speed': {'width': 7, 'visible': True},
+ 'state': {'width': 13},
+ 'eta': {'width': 8, 'visible': True},
+ 'time_added': {'width': 15},
+ 'tracker': {'width': 15},
+ 'download_location': {'width': 15},
+ 'downloaded': {'width': 13},
+ 'uploaded': {'width': 7},
+ 'remaining': {'width': 13},
+ 'completed_time': {'width': 15},
+ 'last_seen_complete': {'width': 15},
+ 'max_upload_speed': {'width': 7},
}
default_columns = {}
for col_i, col_name in enumerate(torrentviewcolumns.column_pref_names):
- default_columns[col_name] = {"width": 10, "order": col_i, "visible": False}
+ default_columns[col_name] = {'width': 10, 'order': col_i, 'visible': False}
if col_name in default_column_values:
default_columns[col_name].update(default_column_values[col_name])
@@ -99,7 +99,7 @@ class TorrentView(InputKeyHandler):
self.sorted_ids = None
self.torrent_names = None
self.numtorrents = -1
- self.column_string = ""
+ self.column_string = ''
self.curoff = 0
self.marked = []
self.cursel = 0
@@ -124,7 +124,7 @@ class TorrentView(InputKeyHandler):
self.torrent_names = []
for torrent_id in self.sorted_ids:
ts = self.curstate[torrent_id]
- self.torrent_names.append(ts["name"])
+ self.torrent_names.append(ts['name'])
if refresh:
self.torrentlist.refresh()
@@ -132,7 +132,7 @@ class TorrentView(InputKeyHandler):
def set_torrent_filter(self, state):
self.curr_filter = state
filter_dict = {'state': [state]}
- if state == "All":
+ if state == 'All':
self.curr_filter = None
filter_dict = {}
self.filter_dict = filter_dict
@@ -208,13 +208,13 @@ class TorrentView(InputKeyHandler):
return False
def _sort_torrents(self, state):
- "sorts by primary and secondary sort fields"
+ 'sorts by primary and secondary sort fields'
if not state:
return {}
- s_primary = self.config["torrentview"]["sort_primary"]
- s_secondary = self.config["torrentview"]["sort_secondary"]
+ s_primary = self.config['torrentview']['sort_primary']
+ s_secondary = self.config['torrentview']['sort_secondary']
result = state
@@ -222,7 +222,7 @@ class TorrentView(InputKeyHandler):
# so it all works out
def sort_by_field(state, to_sort, field):
- field = torrent_data_fields[field]["status"][0]
+ field = torrent_data_fields[field]['status'][0]
reverse = field in reverse_sort_fields
# Get first element so we can check if it has given field
@@ -242,38 +242,38 @@ class TorrentView(InputKeyHandler):
if is_string:
to_sort = sorted(to_sort, _queue_sort, sort_key2, reverse)
- if field == "eta":
- to_sort = sorted(to_sort, key=lambda s: state.get(s)["eta"] == 0)
+ if field == 'eta':
+ to_sort = sorted(to_sort, key=lambda s: state.get(s)['eta'] == 0)
return to_sort
# Just in case primary and secondary fields are empty and/or
# both are too ambiguous, also sort by queue position first
- if "queue" not in [s_secondary, s_primary]:
- result = sort_by_field(state, result, "queue")
+ if 'queue' not in [s_secondary, s_primary]:
+ result = sort_by_field(state, result, 'queue')
if s_secondary != s_primary:
result = sort_by_field(state, result, s_secondary)
result = sort_by_field(state, result, s_primary)
- if self.config["torrentview"]["separate_complete"]:
- result = sorted(result, _queue_sort, lambda s: state.get(s).get("progress", 0) == 100.0)
+ if self.config['torrentview']['separate_complete']:
+ result = sorted(result, _queue_sort, lambda s: state.get(s).get('progress', 0) == 100.0)
return result
def _get_colors(self, row, tidx):
# default style
- colors = {"fg": "white", "bg": "black", "attr": None}
+ colors = {'fg': 'white', 'bg': 'black', 'attr': None}
if tidx in self.marked:
- colors.update({"bg": "blue", "attr": "bold"})
+ colors.update({'bg': 'blue', 'attr': 'bold'})
if tidx == self.cursel:
- col_selected = {"bg": "white", "fg": "black", "attr": "bold"}
+ col_selected = {'bg': 'white', 'fg': 'black', 'attr': 'bold'}
if tidx in self.marked:
- col_selected["fg"] = "blue"
+ col_selected['fg'] = 'blue'
colors.update(col_selected)
- colors["fg"] = state_fg_colors.get(row[1], colors["fg"])
+ colors['fg'] = state_fg_colors.get(row[1], colors['fg'])
if self.torrentlist.minor_mode:
self.torrentlist.minor_mode.update_colors(tidx, colors)
@@ -283,17 +283,17 @@ class TorrentView(InputKeyHandler):
# add all the torrents
if self.numtorrents == 0:
cols = self.torrentlist.torrentview_columns()
- msg = "No torrents match filter".center(cols)
- self.torrentlist.add_string(3, "{!info!}%s" % msg, scr=self.torrentlist.torrentview_panel)
+ msg = 'No torrents match filter'.center(cols)
+ self.torrentlist.add_string(3, '{!info!}%s' % msg, scr=self.torrentlist.torrentview_panel)
elif self.numtorrents == 0:
- self.torrentlist.add_string(1, "Waiting for torrents from core...")
+ self.torrentlist.add_string(1, 'Waiting for torrents from core...')
return
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"])
+ [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
@@ -317,36 +317,36 @@ class TorrentView(InputKeyHandler):
if (currow + self.torrentlist_offset - 1) > self.torrent_rows:
continue
colors = self._get_colors(row, tidx)
- if colors["attr"]:
- colorstr = "{!%(fg)s,%(bg)s,%(attr)s!}" % colors
+ if colors['attr']:
+ colorstr = '{!%(fg)s,%(bg)s,%(attr)s!}' % colors
else:
- colorstr = "{!%(fg)s,%(bg)s!}" % colors
+ colorstr = '{!%(fg)s,%(bg)s!}' % colors
- self.torrentlist.add_string(currow + self.torrentlist_offset, "%s%s" % (colorstr, row[0]),
+ 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,
+ 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):
- s_primary = self.config["torrentview"]["sort_primary"]
- s_secondary = self.config["torrentview"]["sort_secondary"]
+ s_primary = self.config['torrentview']['sort_primary']
+ s_secondary = self.config['torrentview']['sort_secondary']
changed = None
for col in default_columns:
- if col not in self.config["torrentview"]["columns"]:
- changed = self.config["torrentview"]["columns"][col] = default_columns[col]
+ if col not in self.config['torrentview']['columns']:
+ changed = self.config['torrentview']['columns'][col] = default_columns[col]
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
- for rf in ["state", "name", "queue", "progress"]:
+ for rf in ['state', 'name', 'queue', 'progress']:
if rf not in self.status_fields:
self.status_fields.append(rf)
@@ -359,7 +359,7 @@ class TorrentView(InputKeyHandler):
self.update_columns()
def update_columns(self):
- self.column_widths = [self.config["torrentview"]["columns"][col]["width"] for col in self.cols_to_show]
+ 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])
cols = self.torrentlist.torrentview_columns()
@@ -376,12 +376,12 @@ class TorrentView(InputKeyHandler):
if self.column_widths[i] < 0:
self.column_widths[i] = vw
- self.column_string = "{!header!}"
+ self.column_string = '{!header!}'
- primary_sort_col_name = self.config["torrentview"]["sort_primary"]
+ primary_sort_col_name = self.config['torrentview']['sort_primary']
for i, column in enumerate(self.cols_to_show):
- ccol = torrent_data_fields[column]["name"]
+ ccol = torrent_data_fields[column]['name']
width = self.column_widths[i]
# Trim the column if it's too long to fit
@@ -389,14 +389,14 @@ class TorrentView(InputKeyHandler):
ccol = ccol[:width - 1]
# Padding
- ccol += " " * (width - len(ccol))
+ ccol += ' ' * (width - len(ccol))
# Highlight the primary sort column
if column == primary_sort_col_name:
if i != len(self.cols_to_show) - 1:
- ccol = "{!black,green,bold!}%s{!header!}" % ccol
+ ccol = '{!black,green,bold!}%s{!header!}' % ccol
else:
- ccol = ("{!black,green,bold!}%s" % ccol)[:-1]
+ ccol = ('{!black,green,bold!}%s' % ccol)[:-1]
self.column_string += ccol
@@ -434,14 +434,14 @@ class TorrentView(InputKeyHandler):
torrent_actions_popup(self.torrentlist, self._selected_torrent_ids(), details=True, close_cb=on_close)
self.torrentlist.refresh()
- elif c == ord("j"):
+ elif c == ord('j'):
affected_lines = self._scroll_up(1)
- elif c == ord("k"):
+ elif c == ord('k'):
affected_lines = self._scroll_down(1)
- elif c == ord("m"):
+ elif c == ord('m'):
self.mark_unmark(self.cursel)
affected_lines = [self.cursel]
- elif c == ord("M"):
+ elif c == ord('M'):
if self.last_mark >= 0:
if self.cursel > self.last_mark:
mrange = range(self.last_mark, self.cursel + 1)
@@ -452,24 +452,24 @@ class TorrentView(InputKeyHandler):
else:
self.mark_unmark(self.cursel)
affected_lines = [self.cursel]
- elif c == ord("c"):
+ elif c == ord('c'):
self.clear_marked()
- elif c == ord("o"):
+ elif c == ord('o'):
if not self.marked:
added = self.update_marked(self.cursel, clear=True)
else:
self.last_mark = -1
torrent_actions_popup(self.torrentlist, self._selected_torrent_ids(), action=ACTION.TORRENT_OPTIONS)
- elif c in [ord(">"), ord("<")]:
+ elif c in [ord('>'), ord('<')]:
try:
- i = self.cols_to_show.index(self.config["torrentview"]["sort_primary"])
+ i = self.cols_to_show.index(self.config['torrentview']['sort_primary'])
except ValueError:
i = 0 if chr(c) == '<' else len(self.cols_to_show)
else:
i += 1 if chr(c) == '>' else -1
i = max(0, min(len(self.cols_to_show) - 1, i))
- self.config["torrentview"]["sort_primary"] = self.cols_to_show[i]
+ self.config['torrentview']['sort_primary'] = self.cols_to_show[i]
self.config.save()
self.on_config_changed()
self.update_columns()
diff --git a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
index b7872ca59..6b3855abd 100644
--- a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
+++ b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py
@@ -23,12 +23,12 @@ 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",
- "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',
+ 'shared', 'owner']
class ColumnAndWidth(CheckedPlusInput):
@@ -54,7 +54,7 @@ class TorrentViewColumns(InputPopup):
self.torrentlist = torrentlist
self.torrentview = torrentlist.torrentview
- title = "Visible columns (Esc to exit)"
+ 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,
@@ -62,20 +62,20 @@ class TorrentViewColumns(InputPopup):
border_off_west=1,
allow_rearrange=True)
- msg_fmt = "%-25s"
- self.add_header((msg_fmt % _("Columns")) + " " + _("Width"), space_below=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")
+ 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')
def on_width_func(name, width):
- self.torrentview.config["torrentview"]["columns"][name]["width"] = width
+ self.torrentview.config['torrentview']['columns'][name]['width'] = width
- self._add_input(ColumnAndWidth(self, colpref_name, torrent_data_fields[colpref_name]["name"], width_spin,
+ 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,
+ 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):
@@ -86,8 +86,8 @@ class TorrentViewColumns(InputPopup):
return
for key, value in data.items():
- self.torrentview.config["torrentview"]["columns"][key]["visible"] = value["value"]
- self.torrentview.config["torrentview"]["columns"][key]["order"] = value["order"]
+ self.torrentview.config['torrentview']['columns'][key]['visible'] = value['value']
+ self.torrentview.config['torrentview']['columns'][key]['order'] = value['order']
self.torrentview.config.save()
self.torrentview.on_config_changed()
@@ -96,7 +96,7 @@ class TorrentViewColumns(InputPopup):
@overrides(InputPopup)
def handle_read(self, c):
if c == ord('h'):
- popup = MessagePopup(self.torrentlist, "Help", COLUMN_VIEW_HELP_STR, width_req=70, border_off_west=1)
+ popup = MessagePopup(self.torrentlist, 'Help', COLUMN_VIEW_HELP_STR, width_req=70, border_off_west=1)
self.torrentlist.push_popup(popup)
return util.ReadState.READ
return InputPopup.handle_read(self, c)
diff --git a/deluge/ui/console/parser.py b/deluge/ui/console/parser.py
index 94f911c55..42138c14c 100644
--- a/deluge/ui/console/parser.py
+++ b/deluge/ui/console/parser.py
@@ -29,7 +29,7 @@ class ConsoleBaseParser(argparse.ArgumentParser):
"""
# Handle epilog manually to keep the text formatting
epilog = self.epilog
- self.epilog = ""
+ self.epilog = ''
help_str = super(ConsoleBaseParser, self).format_help()
if epilog is not None:
help_str += epilog
@@ -44,9 +44,9 @@ class ConsoleCommandParser(ConsoleBaseParser):
for a in args:
if not a:
continue
- if ";" in a:
- cmd_lines = [arg.strip() for arg in a.split(";")]
- elif " " in a:
+ if ';' in a:
+ cmd_lines = [arg.strip() for arg in a.split(';')]
+ elif ' ' in a:
cmd_lines = [a]
else:
continue
@@ -84,8 +84,8 @@ class ConsoleCommandParser(ConsoleBaseParser):
options.parsed_cmds = multi_command
else:
subcommand = False
- if hasattr(self.base_parser, "subcommand"):
- subcommand = getattr(self.base_parser, "subcommand")
+ if hasattr(self.base_parser, 'subcommand'):
+ subcommand = getattr(self.base_parser, 'subcommand')
if not subcommand:
# We must use parse_known_args to handle case when no subcommand
# is provided, because argparse does not support parsing without
@@ -100,7 +100,7 @@ class ConsoleCommandParser(ConsoleBaseParser):
options = super(ConsoleCommandParser, self).parse_args(args=args)
options.parsed_cmds = [options]
- if not hasattr(options, "remaining"):
+ if not hasattr(options, 'remaining'):
options.remaining = []
return options
@@ -127,13 +127,13 @@ class OptionParser(ConsoleBaseParser):
raise OptionParserError(msg)
def print_usage(self, _file=None):
- console = component.get("ConsoleUI")
+ console = component.get('ConsoleUI')
if self.usage:
for line in self.format_usage().splitlines():
console.write(line)
def print_help(self, _file=None):
- console = component.get("ConsoleUI")
+ console = component.get('ConsoleUI')
console.set_batch_write(True)
for line in self.format_help().splitlines():
console.write(line)
diff --git a/deluge/ui/console/utils/colors.py b/deluge/ui/console/utils/colors.py
index f63c91f11..37b15759a 100644
--- a/deluge/ui/console/utils/colors.py
+++ b/deluge/ui/console/utils/colors.py
@@ -20,55 +20,55 @@ except ImportError:
log = logging.getLogger(__name__)
colors = [
- "COLOR_BLACK",
- "COLOR_BLUE",
- "COLOR_CYAN",
- "COLOR_GREEN",
- "COLOR_MAGENTA",
- "COLOR_RED",
- "COLOR_WHITE",
- "COLOR_YELLOW"
+ 'COLOR_BLACK',
+ 'COLOR_BLUE',
+ 'COLOR_CYAN',
+ 'COLOR_GREEN',
+ 'COLOR_MAGENTA',
+ 'COLOR_RED',
+ 'COLOR_WHITE',
+ '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
schemes = {
- "input": ("white", "black"),
- "normal": ("white", "black"),
- "status": ("yellow", "blue", "bold"),
- "info": ("white", "black", "bold"),
- "error": ("red", "black", "bold"),
- "success": ("green", "black", "bold"),
- "event": ("magenta", "black", "bold"),
- "selected": ("black", "white", "bold"),
- "marked": ("white", "blue", "bold"),
- "selectedmarked": ("blue", "white", "bold"),
- "header": ("green", "black", "bold"),
- "filterstatus": ("green", "blue", "bold")
+ 'input': ('white', 'black'),
+ 'normal': ('white', 'black'),
+ 'status': ('yellow', 'blue', 'bold'),
+ 'info': ('white', 'black', 'bold'),
+ 'error': ('red', 'black', 'bold'),
+ 'success': ('green', 'black', 'bold'),
+ 'event': ('magenta', 'black', 'bold'),
+ 'selected': ('black', 'white', 'bold'),
+ 'marked': ('white', 'blue', 'bold'),
+ 'selectedmarked': ('blue', 'white', 'bold'),
+ 'header': ('green', 'black', 'bold'),
+ 'filterstatus': ('green', 'blue', 'bold')
}
# Colors for various torrent states
state_color = {
- "Seeding": "{!blue,black,bold!}",
- "Downloading": "{!green,black,bold!}",
- "Paused": "{!white,black!}",
- "Checking": "{!green,black!}",
- "Queued": "{!yellow,black!}",
- "Error": "{!red,black,bold!}",
- "Moving": "{!green,black,bold!}"
+ 'Seeding': '{!blue,black,bold!}',
+ 'Downloading': '{!green,black,bold!}',
+ 'Paused': '{!white,black!}',
+ 'Checking': '{!green,black!}',
+ 'Queued': '{!yellow,black!}',
+ 'Error': '{!red,black,bold!}',
+ 'Moving': '{!green,black,bold!}'
}
type_color = {
- bool: "{!yellow,black,bold!}",
- int: "{!green,black,bold!}",
- float: "{!green,black,bold!}",
- str: "{!cyan,black,bold!}",
- list: "{!magenta,black,bold!}",
- dict: "{!white,black,bold!}"
+ bool: '{!yellow,black,bold!}',
+ int: '{!green,black,bold!}',
+ float: '{!green,black,bold!}',
+ str: '{!cyan,black,bold!}',
+ list: '{!magenta,black,bold!}',
+ dict: '{!white,black,bold!}'
}
@@ -88,7 +88,7 @@ def init_colors():
color_pairs[(fg_name, bg_name)] = counter
counter += 1
except curses.error as ex:
- log.warn("Error: %s", ex)
+ log.warn('Error: %s', ex)
return counter
# Create the color_pairs dict
@@ -97,9 +97,9 @@ def init_colors():
for bg in colors:
counter = define_pair(counter, fg[6:].lower(), bg[6:].lower(), getattr(curses, fg), getattr(curses, bg))
- counter = define_pair(counter, "white", "grey", curses.COLOR_WHITE, 241)
- counter = define_pair(counter, "black", "whitegrey", curses.COLOR_BLACK, 249)
- counter = define_pair(counter, "magentadark", "white", 99, curses.COLOR_WHITE)
+ counter = define_pair(counter, 'white', 'grey', curses.COLOR_WHITE, 241)
+ counter = define_pair(counter, 'black', 'whitegrey', curses.COLOR_BLACK, 249)
+ counter = define_pair(counter, 'magentadark', 'white', 99, curses.COLOR_WHITE)
class BadColorString(Exception):
@@ -111,9 +111,9 @@ def replace_tabs(line):
Returns a string with tabs replaced with spaces.
"""
- for i in range(line.count("\t")):
- tab_length = 8 - (len(line[:line.find("\t")]) % 8)
- line = line.replace("\t", " " * tab_length, 1)
+ for i in range(line.count('\t')):
+ tab_length = 8 - (len(line[:line.find('\t')]) % 8)
+ line = line.replace('\t', ' ' * tab_length, 1)
return line
@@ -123,22 +123,22 @@ def strip_colors(line):
"""
# Remove all the color tags
- while line.find("{!") != -1:
- line = line[:line.find("{!")] + line[line.find("!}") + 2:]
+ while line.find('{!') != -1:
+ line = line[:line.find('{!')] + line[line.find('!}') + 2:]
return line
-def get_line_length(line, encoding="UTF-8"):
+def get_line_length(line, encoding='UTF-8'):
"""
Returns the string length without the color formatting.
"""
- if line.count("{!") != line.count("!}"):
- raise BadColorString("Number of {! is not equal to number of !}")
+ if line.count('{!') != line.count('!}'):
+ raise BadColorString('Number of {! is not equal to number of !}')
if isinstance(line, unicode):
- line = line.encode(encoding, "replace")
+ line = line.encode(encoding, 'replace')
# Remove all the color tags
line = strip_colors(line)
@@ -148,16 +148,16 @@ def get_line_length(line, encoding="UTF-8"):
return len(line)
-def get_line_width(line, encoding="UTF-8"):
+def get_line_width(line, encoding='UTF-8'):
"""
Get width of string considering double width characters
"""
- if line.count("{!") != line.count("!}"):
- raise BadColorString("Number of {! is not equal to number of !}")
+ if line.count('{!') != line.count('!}'):
+ raise BadColorString('Number of {! is not equal to number of !}')
if isinstance(line, unicode):
- line = line.encode(encoding, "replace")
+ line = line.encode(encoding, 'replace')
# Remove all the color tags
line = strip_colors(line)
@@ -167,7 +167,7 @@ def get_line_width(line, encoding="UTF-8"):
return format_utils.strwidth(line)
-def parse_color_string(s, encoding="UTF-8"):
+def parse_color_string(s, encoding='UTF-8'):
"""
Parses a string and returns a list of 2-tuples (color, string).
@@ -175,43 +175,43 @@ def parse_color_string(s, encoding="UTF-8"):
:param encoding: the encoding to use on output
"""
- if s.count("{!") != s.count("!}"):
- raise BadColorString("Number of {! is not equal to number of !}")
+ if s.count('{!') != s.count('!}'):
+ raise BadColorString('Number of {! is not equal to number of !}')
if isinstance(s, unicode):
- s = s.encode(encoding, "replace")
+ s = s.encode(encoding, 'replace')
ret = []
last_color_attr = None
# Keep track of where the strings
- while s.find("{!") != -1:
- begin = s.find("{!")
+ while s.find('{!') != -1:
+ begin = s.find('{!')
if begin > 0:
- ret.append((curses.color_pair(color_pairs[(schemes["input"][0], schemes["input"][1])]), s[:begin]))
+ ret.append((curses.color_pair(color_pairs[(schemes['input'][0], schemes['input'][1])]), s[:begin]))
- end = s.find("!}")
+ end = s.find('!}')
if end == -1:
raise BadColorString("Missing closing '!}'")
# Get a list of attributes in the bracketed section
- attrs = s[begin + 2:end].split(",")
+ attrs = s[begin + 2:end].split(',')
- if len(attrs) == 1 and not attrs[0].strip(" "):
- raise BadColorString("No description in {! !}")
+ if len(attrs) == 1 and not attrs[0].strip(' '):
+ raise BadColorString('No description in {! !}')
def apply_attrs(cp, attrs):
# This function applies any additional attributes as necessary
for attr in attrs:
- if attr == "ignore":
+ if attr == 'ignore':
continue
mode = '+'
if attr[0] in ['+', '-']:
mode = attr[0]
attr = attr[1:]
if mode == '+':
- cp |= getattr(curses, "A_" + attr.upper())
+ cp |= getattr(curses, 'A_' + attr.upper())
else:
- cp ^= getattr(curses, "A_" + attr.upper())
+ cp ^= getattr(curses, 'A_' + attr.upper())
return cp
# Check for a builtin type first
@@ -219,26 +219,26 @@ def parse_color_string(s, encoding="UTF-8"):
pair = (schemes[attrs[0]][0], schemes[attrs[0]][1])
if pair not in color_pairs:
log.debug("Color pair doesn't exist: %s, attrs: %s", pair, attrs)
- pair = ("white", "black")
+ pair = ('white', 'black')
# Get the color pair number
color_pair = curses.color_pair(color_pairs[pair])
color_pair = apply_attrs(color_pair, schemes[attrs[0]][2:])
last_color_attr = color_pair
else:
- attrlist = ["blink", "bold", "dim", "reverse", "standout", "underline"]
+ attrlist = ['blink', 'bold', 'dim', 'reverse', 'standout', 'underline']
if attrs[0][0] in ['+', '-']:
# Color is not given, so use last color
if last_color_attr is None:
- raise BadColorString("No color value given when no previous color was used!: %s" % (attrs[0]))
+ raise BadColorString('No color value given when no previous color was used!: %s' % (attrs[0]))
color_pair = last_color_attr
for i, attr in enumerate(attrs):
if attr[1:] not in attrlist:
- raise BadColorString("Bad attribute value!: %s" % (attr))
+ raise BadColorString('Bad attribute value!: %s' % (attr))
else:
# This is a custom color scheme
fg = attrs[0]
- bg = "black" # Default to 'black' if no bg is chosen
+ bg = 'black' # Default to 'black' if no bg is chosen
if len(attrs) > 1:
bg = attrs[1]
try:
@@ -249,23 +249,23 @@ def parse_color_string(s, encoding="UTF-8"):
# assume this means selection, and use "white", "black" + reverse
# To have white background and black foreground
log.debug("Color pair doesn't exist: %s", pair)
- if pair[1] == "white":
- if attrs[2] == "ignore":
- attrs[2] = "reverse"
+ if pair[1] == 'white':
+ if attrs[2] == 'ignore':
+ attrs[2] = 'reverse'
else:
- attrs.append("reverse")
- pair = ("white", "black")
+ attrs.append('reverse')
+ pair = ('white', 'black')
color_pair = curses.color_pair(color_pairs[pair])
last_color_attr = color_pair
attrs = attrs[2:] # Remove colors
except KeyError:
- raise BadColorString("Bad color value in tag: %s,%s" % (fg, bg))
+ raise BadColorString('Bad color value in tag: %s,%s' % (fg, bg))
# Check for additional attributes and OR them to the color_pair
color_pair = apply_attrs(color_pair, attrs)
last_color_attr = color_pair
# We need to find the text now, so lets try to find another {! and if
# there isn't one, then it's the rest of the string
- next_begin = s.find("{!", end)
+ next_begin = s.find('{!', end)
if next_begin == -1:
ret.append((color_pair, replace_tabs(s[end + 2:])))
@@ -286,25 +286,25 @@ class ConsoleColorFormatter(object):
"""
replace_dict = {
- "<torrent-id>": "{!green!}%s{!input!}",
- "<torrent>": "{!green!}%s{!input!}",
- "<command>": "{!green!}%s{!input!}",
-
- "<state>": "{!yellow!}%s{!input!}",
- "\\.\\.\\.": "{!yellow!}%s{!input!}",
- "\\s\\*\\s": "{!blue!}%s{!input!}",
- "(?<![\\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}",
+ '<torrent-id>': '{!green!}%s{!input!}',
+ '<torrent>': '{!green!}%s{!input!}',
+ '<command>': '{!green!}%s{!input!}',
+
+ '<state>': '{!yellow!}%s{!input!}',
+ '\\.\\.\\.': '{!yellow!}%s{!input!}',
+ '\\s\\*\\s': '{!blue!}%s{!input!}',
+ '(?<![\\-a-z])(-[a-zA-Z0-9])': '{!red!}%s{!input!}',
# "(\-[a-zA-Z0-9])": "{!red!}%s{!input!}",
- "--[_\\-a-zA-Z0-9]+": "{!green!}%s{!input!}",
- "(\\[|\\])": "{!info!}%s{!input!}",
-
- "<tab>": "{!white!}%s{!input!}",
- "[_A-Z]{3,}": "{!cyan!}%s{!input!}",
- "<key>": "{!cyan!}%s{!input!}",
- "<value>": "{!cyan!}%s{!input!}",
- "usage:": "{!info!}%s{!input!}",
- "<download-folder>": "{!yellow!}%s{!input!}",
- "<torrent-file>": "{!green!}%s{!input!}"
+ '--[_\\-a-zA-Z0-9]+': '{!green!}%s{!input!}',
+ '(\\[|\\])': '{!info!}%s{!input!}',
+
+ '<tab>': '{!white!}%s{!input!}',
+ '[_A-Z]{3,}': '{!cyan!}%s{!input!}',
+ '<key>': '{!cyan!}%s{!input!}',
+ '<value>': '{!cyan!}%s{!input!}',
+ 'usage:': '{!info!}%s{!input!}',
+ '<download-folder>': '{!yellow!}%s{!input!}',
+ '<torrent-file>': '{!green!}%s{!input!}'
}
diff --git a/deluge/ui/console/utils/column.py b/deluge/ui/console/utils/column.py
index 016d52a69..ab63875bc 100644
--- a/deluge/ui/console/utils/column.py
+++ b/deluge/ui/console/utils/column.py
@@ -25,68 +25,68 @@ torrent_data_fields = copy.deepcopy(TORRENT_DATA_FIELD)
def format_queue(qnum):
if qnum < 0:
- return ""
- return "%d" % (qnum + 1)
+ return ''
+ return '%d' % (qnum + 1)
formatters = {
- "queue": format_queue,
- "name": lambda a, b: b,
- "state": None,
- "tracker": None,
- "download_location": None,
- "owner": None,
-
- "progress_state": format_utils.format_progress,
- "progress": format_utils.format_progress,
-
- "size": deluge.common.fsize,
- "downloaded": deluge.common.fsize,
- "uploaded": deluge.common.fsize,
- "remaining": deluge.common.fsize,
-
- "ratio": format_utils.format_float,
- "avail": format_utils.format_float,
- "seeds_peers_ratio": format_utils.format_float,
-
- "download_speed": format_utils.format_speed,
- "upload_speed": format_utils.format_speed,
- "max_download_speed": format_utils.format_speed,
- "max_upload_speed": format_utils.format_speed,
-
- "peers": format_utils.format_seeds_peers,
- "seeds": format_utils.format_seeds_peers,
-
- "time_added": deluge.common.fdate,
- "seeding_time": deluge.common.ftime,
- "active_time": deluge.common.ftime,
- "finished_time": deluge.common.ftime,
-
- "last_seen_complete": format_utils.format_date_never,
- "completed_time": format_utils.format_date,
- "eta": format_utils.format_time,
- "pieces": format_utils.format_pieces,
+ 'queue': format_queue,
+ 'name': lambda a, b: b,
+ 'state': None,
+ 'tracker': None,
+ 'download_location': None,
+ 'owner': None,
+
+ 'progress_state': format_utils.format_progress,
+ 'progress': format_utils.format_progress,
+
+ 'size': deluge.common.fsize,
+ 'downloaded': deluge.common.fsize,
+ 'uploaded': deluge.common.fsize,
+ 'remaining': deluge.common.fsize,
+
+ 'ratio': format_utils.format_float,
+ 'avail': format_utils.format_float,
+ 'seeds_peers_ratio': format_utils.format_float,
+
+ 'download_speed': format_utils.format_speed,
+ 'upload_speed': format_utils.format_speed,
+ 'max_download_speed': format_utils.format_speed,
+ 'max_upload_speed': format_utils.format_speed,
+
+ 'peers': format_utils.format_seeds_peers,
+ 'seeds': format_utils.format_seeds_peers,
+
+ 'time_added': deluge.common.fdate,
+ 'seeding_time': deluge.common.ftime,
+ 'active_time': deluge.common.ftime,
+ 'finished_time': deluge.common.ftime,
+
+ 'last_seen_complete': format_utils.format_date_never,
+ 'completed_time': format_utils.format_date,
+ 'eta': format_utils.format_time,
+ 'pieces': format_utils.format_pieces,
}
-torrent_data_fields["pieces"] = {"name": _("Pieces"), "status": ["num_pieces", "piece_length"]}
-torrent_data_fields["seed_rank"] = {"name": _("Seed Rank"), "status": ["seed_rank"]}
+torrent_data_fields['pieces'] = {'name': _('Pieces'), 'status': ['num_pieces', 'piece_length']}
+torrent_data_fields['seed_rank'] = {'name': _('Seed Rank'), 'status': ['seed_rank']}
for data_field in torrent_data_fields:
- torrent_data_fields[data_field]["formatter"] = formatters.get(data_field, str)
+ torrent_data_fields[data_field]['formatter'] = formatters.get(data_field, str)
def get_column_value(name, state):
col = torrent_data_fields[name]
- if col["formatter"]:
- args = [state[key] for key in col["status"]]
- return col["formatter"](*args)
+ if col['formatter']:
+ args = [state[key] for key in col['status']]
+ return col['formatter'](*args)
else:
- return state[col["status"][0]]
+ return state[col['status'][0]]
def get_required_fields(cols):
fields = []
for col in cols:
- fields.extend(torrent_data_fields[col]["status"])
+ fields.extend(torrent_data_fields[col]['status'])
return fields
diff --git a/deluge/ui/console/utils/format_utils.py b/deluge/ui/console/utils/format_utils.py
index 64cdd7abb..64f7d49b8 100644
--- a/deluge/ui/console/utils/format_utils.py
+++ b/deluge/ui/console/utils/format_utils.py
@@ -19,69 +19,69 @@ def format_speed(speed):
if speed > 0:
return deluge.common.fspeed(speed)
else:
- return "-"
+ return '-'
def format_time(time):
if time > 0:
return deluge.common.ftime(time)
else:
- return "-"
+ return '-'
def format_date(time):
if time > 0:
return deluge.common.fdate(time)
else:
- return ""
+ return ''
def format_date_never(time):
if time > 0:
return deluge.common.fdate(time)
else:
- return "Never"
+ return 'Never'
def format_float(x):
if x < 0:
- return "-"
+ return '-'
else:
- return "%.3f" % x
+ return '%.3f' % x
def format_seeds_peers(num, total):
- return "%d (%d)" % (num, total)
+ return '%d (%d)' % (num, total)
def format_progress(perc):
if perc < 100:
- return "%.2f%%" % perc
+ return '%.2f%%' % perc
else:
- return "100%"
+ return '100%'
def format_pieces(num, size):
- return "%d (%s)" % (num, deluge.common.fsize(size))
+ return '%d (%s)' % (num, deluge.common.fsize(size))
def format_priority(prio):
if prio == - 2:
- return "[Mixed]"
+ return '[Mixed]'
if prio < 0:
- return "-"
+ return '-'
pstring = deluge.common.FILE_PRIORITY[prio]
if prio > 0:
- return pstring[:pstring.index("Priority") - 1]
+ return pstring[:pstring.index('Priority') - 1]
else:
return pstring
def trim_string(string, w, have_dbls):
if w <= 0:
- return ""
+ return ''
elif w == 1:
- return u" "
+ return u' '
elif have_dbls:
# have to do this the slow way
chrs = []
@@ -89,17 +89,17 @@ def trim_string(string, w, have_dbls):
idx = 0
while width < w:
chrs.append(string[idx])
- if east_asian_width(string[idx]) in ["W", "F"]:
+ if east_asian_width(string[idx]) in ['W', 'F']:
width += 2
else:
width += 1
idx += 1
if width != w:
chrs.pop()
- chrs.append(".")
- return u"%s " % ("".join(chrs))
+ chrs.append('.')
+ return u'%s ' % (''.join(chrs))
else:
- return u"%s " % (string[0:w - 1])
+ return u'%s ' % (string[0:w - 1])
def format_column(col, lim):
@@ -109,25 +109,25 @@ def format_column(col, lim):
# for unicode strings.
if col.__class__ is unicode:
# might have some double width chars
- col = ud_normalize("NFC", col)
- dbls = sum(east_asian_width(c) in "WF" for c in col)
+ col = ud_normalize('NFC', col)
+ dbls = sum(east_asian_width(c) in 'WF' for c in col)
size = len(col) + dbls
if size >= lim - 1:
return trim_string(col, lim, dbls > 0)
else:
- return "%s%s" % (col, " " * (lim - size))
+ return '%s%s' % (col, ' ' * (lim - size))
def format_row(row, column_widths):
- return "".join([format_column(row[i], column_widths[i]) for i in range(0, len(row))])
+ return ''.join([format_column(row[i], column_widths[i]) for i in range(0, len(row))])
-_strip_re = re.compile("\\{!.*?!\\}")
+_strip_re = re.compile('\\{!.*?!\\}')
-_format_code = re.compile(r"\{\|(.*)\|\}")
+_format_code = re.compile(r'\{\|(.*)\|\}')
def remove_formatting(string):
- return re.sub(_strip_re, "", string)
+ return re.sub(_strip_re, '', string)
def wrap_string(string, width, min_lines=0, strip_colors=True):
@@ -141,8 +141,8 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
width of the line. They will still be present in the output.
"""
ret = []
- s1 = string.split("\n")
- indent = ""
+ s1 = string.split('\n')
+ indent = ''
def insert_clr(s, offset, mtchs, clrs):
end_pos = offset + len(s)
@@ -150,20 +150,20 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
mtc = mtchs.popleft() - offset
clr = clrs.popleft()
end_pos += len(clr)
- s = "%s%s%s" % (s[:mtc], clr, s[mtc:])
+ s = '%s%s%s' % (s[:mtc], clr, s[mtc:])
return s
for s in s1:
offset = 0
- indent = ""
+ indent = ''
m = _format_code.search(remove_formatting(s))
if m:
- if m.group(1).startswith("indent:"):
- indent = m.group(1)[len("indent:"):]
- elif m.group(1).startswith("indent_pos:"):
+ if m.group(1).startswith('indent:'):
+ indent = m.group(1)[len('indent:'):]
+ elif m.group(1).startswith('indent_pos:'):
begin = m.start(0)
- indent = " " * begin
- s = _format_code.sub("", s)
+ indent = ' ' * begin
+ s = _format_code.sub('', s)
if strip_colors:
mtchs = deque()
@@ -171,7 +171,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
for m in _strip_re.finditer(s):
mtchs.append(m.start())
clrs.append(m.group())
- cstr = _strip_re.sub("", s)
+ cstr = _strip_re.sub('', s)
else:
cstr = s
@@ -186,7 +186,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
max_width = width - (len(indent) if offset != 0 else 0)
if len(cstr) < max_width:
break
- sidx = cstr.rfind(" ", 0, max_width - 1)
+ sidx = cstr.rfind(' ', 0, max_width - 1)
sidx += 1
if sidx > 0:
if strip_colors:
@@ -221,15 +221,15 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
if min_lines > 0:
for i in range(len(ret), min_lines):
- ret.append(" ")
+ ret.append(' ')
# Carry colors over to the next line
- last_color_string = ""
+ last_color_string = ''
for i, line in enumerate(ret):
if i != 0:
- ret[i] = "%s%s" % (last_color_string, ret[i])
+ ret[i] = '%s%s' % (last_color_string, ret[i])
- colors = re.findall("\\{![^!]+!\\}", line)
+ colors = re.findall('\\{![^!]+!\\}', line)
if colors:
last_color_string = colors[-1]
@@ -241,20 +241,20 @@ def strwidth(string):
Measure width of a string considering asian double width characters
"""
if not isinstance(string, unicode):
- string = unicode(string, "utf-8")
- return sum([1 + (east_asian_width(char) in ["W", "F"]) for char in string])
+ string = unicode(string, 'utf-8')
+ return sum([1 + (east_asian_width(char) in ['W', 'F']) for char in string])
-def pad_string(string, length, character=" ", side="right"):
+def pad_string(string, length, character=' ', side='right'):
"""
Pad string with specified character to desired length, considering double width characters.
"""
w = strwidth(string)
diff = length - w
- if side == "left":
- return "%s%s" % (character * diff, string)
- elif side == "right":
- return "%s%s" % (string, character * diff)
+ if side == 'left':
+ return '%s%s' % (character * diff, string)
+ elif side == 'right':
+ return '%s%s' % (string, character * diff)
def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/"):
@@ -271,8 +271,8 @@ def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/")
if (not seg_start) or (input_cursor == 0):
break
if deleted and seg_start[-1] in sep_chars:
- if seg_start[-1] == " ":
- if seg_start[-2] == " " or none_space_deleted is False:
+ if seg_start[-1] == ' ':
+ if seg_start[-2] == ' ' or none_space_deleted is False:
# Continue as long as:
# * next char is also a space
# * no none-space characters have been deleted
@@ -283,7 +283,7 @@ def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/")
break
if not none_space_deleted:
- none_space_deleted = seg_start[-1] != " "
+ none_space_deleted = seg_start[-1] != ' '
seg_start = seg_start[:-1]
deleted += 1
input_cursor -= 1
diff --git a/deluge/ui/console/widgets/fields.py b/deluge/ui/console/widgets/fields.py
index acbf03d90..7e1ca57d9 100644
--- a/deluge/ui/console/widgets/fields.py
+++ b/deluge/ui/console/widgets/fields.py
@@ -33,16 +33,16 @@ class BaseField(InputKeyHandler):
self.name = name
self.parent = parent
self.fmt_keys = {}
- self.set_fmt_key("font", "ignore", kwargs)
- self.set_fmt_key("color", "white,black", kwargs)
- self.set_fmt_key("color_end", "white,black", kwargs)
- self.set_fmt_key("color_active", "black,white", kwargs)
- self.set_fmt_key("color_unfocused", "color", kwargs)
- self.set_fmt_key("color_unfocused_active", "black,whitegrey", kwargs)
- self.set_fmt_key("font_active", "font", kwargs)
- self.set_fmt_key("font_unfocused", "font", kwargs)
- self.set_fmt_key("font_unfocused_active", "font_active", kwargs)
- self.default_col = kwargs.get("col", -1)
+ self.set_fmt_key('font', 'ignore', kwargs)
+ self.set_fmt_key('color', 'white,black', kwargs)
+ self.set_fmt_key('color_end', 'white,black', kwargs)
+ self.set_fmt_key('color_active', 'black,white', kwargs)
+ self.set_fmt_key('color_unfocused', 'color', kwargs)
+ self.set_fmt_key('color_unfocused_active', 'black,whitegrey', kwargs)
+ self.set_fmt_key('font_active', 'font', kwargs)
+ self.set_fmt_key('font_unfocused', 'font', kwargs)
+ self.set_fmt_key('font_unfocused_active', 'font_active', kwargs)
+ self.default_col = kwargs.get('col', -1)
self._selectable = selectable
self.value = None
@@ -56,19 +56,19 @@ class BaseField(InputKeyHandler):
self.fmt_keys[key] = value
def get_fmt_keys(self, focused, active, **kwargs):
- color_key = kwargs.get("color_key", "color")
- font_key = "font"
+ color_key = kwargs.get('color_key', 'color')
+ font_key = 'font'
if not focused:
- color_key += "_unfocused"
- font_key += "_unfocused"
+ color_key += '_unfocused'
+ font_key += '_unfocused'
if active:
- color_key += "_active"
- font_key += "_active"
+ color_key += '_active'
+ font_key += '_active'
return color_key, font_key
- def build_fmt_string(self, focused, active, value_key="msg", **kwargs):
+ def build_fmt_string(self, focused, active, value_key='msg', **kwargs):
color_key, font_key = self.get_fmt_keys(focused, active, **kwargs)
- return "{!%%(%s)s,%%(%s)s!}%%(%s)s{!%%(%s)s!}" % (color_key, font_key, value_key, "color_end")
+ return '{!%%(%s)s,%%(%s)s!}%%(%s)s{!%%(%s)s!}' % (color_key, font_key, value_key, 'color_end')
def depend_skip(self):
return False
@@ -124,7 +124,7 @@ class InputField(BaseField):
def set_depend(self, i, inverse=False):
if not isinstance(i, CheckedInput):
- raise Exception("Can only depend on CheckedInputs")
+ raise Exception('Can only depend on CheckedInputs')
self.depend = i
self.inverse = inverse
@@ -140,10 +140,10 @@ class InputField(BaseField):
class Header(NoInputField):
def __init__(self, parent, header, space_above, space_below, **kwargs):
- if "name" not in kwargs:
- kwargs["name"] = header
+ if 'name' not in kwargs:
+ kwargs['name'] = header
NoInputField.__init__(self, parent=parent, **kwargs)
- self.header = "{!white,black,bold!}%s" % header
+ self.header = '{!white,black,bold!}%s' % header
self.space_above = space_above
self.space_below = space_below
@@ -169,7 +169,7 @@ class InfoField(NoInputField):
NoInputField.__init__(self, parent=parent, name=name, **kwargs)
self.label = label
self.value = value
- self.txt = "%s %s" % (label, value)
+ self.txt = '%s %s' % (label, value)
@overrides(BaseField)
def render(self, screen, row, col=0, **kwargs):
@@ -180,27 +180,27 @@ class InfoField(NoInputField):
def set_value(self, v):
self.value = v
if isinstance(v, float):
- self.txt = "%s %.2f" % (self.label, self.value)
+ self.txt = '%s %.2f' % (self.label, self.value)
else:
- self.txt = "%s %s" % (self.label, self.value)
+ self.txt = '%s %s' % (self.label, self.value)
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.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)
- self.set_fmt_key("font_unfocused_active_checked", "font_active_checked", kwargs)
- self.set_fmt_key("color_checked", "color", kwargs)
- self.set_fmt_key("color_active_checked", "color_active", kwargs)
- self.set_fmt_key("color_unfocused_checked", "color_checked", kwargs)
- self.set_fmt_key("color_unfocused_active_checked", "color_unfocused_active", kwargs)
+ 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)
+ self.set_fmt_key('font_unfocused_active_checked', 'font_active_checked', kwargs)
+ self.set_fmt_key('color_checked', 'color', kwargs)
+ self.set_fmt_key('color_active_checked', 'color_active', kwargs)
+ self.set_fmt_key('color_unfocused_checked', 'color_checked', kwargs)
+ self.set_fmt_key('color_unfocused_active_checked', 'color_unfocused_active', kwargs)
@property
def checked(self):
@@ -210,16 +210,16 @@ class CheckedInput(InputField):
def get_fmt_keys(self, focused, active, **kwargs):
color_key, font_key = super(CheckedInput, self).get_fmt_keys(focused, active, **kwargs)
if self.checked:
- color_key += "_checked"
- font_key += "_checked"
+ color_key += '_checked'
+ font_key += '_checked'
return color_key, font_key
def build_msg_string(self, focused, active):
fmt_str = self.build_fmt_string(focused, active)
- char = self.fmt_keys["checked_char" if self.checked else "unchecked_char"]
- chk_box = ""
+ char = self.fmt_keys['checked_char' if self.checked else 'unchecked_char']
+ chk_box = ''
try:
- chk_box = self.fmt_keys["checkbox_format"] % char
+ chk_box = self.fmt_keys['checkbox_format'] % char
except KeyError:
pass
msg = fmt_str % self.fmt_keys
@@ -227,7 +227,7 @@ class CheckedInput(InputField):
@overrides(InputField)
def render(self, screen, row, col=0, **kwargs):
- string = self.build_msg_string(kwargs.get("focused"), kwargs.get("active"))
+ string = self.build_msg_string(kwargs.get('focused'), kwargs.get('active'))
self.parent.add_string(row, string, scr=screen, col=col, pad=False)
return 1
@@ -242,9 +242,9 @@ class CheckedInput(InputField):
@overrides(InputField)
def set_message(self, msg):
changed = InputField.set_message(self, msg)
- if "msg" in self.fmt_keys and self.fmt_keys["msg"] != msg:
+ if 'msg' in self.fmt_keys and self.fmt_keys['msg'] != msg:
changed = True
- self.fmt_keys.update({"msg": msg})
+ self.fmt_keys.update({'msg': msg})
return changed
@@ -252,7 +252,7 @@ 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):
+ show_usage_hints=True, msg_fmt='%s ', **kwargs):
CheckedInput.__init__(self, parent, name, message, **kwargs)
self.child = child
self.child_active = False
@@ -270,7 +270,7 @@ class CheckedPlusInput(CheckedInput):
CheckedInput.render(self, screen, row, width=width, active=isact, focused=focused, col=col)
rows = 1
if self.show_usage_hints and (self.child_always_visible or (active and self.checked)):
- msg = "(esc to leave)" if self.child_active else "(right arrow to edit)"
+ msg = '(esc to leave)' if self.child_active else '(right arrow to edit)'
self.parent.add_string(row + 1, msg, scr=screen, col=col, pad=False)
rows += 1
@@ -282,7 +282,7 @@ class CheckedPlusInput(CheckedInput):
col=col + msglen, cursor_offset=msglen)
rows = max(rows, crows)
else:
- self.parent.add_string(row, "(enable to view/edit value)", scr=screen,
+ self.parent.add_string(row, '(enable to view/edit value)', scr=screen,
col=col + msglen, pad=False)
return rows
@@ -310,7 +310,7 @@ 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):
+ 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
@@ -344,16 +344,16 @@ class IntSpinInput(InputField):
self.set_value(self.valstr, validate=True, value_on_fail=self.last_valid_value)
self.last_active = False
- fmt_str = self.build_fmt_string(focused, active, value_key="value")
- value_format = "%(msg)s {!input!}"
+ fmt_str = self.build_fmt_string(focused, active, value_key='value')
+ value_format = '%(msg)s {!input!}'
if not self.valstr:
- value_format += "[ ]"
+ value_format += '[ ]'
elif self.format_default and self.valstr == self.default_str:
- value_format += "[ {!magenta,black!}%(value)s{!input!} ]"
+ value_format += '[ {!magenta,black!}%(value)s{!input!} ]'
else:
- value_format += "[ " + fmt_str + " ]"
+ value_format += '[ ' + fmt_str + ' ]'
- self.parent.add_string(row, value_format % dict({"msg": self.message, "value": "%s" % self.valstr},
+ 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:
@@ -409,7 +409,7 @@ class IntSpinInput(InputField):
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("-")
+ minus_place = self.valstr.find('-')
if self.cursor > minus_place:
new_val = self.valstr[:self.cursor] + chr(c) + self.valstr[self.cursor:]
self.set_value(new_val, validate=True, cursor=self.cursor + 1, on_invalid=self.value)
@@ -447,7 +447,7 @@ class IntSpinInput(InputField):
self.cursor = cursor
except TypeError:
import traceback
- log.warn("TypeError: %s", "".join(traceback.format_exc()))
+ log.warn('TypeError: %s', ''.join(traceback.format_exc()))
else:
if cursor is True:
self.cursor = len(self.valstr)
@@ -460,7 +460,7 @@ class FloatSpinInput(IntSpinInput):
def __init__(self, parent, message, name, move_func, value, precision=1, **kwargs):
self.precision = precision
IntSpinInput.__init__(self, parent, message, name, move_func, value, **kwargs)
- self.fmt = "%%.%df" % precision
+ self.fmt = '%%.%df' % precision
self.convert_func = lambda valstr: round(float(valstr), self.precision)
self.set_value(value)
self.cursor = len(self.valstr)
@@ -468,10 +468,10 @@ class FloatSpinInput(IntSpinInput):
@overrides(IntSpinInput)
def handle_read(self, c):
if c == ord('.'):
- minus_place = self.valstr.find("-")
+ minus_place = self.valstr.find('-')
if self.cursor <= minus_place:
return util.ReadState.READ
- point_place = self.valstr.find(".")
+ point_place = self.valstr.find('.')
if point_place >= 0:
return util.ReadState.READ
new_val = self.valstr[:self.cursor] + chr(c) + self.valstr[self.cursor:]
@@ -491,27 +491,27 @@ class SelectInput(InputField):
self.selected_index = active_index
self.default_option = active_index if active_default else None
self.require_select_action = require_select_action
- self.fmt_keys.update({"font_active": "bold"})
- font_selected = kwargs.get("font_selected", "bold,underline")
-
- self.set_fmt_key("font_selected", font_selected, kwargs)
- self.set_fmt_key("font_active_selected", "font_selected", kwargs)
- self.set_fmt_key("font_unfocused_selected", "font_selected", kwargs)
- self.set_fmt_key("font_unfocused_active_selected", "font_active_selected", kwargs)
-
- self.set_fmt_key("color_selected", "color", kwargs)
- self.set_fmt_key("color_active_selected", "color_active", kwargs)
- self.set_fmt_key("color_unfocused_selected", "color_selected", kwargs)
- self.set_fmt_key("color_unfocused_active_selected", "color_unfocused_active", kwargs)
- self.set_fmt_key("color_default_value", "magenta,black", kwargs)
-
- self.set_fmt_key("color_default_value", "magenta,black")
- self.set_fmt_key("color_default_value_active", "magentadark,white")
- self.set_fmt_key("color_default_value_selected", "color_default_value", kwargs)
- self.set_fmt_key("color_default_value_unfocused", "color_default_value", kwargs)
- self.set_fmt_key("color_default_value_unfocused_selected", "color_default_value_selected", kwargs)
- self.set_fmt_key("color_default_value_active_selected", "magentadark,white")
- self.set_fmt_key("color_default_value_unfocused_active_selected", "color_unfocused_active", kwargs)
+ self.fmt_keys.update({'font_active': 'bold'})
+ font_selected = kwargs.get('font_selected', 'bold,underline')
+
+ self.set_fmt_key('font_selected', font_selected, kwargs)
+ self.set_fmt_key('font_active_selected', 'font_selected', kwargs)
+ self.set_fmt_key('font_unfocused_selected', 'font_selected', kwargs)
+ self.set_fmt_key('font_unfocused_active_selected', 'font_active_selected', kwargs)
+
+ self.set_fmt_key('color_selected', 'color', kwargs)
+ self.set_fmt_key('color_active_selected', 'color_active', kwargs)
+ self.set_fmt_key('color_unfocused_selected', 'color_selected', kwargs)
+ self.set_fmt_key('color_unfocused_active_selected', 'color_unfocused_active', kwargs)
+ self.set_fmt_key('color_default_value', 'magenta,black', kwargs)
+
+ self.set_fmt_key('color_default_value', 'magenta,black')
+ self.set_fmt_key('color_default_value_active', 'magentadark,white')
+ self.set_fmt_key('color_default_value_selected', 'color_default_value', kwargs)
+ self.set_fmt_key('color_default_value_unfocused', 'color_default_value', kwargs)
+ self.set_fmt_key('color_default_value_unfocused_selected', 'color_default_value_selected', kwargs)
+ self.set_fmt_key('color_default_value_active_selected', 'magentadark,white')
+ self.set_fmt_key('color_default_value_unfocused_active_selected', 'color_unfocused_active', kwargs)
@property
def height(self):
@@ -521,8 +521,8 @@ class SelectInput(InputField):
def get_fmt_keys(self, focused, active, selected=False, **kwargs):
color_key, font_key = super(SelectInput, self).get_fmt_keys(focused, active, **kwargs)
if selected:
- color_key += "_selected"
- font_key += "_selected"
+ color_key += '_selected'
+ font_key += '_selected'
return color_key, font_key
@overrides(InputField)
@@ -533,12 +533,12 @@ class SelectInput(InputField):
off = col + 1
for i, opt in enumerate(self.opts):
- self.fmt_keys["msg"] = opt
- fmt_args = {"selected": i == self.selected_index}
+ self.fmt_keys['msg'] = opt
+ fmt_args = {'selected': i == self.selected_index}
if i == self.default_option:
- fmt_args["color_key"] = "color_default_value"
+ fmt_args['color_key'] = 'color_default_value'
fmt = self.build_fmt_string(focused, (i == self.active_index) and active, **fmt_args)
- string = "[%s]" % (fmt % self.fmt_keys)
+ string = '[%s]' % (fmt % self.fmt_keys)
self.parent.add_string(row, string, scr=screen, col=off, pad=False)
off += len(opt) + 3
if self.message:
@@ -573,7 +573,7 @@ class SelectInput(InputField):
if value == val:
self.selected_index = i
return
- raise Exception("Invalid value for SelectInput")
+ raise Exception('Invalid value for SelectInput')
class TextInput(InputField):
@@ -665,11 +665,11 @@ class TextInput(InputField):
x_pos = self.calculate_cursor_pos(width, col)
self.move_func(row, x_pos)
- fmt = "{!black,white,bold!}%s"
+ fmt = '{!black,white,bold!}%s'
if self.format_default and len(self.value) != 0 and self.value == self.default_value:
- fmt = "{!magenta,white!}%s"
+ fmt = '{!magenta,white!}%s'
if not active or not focused or self.input_active:
- fmt = "{!white,grey,bold!}%s"
+ fmt = '{!white,grey,bold!}%s'
self.parent.add_string(row, fmt % vstr, scr=screen, col=col, pad=False, trim=False)
return self.height
@@ -709,13 +709,13 @@ class TextInput(InputField):
# We only call the tab completer function if we're at the end of
# the input string on the cursor is on a space
- if self.cursor == len(self.value) or self.value[self.cursor] == " ":
+ if self.cursor == len(self.value) or self.value[self.cursor] == ' ':
if self.opts:
prev = self.opt_off
self.opt_off += self.width - 3
# now find previous double space, best guess at a split point
# in future could keep opts unjoined to get this really right
- self.opt_off = self.opts.rfind(" ", 0, self.opt_off) + 2
+ self.opt_off = self.opts.rfind(' ', 0, self.opt_off) + 2
if second_hit and self.opt_off == prev: # double tap and we're at the end
self.opt_off = 0
else:
@@ -732,7 +732,7 @@ class TextInput(InputField):
if len(opts) > 1 and second_hit: # display multiple options on second tab hit
sp = self.value.rfind(os.sep) + 1
- self.opts = " ".join([o[sp:] for o in opts])
+ self.opts = ' '.join([o[sp:] for o in opts])
# Cursor movement
elif c == curses.KEY_LEFT:
@@ -757,7 +757,7 @@ class TextInput(InputField):
elif c > 31 and c < 256:
# Emulate getwch
stroke = chr(c)
- uchar = ""
+ uchar = ''
while not uchar:
try:
uchar = stroke.decode(self.parent.encoding)
@@ -789,7 +789,7 @@ class TextInput(InputField):
# Directory, so we need to show contents of directory
for f in os.listdir(line):
# Skip hidden
- if f.startswith("."):
+ if f.startswith('.'):
continue
f = os.path.join(line, f)
if os.path.isdir(f):
@@ -831,8 +831,8 @@ class ComboInput(InputField):
@overrides(BaseField)
def render(self, screen, row, col=0, **kwargs):
- fmt_str = self.build_fmt_string(kwargs.get("focused"), kwargs.get("active"))
- string = "%s: [%10s]" % (self.message, fmt_str % self.fmt_keys)
+ fmt_str = self.build_fmt_string(kwargs.get('focused'), kwargs.get('active'))
+ string = '%s: [%10s]' % (self.message, fmt_str % self.fmt_keys)
self.parent.add_string(row, string, scr=screen, col=col, pad=False)
return 1
@@ -865,11 +865,11 @@ 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,
+ 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]}
+ args = {'data': choice[0]}
select_popup.add_line(choice[0], choice[1], selectable=True,
selected=choice[0] == self.get_value(), **args)
self.parent.push_popup(select_popup)
@@ -886,12 +886,12 @@ class ComboInput(InputField):
break
if msg is None:
log.warn("Setting a value '%s' found found in choices: %s", val, self.choices)
- self.fmt_keys.update({"msg": msg})
+ self.fmt_keys.update({'msg': msg})
class TextField(BaseField):
- def __init__(self, parent, name, value, selectable=True, value_fmt="%s", **kwargs):
+ def __init__(self, parent, name, value, selectable=True, value_fmt='%s', **kwargs):
BaseField.__init__(self, parent=parent, name=name, selectable=selectable, **kwargs)
self.value = value
self.value_fmt = value_fmt
@@ -910,7 +910,7 @@ class TextField(BaseField):
def render(self, screen, row, active=False, focused=False, col=0, **kwargs):
util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active
fmt = self.build_fmt_string(focused, active)
- self.fmt_keys["msg"] = self.txt
+ self.fmt_keys['msg'] = self.txt
string = fmt % self.fmt_keys
self.parent.add_string(row, string, scr=screen, col=col, pad=False, trim=False)
return 1
@@ -918,17 +918,17 @@ class TextField(BaseField):
class TextArea(TextField):
- def __init__(self, parent, name, value, value_fmt="%s", **kwargs):
+ def __init__(self, parent, name, value, value_fmt='%s', **kwargs):
TextField.__init__(self, parent, name, value, selectable=False, value_fmt=value_fmt, **kwargs)
@overrides(TextField)
def render(self, screen, row, col=0, **kwargs):
util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active
- color = "{!white,black!}"
+ color = '{!white,black!}'
lines = wrap_string(self.txt, self.parent.width - 3, 3, True)
for i, line in enumerate(lines):
- self.parent.add_string(row + i, "%s%s" % (color, line), scr=screen, col=col, pad=False, trim=False)
+ self.parent.add_string(row + i, '%s%s' % (color, line), scr=screen, col=col, pad=False, trim=False)
return len(lines)
@property
@@ -943,7 +943,7 @@ class TextArea(TextField):
class DividerField(NoInputField):
- def __init__(self, parent, name, value, selectable=False, fill_width=True, value_fmt="%s", **kwargs):
+ def __init__(self, parent, name, value, selectable=False, fill_width=True, value_fmt='%s', **kwargs):
NoInputField.__init__(self, parent=parent, name=name, selectable=selectable, **kwargs)
self.value = value
self.value_fmt = value_fmt
@@ -959,12 +959,12 @@ class DividerField(NoInputField):
def render(self, screen, row, active=False, focused=False, col=0, width=None, **kwargs):
util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active
fmt = self.build_fmt_string(focused, active)
- self.fmt_keys["msg"] = self.txt
+ self.fmt_keys['msg'] = self.txt
if self.fill_width:
- self.fmt_keys["msg"] = ""
+ self.fmt_keys['msg'] = ''
string_len = len(remove_formatting(fmt % self.fmt_keys))
fill_len = width - string_len - (len(self.txt) - 1)
- self.fmt_keys["msg"] = self.txt * fill_len
+ self.fmt_keys['msg'] = self.txt * fill_len
string = fmt % self.fmt_keys
self.parent.add_string(row, string, scr=screen, col=col, pad=False, trim=False)
return 1
diff --git a/deluge/ui/console/widgets/inputpane.py b/deluge/ui/console/widgets/inputpane.py
index ce1b92383..c8eab01a9 100644
--- a/deluge/ui/console/widgets/inputpane.py
+++ b/deluge/ui/console/widgets/inputpane.py
@@ -47,24 +47,24 @@ class BaseInputPane(InputKeyHandler):
self.border_off_south = border_off_south
self.last_lineoff_move = 0
- if not hasattr(self, "visible_content_pane_height"):
+ 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__)
- raise AttributeError("visible_content_pane_height")
+ self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__)
+ raise AttributeError('visible_content_pane_height')
@property
def visible_content_pane_width(self):
return self.mode.width
def add_spaces(self, num):
- string = ""
+ string = ''
for i in range(num):
- string += "\n"
+ string += '\n'
- self.add_text_area("space %d" % len(self.inputs), string)
+ self.add_text_area('space %d' % len(self.inputs), string)
def add_text(self, string):
- self.add_text_area("", string)
+ self.add_text_area('', string)
def move(self, r, c):
self._cursor_row = r
@@ -82,7 +82,7 @@ class BaseInputPane(InputKeyHandler):
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)))
+ input_element.name, e, ''.join(traceback.format_stack(limit=5)))
return
self.inputs.append(input_element)
@@ -97,7 +97,7 @@ class BaseInputPane(InputKeyHandler):
def add_info_field(self, name, label, value):
return self._add_input(InfoField(self, name, label, value))
- def add_text_field(self, name, message, selectable=True, col="+1", **kwargs):
+ def add_text_field(self, name, message, selectable=True, col='+1', **kwargs):
return self._add_input(TextField(self, name, message, selectable=selectable, col=col, **kwargs))
def add_text_area(self, name, message, **kwargs):
@@ -106,7 +106,7 @@ class BaseInputPane(InputKeyHandler):
def add_divider_field(self, name, message, **kwargs):
return self._add_input(DividerField(self, name, message, **kwargs))
- def add_text_input(self, name, message, value="", col="+1", **kwargs):
+ def add_text_input(self, name, message, value='', col='+1', **kwargs):
"""
Add a text input field
@@ -121,19 +121,19 @@ class BaseInputPane(InputKeyHandler):
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))
- def add_checked_input(self, name, message, checked=False, col="+1", **kwargs):
+ def add_checked_input(self, name, message, checked=False, col='+1', **kwargs):
return self._add_input(CheckedInput(self, name, message, checked=checked, col=col, **kwargs))
- def add_checkedplus_input(self, name, message, child, checked=False, col="+1", **kwargs):
+ def add_checkedplus_input(self, name, message, child, checked=False, col='+1', **kwargs):
return self._add_input(CheckedPlusInput(self, name, message, child, checked=checked, col=col, **kwargs))
- def add_float_spin_input(self, name, message, value=0.0, col="+1", **kwargs):
+ def add_float_spin_input(self, name, message, value=0.0, col='+1', **kwargs):
return self._add_input(FloatSpinInput(self, name, message, self.move, value, col=col, **kwargs))
- def add_int_spin_input(self, name, message, value=0, col="+1", **kwargs):
+ def add_int_spin_input(self, name, message, value=0, col='+1', **kwargs):
return self._add_input(IntSpinInput(self, name, message, self.move, value, col=col, **kwargs))
- def add_combo_input(self, name, message, choices, col="+1", **kwargs):
+ def add_combo_input(self, name, message, choices, col='+1', **kwargs):
return self._add_input(ComboInput(self, name, message, choices, col=col, **kwargs))
@overrides(InputKeyHandler)
@@ -190,7 +190,7 @@ class BaseInputPane(InputKeyHandler):
for i, ipt in enumerate(self.inputs):
if not ipt.has_input():
continue
- vals[ipt.name] = {"value": ipt.get_value(), "order": i, "active": self.active_input == i}
+ vals[ipt.name] = {'value': ipt.get_value(), 'order': i, 'active': self.active_input == i}
return vals
def immediate_action_cb(self, state_changed=True):
diff --git a/deluge/ui/console/widgets/popup.py b/deluge/ui/console/widgets/popup.py
index e5df2a878..4f3a12f63 100644
--- a/deluge/ui/console/widgets/popup.py
+++ b/deluge/ui/console/widgets/popup.py
@@ -174,7 +174,7 @@ class Popup(BaseWindow, InputKeyHandler):
def close(self, *args, **kwargs):
self._closed = True
- if kwargs.get("call_cb", True):
+ if kwargs.get('call_cb', True):
self._call_close_cb(*args)
self.panel.hide()
@@ -209,15 +209,15 @@ class SelectablePopup(BaseInputPane, Popup):
"""
Popup.__init__(self, parent_mode, title, close_cb=close_cb, **kwargs)
- kwargs.update({"allow_rearrange": allow_rearrange, "immediate_action": immediate_action})
+ kwargs.update({'allow_rearrange': allow_rearrange, 'immediate_action': immediate_action})
BaseInputPane.__init__(self, self, **kwargs)
self.selection_cb = selection_cb
self.input_cb = input_cb
self.hotkeys = {}
self.cb_arg = {}
- self.cb_args = kwargs.get("cb_args", {})
- if "base_popup" not in self.cb_args:
- self.cb_args["base_popup"] = self
+ self.cb_args = kwargs.get('cb_args', {})
+ if 'base_popup' not in self.cb_args:
+ self.cb_args['base_popup'] = self
@property
@overrides(BaseWindow)
@@ -226,7 +226,7 @@ class SelectablePopup(BaseInputPane, Popup):
return Popup.visible_content_pane_height.fget(self)
def current_selection(self):
- "Returns a tuple of (selected index, selected data)"
+ 'Returns a tuple of (selected index, selected data)'
return self.active_input
def set_selection(self, index):
@@ -238,15 +238,15 @@ class SelectablePopup(BaseInputPane, Popup):
hotkey = None
self.cb_arg[name] = cb_arg
if use_underline:
- udx = string.find("_")
+ udx = string.find('_')
if udx >= 0:
hotkey = string[udx].lower()
- string = string[:udx] + "{!+underline!}" + string[udx + 1] + "{!-underline!}" + string[udx + 2:]
+ string = string[:udx] + '{!+underline!}' + string[udx + 1] + '{!-underline!}' + string[udx + 2:]
- kwargs["selectable"] = selectable
+ kwargs['selectable'] = selectable
if foreground:
- kwargs["color_active"] = "%s,white" % foreground
- kwargs["color"] = "%s,black" % foreground
+ kwargs['color_active'] = '%s,white' % foreground
+ kwargs['color'] = '%s,black' % foreground
field = self.add_text_field(name, string, **kwargs)
if hotkey:
@@ -259,7 +259,7 @@ class SelectablePopup(BaseInputPane, Popup):
def handle_read(self, c):
if c in [curses.KEY_ENTER, util.KEY_ENTER2]:
for k, v in self.get_values().iteritems():
- if v["active"]:
+ if v['active']:
if self.selection_cb(k, **dict(self.cb_args, data=self.cb_arg)):
self.close(None)
return util.ReadState.READ
@@ -279,12 +279,12 @@ class SelectablePopup(BaseInputPane, Popup):
self.refresh()
return util.ReadState.IGNORED
- def add_divider(self, message=None, char="-", fill_width=True, color="white"):
+ def add_divider(self, message=None, char='-', fill_width=True, color='white'):
if message is not None:
fill_width = False
else:
message = char
- self.add_divider_field("", message, selectable=False, fill_width=fill_width)
+ self.add_divider_field('', message, selectable=False, fill_width=fill_width)
class MessagePopup(Popup, BaseInputPane):
@@ -304,7 +304,7 @@ class MessagePopup(Popup, BaseInputPane):
self.handle_resize()
self.no_refresh = False
- self.add_text_area("TextMessage", message)
+ self.add_text_area('TextMessage', message)
@overrides(Popup, BaseInputPane)
def handle_read(self, c):
diff --git a/deluge/ui/console/widgets/statusbars.py b/deluge/ui/console/widgets/statusbars.py
index 5a002823d..5c43fb1d6 100644
--- a/deluge/ui/console/widgets/statusbars.py
+++ b/deluge/ui/console/widgets/statusbars.py
@@ -15,101 +15,101 @@ from deluge.ui.client import client
class StatusBars(component.Component):
def __init__(self):
- component.Component.__init__(self, "StatusBars", 2, depend=["CoreConfig"])
- self.config = component.get("CoreConfig")
+ component.Component.__init__(self, 'StatusBars', 2, depend=['CoreConfig'])
+ self.config = component.get('CoreConfig')
# Hold some values we get from the core
self.connections = 0
- self.download = ""
- self.upload = ""
+ self.download = ''
+ self.upload = ''
self.dht = 0
- self.external_ip = ""
+ self.external_ip = ''
# Default values
- self.topbar = "{!status!}Deluge %s Console - " % deluge.common.get_version()
- self.bottombar = "{!status!}C: %s" % self.connections
+ self.topbar = '{!status!}Deluge %s Console - ' % deluge.common.get_version()
+ self.bottombar = '{!status!}C: %s' % self.connections
def start(self):
self.update()
def update(self):
def on_get_session_status(status):
- self.upload = deluge.common.fsize(status["payload_upload_rate"])
- self.download = deluge.common.fsize(status["payload_download_rate"])
- self.connections = status["num_peers"]
- if "dht_nodes" in status:
- self.dht = status["dht_nodes"]
+ self.upload = deluge.common.fsize(status['payload_upload_rate'])
+ self.download = deluge.common.fsize(status['payload_download_rate'])
+ self.connections = status['num_peers']
+ if 'dht_nodes' in status:
+ self.dht = status['dht_nodes']
self.update_statusbars()
def on_get_external_ip(external_ip):
self.external_ip = external_ip
- keys = ["num_peers", "payload_upload_rate", "payload_download_rate"]
+ keys = ['num_peers', 'payload_upload_rate', 'payload_download_rate']
- if self.config["dht"]:
- keys.append("dht_nodes")
+ if self.config['dht']:
+ keys.append('dht_nodes')
client.core.get_session_status(keys).addCallback(on_get_session_status)
client.core.get_external_ip().addCallback(on_get_external_ip)
def update_statusbars(self):
# Update the topbar string
- self.topbar = "{!status!}Deluge %s Console - " % deluge.common.get_version()
+ self.topbar = '{!status!}Deluge %s Console - ' % deluge.common.get_version()
if client.connected():
info = client.connection_info()
- connection_info = ""
+ connection_info = ''
# Client name
- if info[2] == "localclient":
- connection_info += "{!white,blue!}%s"
+ if info[2] == 'localclient':
+ connection_info += '{!white,blue!}%s'
else:
- connection_info += "{!green,blue,bold!}%s"
+ connection_info += '{!green,blue,bold!}%s'
# Hostname
- if info[0] == "127.0.0.1":
- connection_info += "{!white,blue,bold!}@{!white,blue!}%s"
+ if info[0] == '127.0.0.1':
+ connection_info += '{!white,blue,bold!}@{!white,blue!}%s'
else:
- connection_info += "{!white,blue,bold!}@{!red,blue,bold!}%s"
+ connection_info += '{!white,blue,bold!}@{!red,blue,bold!}%s'
# Port
- if info[1] == DEFAULT_PREFS["daemon_port"]:
- connection_info += "{!white,blue!}:%s"
+ if info[1] == DEFAULT_PREFS['daemon_port']:
+ connection_info += '{!white,blue!}:%s'
else:
- connection_info += "{!status!}:%s"
+ connection_info += '{!status!}:%s'
# Change color back to normal, just in case
- connection_info += "{!status!}"
+ connection_info += '{!status!}'
self.topbar += connection_info % (info[2], info[0], info[1])
else:
- self.topbar += "Not Connected"
+ self.topbar += 'Not Connected'
# Update the bottombar string
- self.bottombar = "{!status!}C: {!white,blue!}%s{!status!}" % self.connections
+ self.bottombar = '{!status!}C: {!white,blue!}%s{!status!}' % self.connections
- if self.config["max_connections_global"] > -1:
- self.bottombar += " (%s)" % self.config["max_connections_global"]
+ if self.config['max_connections_global'] > -1:
+ self.bottombar += ' (%s)' % self.config['max_connections_global']
- if self.download != "0.0 KiB":
- self.bottombar += " D: {!magenta,blue,bold!}%s{!status!}" % self.download
+ if self.download != '0.0 KiB':
+ self.bottombar += ' D: {!magenta,blue,bold!}%s{!status!}' % self.download
else:
- self.bottombar += " D: {!white,blue!}%s{!status!}" % self.download
+ self.bottombar += ' D: {!white,blue!}%s{!status!}' % self.download
- if self.config["max_download_speed"] > -1:
- self.bottombar += " (%s " % self.config["max_download_speed"] + _("KiB/s") + ")"
+ if self.config['max_download_speed'] > -1:
+ self.bottombar += ' (%s ' % self.config['max_download_speed'] + _('KiB/s') + ')'
- if self.upload != "0.0 KiB":
- self.bottombar += " U: {!green,blue,bold!}%s{!status!}" % self.upload
+ if self.upload != '0.0 KiB':
+ self.bottombar += ' U: {!green,blue,bold!}%s{!status!}' % self.upload
else:
- self.bottombar += " U: {!white,blue!}%s{!status!}" % self.upload
+ self.bottombar += ' U: {!white,blue!}%s{!status!}' % self.upload
- if self.config["max_upload_speed"] > -1:
- self.bottombar += " (%s " % self.config["max_upload_speed"] + _("KiB/s") + ")"
+ if self.config['max_upload_speed'] > -1:
+ self.bottombar += ' (%s ' % self.config['max_upload_speed'] + _('KiB/s') + ')'
- if self.config["dht"]:
- self.bottombar += " " + _("DHT") + ": {!white,blue!}%s{!status!}" % self.dht
+ if self.config['dht']:
+ 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.bottombar += ' ' + _('IP {!white,blue!}%s{!status!}') % (
+ 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 1c83c1b25..a82107c66 100644
--- a/deluge/ui/console/widgets/window.py
+++ b/deluge/ui/console/widgets/window.py
@@ -40,14 +40,14 @@ class BaseWindow(object):
self.posy, self.posx = posy, posx
if encoding is None:
from deluge import component
- encoding = component.get("ConsoleUI").encoding
+ encoding = component.get('ConsoleUI').encoding
self.encoding = encoding
self.panel = mkpanel(curses.COLOR_GREEN, height, width, posy, posx)
self.outer_screen = self.panel.window()
self.outer_screen.bkgdset(0, curses.COLOR_RED)
by, bx = self.outer_screen.getbegyx()
- self.screen = mkpad(get_color_pair("white", "black"), height - 1, width - 2)
+ self.screen = mkpad(get_color_pair('white', 'black'), height - 1, width - 2)
self._height, self._width = self.outer_screen.getmaxyx()
@property
@@ -120,7 +120,7 @@ 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,
+ add_string(indicator_row, '{!red,black,bold!}#', screen, self.encoding,
col=indicator_col, pad=False, trim=False)
def refresh(self):
@@ -130,7 +130,7 @@ class BaseWindow(object):
if self.title:
toff = max(1, (self.width // 2) - (len(self.title) // 2))
- self.add_string(0, "{!white,black,bold!}%s" % self.title, scr=self.outer_screen, col=toff, pad=False)
+ self.add_string(0, '{!white,black,bold!}%s' % self.title, scr=self.outer_screen, col=toff, pad=False)
self.draw_scroll_indicator(self.outer_screen)
self.outer_screen.noutrefresh()
@@ -149,4 +149,4 @@ class BaseWindow(object):
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()))
+ pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, ''.join(traceback.format_stack()))
diff --git a/deluge/ui/coreconfig.py b/deluge/ui/coreconfig.py
index 887e37e50..2014bb869 100644
--- a/deluge/ui/coreconfig.py
+++ b/deluge/ui/coreconfig.py
@@ -17,13 +17,13 @@ log = logging.getLogger(__name__)
class CoreConfig(component.Component):
def __init__(self):
- log.debug("CoreConfig init..")
- component.Component.__init__(self, "CoreConfig")
+ log.debug('CoreConfig init..')
+ component.Component.__init__(self, 'CoreConfig')
self.config = {}
def on_configvaluechanged_event(key, value):
self.config[key] = value
- client.register_event_handler("ConfigValueChangedEvent", on_configvaluechanged_event)
+ client.register_event_handler('ConfigValueChangedEvent', on_configvaluechanged_event)
def start(self):
def on_get_config(config):
diff --git a/deluge/ui/gtkui/__init__.py b/deluge/ui/gtkui/__init__.py
index 5836b7ecd..4f64705ee 100644
--- a/deluge/ui/gtkui/__init__.py
+++ b/deluge/ui/gtkui/__init__.py
@@ -20,12 +20,12 @@ class Gtk(UI):
cmd_description = """GTK-based graphical user interface"""
def __init__(self, *args, **kwargs):
- super(Gtk, self).__init__("gtk", *args, description="Starts the Deluge GTK+ interface", **kwargs)
+ 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 = 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'))
def start(self):
super(Gtk, self).start()
diff --git a/deluge/ui/gtkui/aboutdialog.py b/deluge/ui/gtkui/aboutdialog.py
index 037411423..3ddf489ab 100644
--- a/deluge/ui/gtkui/aboutdialog.py
+++ b/deluge/ui/gtkui/aboutdialog.py
@@ -24,251 +24,251 @@ class AboutDialog(object):
gtk.about_dialog_set_url_hook(url_hook)
self.about = gtk.AboutDialog()
self.about.set_position(gtk.WIN_POS_CENTER)
- self.about.set_name("Deluge")
- self.about.set_program_name(_("Deluge"))
+ self.about.set_name('Deluge')
+ self.about.set_program_name(_('Deluge'))
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)
+ _('A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.') +
+ '\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"
+ _('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'
])
- self.about.set_artists(["Andrew Wedderburn", "Andrew Resch"])
- self.about.set_translator_credits("\n".join([
- "Aaron Wang Shi", "abbigss", "ABCdatos", "Abcx", "Actam", "Adam",
- "adaminikisi", "adi_oporanu", "Adrian Goll", "afby", "Ahmades",
- "Ahmad Farghal", "Ahmad Gharbeia أحمد غربية", "akira", "Aki Sivula",
- "Alan Pepelko", "Alberto", "Alberto Ferrer", "alcatr4z", "AlckO",
- "Aleksej Korgenkov", "Alessio Treglia", "Alexander Ilyashov",
- "Alexander Matveev", "Alexander Saltykov", "Alexander Taubenkorb",
- "Alexander Telenga", "Alexander Yurtsev", "Alexandre Martani",
- "Alexandre Rosenfeld", "Alexandre Sapata Carbonell",
- "Alexey Osipov", "Alin Claudiu Radut", "allah", "AlSim",
- "Alvaro Carrillanca P.", "A.Matveev", "Andras Hipsag",
- "András Kárász", "Andrea Ratto", "Andreas Johansson", "Andreas Str",
- "André F. Oliveira", "AndreiF", "andrewh", "Angel Guzman Maeso",
- "Aníbal Deboni Neto", "animarval", "Antonio Cono", "antoniojreyes",
- "Anton Shestakov", "Anton Yakutovich", "antou",
- "Arkadiusz Kalinowski", "Artin", "artir", "Astur",
- "Athanasios Lefteris", "Athmane MOKRAOUI (ButterflyOfFire)",
- "Augusta Carla Klug", "Avoledo Marco", "axaard", "AxelRafn",
- "Axezium", "Ayont", "b3rx", "Bae Taegil", "Bajusz Tamás",
- "Balaam's Miracle", "Ballestein", "Bent Ole Fosse", "berto89",
- "bigx", "Bjorn Inge Berg", "blackbird", "Blackeyed", "blackmx",
- "BlueSky", "Blutheo", "bmhm", "bob00work", "boenki",
- "Bogdan Bădic-Spătariu", "bonpu", "Boone", "boss01",
- "Branislav Jovanović", "bronze", "brownie", "Brus46", "bumper",
- "butely", "BXCracer", "c0nfidencal", "Can Kaya",
- "Carlos Alexandro Becker", "cassianoleal", "Cédric.h",
- "César Rubén", "chaoswizard", "Chen Tao", "chicha",
- "Chien Cheng Wei", "Christian Kopac", "Christian Widell",
- "Christoffer Brodd-Reijer", "christooss", "CityAceE", "Clopy",
- "Clusty", "cnu", "Commandant", "Constantinos Koniaris", "Coolmax",
- "cosmix", "Costin Chirvasuta", "CoVaLiDiTy", "cow_2001",
- "Crispin Kirchner", "crom", "Cruster", "Cybolic", "Dan Bishop",
- "Danek", "Dani", "Daniel Demarco", "Daniel Ferreira",
- "Daniel Frank", "Daniel Holm", "Daniel Høyer Iversen",
- "Daniel Marynicz", "Daniel Nylander", "Daniel Patriche",
- "Daniel Schildt", "Daniil Sorokin", "Dante Díaz", "Daria Michalska",
- "DarkenCZ", "Darren", "Daspah", "David Eurenius", "davidhjelm",
- "David Machakhelidze", "Dawid Dziurdzia", "Daya Adianto ", "dcruz",
- "Deady", "Dereck Wonnacott", "Devgru", "Devid Antonio Filoni"
- "DevilDogTG", "di0rz`", "Dialecti Valsamou", "Diego Medeiros",
- "Dkzoffy", "Dmitrij D. Czarkoff", "Dmitriy Geels",
- "Dmitry Olyenyov", "Dominik Kozaczko", "Dominik Lübben", "doomster",
- "Dorota Król", "Doyen Philippe", "Dread Knight", "DreamSonic",
- "duan", "Duong Thanh An", "DvoglavaZver", "dwori", "dylansmrjones",
- "Ebuntor", "Edgar Alejandro Jarquin Flores", "Eetu", "ekerazha",
- "Elias Julkunen", "elparia", "Emberke", "Emiliano Goday Caneda",
- "EndelWar", "eng.essam", "enubuntu", "ercangun", "Erdal Ronahi",
- "ergin üresin", "Eric", "Éric Lassauge", "Erlend Finvåg", "Errdil",
- "ethan shalev", "Evgeni Spasov", "ezekielnin", "Fabian Ordelmans",
- "Fabio Mazanatti", "Fábio Nogueira", "FaCuZ", "Felipe Lerena",
- "Fernando Pereira", "fjetland", "Florian Schäfer", "FoBoS", "Folke",
- "Force", "fosk", "fragarray", "freddeg", "Frédéric Perrin",
- "Fredrik Kilegran", "FreeAtMind", "Fulvio Ciucci", "Gabor Kelemen",
- "Galatsanos Panagiotis", "Gaussian", "gdevitis", "Georg Brzyk",
- "George Dumitrescu", "Georgi Arabadjiev", "Georg Sieber",
- "Gerd Radecke", "Germán Heusdens", "Gianni Vialetto",
- "Gigih Aji Ibrahim", "Giorgio Wicklein", "Giovanni Rapagnani",
- "Giuseppe", "gl", "glen", "granjerox", "Green Fish", "greentea",
- "Greyhound", "G. U.", "Guillaume BENOIT", "Guillaume Pelletier",
- "Gustavo Henrique Klug", "gutocarvalho", "Guybrush88",
- "Hans Rødtang", "HardDisk", "Hargas Gábor",
- "Heitor Thury Barreiros Barbosa", "helios91940", "helix84",
- "Helton Rodrigues", "Hendrik Luup", "Henrique Ferreiro",
- "Henry Goury-Laffont", "Hezy Amiel", "hidro", "hoball", "hokten",
- "Holmsss", "hristo.num", "Hubert Życiński", "Hyo", "Iarwain", "ibe",
- "ibear", "Id2ndR", "Igor Zubarev", "IKON (Ion)", "imen",
- "Ionuț Jula", "Isabelle STEVANT", "István Nyitrai", "Ivan Petrovic",
- "Ivan Prignano", "IvaSerge", "jackmc", "Jacks0nxD", "Jack Shen",
- "Jacky Yeung", "Jacques Stadler", "Janek Thomaschewski", "Jan Kaláb",
- "Jan Niklas Hasse", "Jasper Groenewegen", "Javi Rodríguez",
- "Jayasimha (ಜಯಸಿಂಹ)", "jeannich", "Jeff Bailes", "Jesse Zilstorff",
- "Joan Duran", "João Santos", "Joar Bagge", "Joe Anderson",
- "Joel Calado", "Johan Linde", "John Garland", "Jojan", "jollyr0ger",
- "Jonas Bo Grimsgaard", "Jonas Granqvist", "Jonas Slivka",
- "Jonathan Zeppettini", "Jørgen", "Jørgen Tellnes", "josé",
- "José Geraldo Gouvêa", "José Iván León Islas", "José Lou C.",
- "Jose Sun", "Jr.", "Jukka Kauppinen", "Julián Alarcón",
- "julietgolf", "Jusic", "Justzupi", "Kaarel", "Kai Thomsen",
- "Kalman Tarnay", "Kamil Páral", "Kane_F", "kaotiks@gmail.com",
- "Kateikyoushii", "kaxhinaz", "Kazuhiro NISHIYAMA", "Kerberos",
- "Keresztes Ákos", "kevintyk", "kiersie", "Kimbo^", "Kim Lübbe",
- "kitzOgen", "Kjetil Rydland", "kluon", "kmikz", "Knedlyk",
- "koleoptero", "Kőrösi Krisztián", "Kouta", "Krakatos",
- "Krešo Kunjas", "kripken", "Kristaps", "Kristian Øllegaard",
- "Kristoffer Egil Bonarjee", "Krzysztof Janowski",
- "Krzysztof Zawada", "Larry Wei Liu", "laughterwym", "Laur Mõtus",
- "lazka", "leandrud", "lê bình", "Le Coz Florent", "Leo", "liorda",
- "LKRaider", "LoLo_SaG", "Long Tran", "Lorenz", "Low Kian Seong",
- "Luca Andrea Rossi", "Luca Ferretti", "Lucky LIX", "Luis Gomes",
- "Luis Reis", "Łukasz Wyszyński", "luojie-dune", "maaark",
- "Maciej Chojnacki", "Maciej Meller", "Mads Peter Rommedahl",
- "Major Kong", "Malaki", "malde", "Malte Lenz", "Mantas Kriaučiūnas",
- "Mara Sorella", "Marcin", "Marcin Falkiewicz", "marcobra",
- "Marco da Silva", "Marco de Moulin", "Marco Rodrigues", "Marcos",
- "Marcos Escalier", "Marcos Mobley", "Marcus Ekstrom",
- "Marek Dębowski", "Mário Buči", "Mario Munda", "Marius Andersen",
- "Marius Hudea", "Marius Mihai", "Mariusz Cielecki",
- "Mark Krapivner", "marko-markovic", "Markus Brummer",
- "Markus Sutter", "Martin", "Martin Dybdal", "Martin Iglesias",
- "Martin Lettner", "Martin Pihl", "Masoud Kalali", "mat02",
- "Matej Urbančič", "Mathias-K", "Mathieu Arès",
- "Mathieu D. (MatToufoutu)", "Mathijs", "Matrik", "Matteo Renzulli",
- "Matteo Settenvini", "Matthew Gadd", "Matthias Benkard",
- "Matthias Mailänder", "Mattias Ohlsson", "Mauro de Carvalho",
- "Max Molchanov", "Me", "MercuryCC", "Mert Bozkurt", "Mert Dirik",
- "MFX", "mhietar", "mibtha", "Michael Budde", "Michael Kaliszka",
- "Michalis Makaronides", "Michał Tokarczyk", "Miguel Pires da Rosa",
- "Mihai Capotă", "Miika Metsälä", "Mikael Fernblad", "Mike Sierra",
- "mikhalek", "Milan Prvulović", "Milo Casagrande", "Mindaugas",
- "Miroslav Matejaš", "misel", "mithras", "Mitja Pagon", "M.Kitchen",
- "Mohamed Magdy", "moonkey", "MrBlonde", "muczy", "Münir Ekinci",
- "Mustafa Temizel", "mvoncken", "Mytonn", "NagyMarton", "neaion",
- "Neil Lin", "Nemo", "Nerijus Arlauskas", "Nicklas Larsson",
- "Nicolaj Wyke", "Nicola Piovesan", "Nicolas Sabatier",
- "Nicolas Velin", "Nightfall", "NiKoB", "Nikolai M. Riabov",
- "Niko_Thien", "niska", "Nithir", "noisemonkey", "nomemohes",
- "nosense", "null", "Nuno Estêvão", "Nuno Santos", "nxxs", "nyo",
- "obo", "Ojan", "Olav Andreas Lindekleiv", "oldbeggar",
- "Olivier FAURAX", "orphe", "osantana", "Osman Tosun", "OssiR",
- "otypoks", "ounn", "Oz123", "Özgür BASKIN", "Pablo Carmona A.",
- "Pablo Ledesma", "Pablo Navarro Castillo", "Paco Molinero",
- "Pål-Eivind Johnsen", "pano", "Paolo Naldini", "Paracelsus",
- "Patryk13_03", "Patryk Skorupa", "PattogoTehen", "Paul Lange",
- "Pavcio", "Paweł Wysocki", "Pedro Brites Moita",
- "Pedro Clemente Pereira Neto", "Pekka \"PEXI\" Niemistö", "Penegal",
- "Penzo", "perdido", "Peter Kotrcka", "Peter Skov",
- "Peter Van den Bosch", "Petter Eklund", "Petter Viklund",
- "phatsphere", "Phenomen", "Philipi", "Philippides Homer", "phoenix",
- "pidi", "Pierre Quillery", "Pierre Rudloff", "Pierre Slamich",
- "Pietrao", "Piotr Strębski", "Piotr Wicijowski", "Pittmann Tamás",
- "Playmolas", "Prescott", "Prescott_SK", "pronull",
- "Przemysław Kulczycki", "Pumy", "pushpika", "PY", "qubicllj",
- "r21vo", "Rafał Barański", "rainofchaos", "Rajbir", "ras0ir", "Rat",
- "rd1381", "Renato", "Rene Hennig", "Rene Pärts", "Ricardo Duarte",
- "Richard", "Robert Hrovat", "Roberth Sjonøy", "Robert Lundmark",
- "Robin Jakobsson", "Robin Kåveland", "Rodrigo Donado",
- "Roel Groeneveld", "rohmaru", "Rolf Christensen", "Rolf Leggewie",
- "Roni Kantis", "Ronmi", "Rostislav Raykov", "royto", "RuiAmaro",
- "Rui Araújo", "Rui Moura", "Rune Svendsen", "Rusna", "Rytis",
- "Sabirov Mikhail", "salseeg", "Sami Koskinen", "Samir van de Sand",
- "Samuel Arroyo Acuña", "Samuel R. C. Vale", "Sanel", "Santi",
- "Santi Martínez Cantelli", "Sardan", "Sargate Kanogan",
- "Sarmad Jari", "Saša Bodiroža", "sat0shi", "Saulius Pranckevičius",
- "Savvas Radevic", "Sebastian Krauß", "Sebastián Porta", "Sedir",
- "Sefa Denizoğlu", "sekolands", "Selim Suerkan", "semsomi",
- "Sergii Golovatiuk", "setarcos", "Sheki", "Shironeko", "Shlomil",
- "silfiriel", "Simone Tolotti", "Simone Vendemia", "sirkubador",
- "Sławomir Więch", "slip", "slyon", "smoke", "Sonja", "spectral",
- "spin_555", "spitf1r3", "Spiziuz", "Spyros Theodoritsis", "SqUe",
- "Squigly", "srtck", "Stefan Horning", "Stefano Maggiolo",
- "Stefano Roberto Soleti", "steinberger", "Stéphane Travostino",
- "Stephan Klein", "Steven De Winter", "Stevie", "Stian24", "stylius",
- "Sukarn Maini", "Sunjae Park", "Susana Pereira", "szymon siglowy",
- "takercena", "TAS", "Taygeto", "temy4", "texxxxxx", "thamood",
- "Thanos Chatziathanassiou", "Tharawut Paripaiboon", "Theodoor",
- "Théophane Anestis", "Thor Marius K. Høgås", "Tiago Silva",
- "Tiago Sousa", "Tikkel", "tim__b", "Tim Bordemann", "Tim Fuchs",
- "Tim Kornhammar", "Timo", "Timo Jyrinki", "Timothy Babych",
- "TitkosRejtozo", "Tom", "Tomas Gustavsson", "Tomas Valentukevičius",
- "Tomasz Dominikowski", "Tomislav Plavčić", "Tom Mannerhagen",
- "Tommy Mikkelsen", "Tom Verdaat", "Tony Manco",
- "Tor Erling H. Opsahl", "Toudi", "tqm_z", "Trapanator", "Tribaal",
- "Triton", "TuniX12", "Tuomo Sipola", "turbojugend_gr", "Turtle.net",
- "twilight", "tymmej", "Ulrik", "Umarzuki Mochlis", "unikob",
- "Vadim Gusev", "Vagi", "Valentin Bora", "Valmantas Palikša",
- "VASKITTU", "Vassilis Skoullis", "vetal17", "vicedo", "viki",
- "villads hamann", "Vincent Garibal", "Vincent Ortalda", "vinchi007",
- "Vinícius de Figueiredo Silva", "Vinzenz Vietzke", "virtoo",
- "virtual_spirit", "Vitor Caike", "Vitor Lamas Gatti",
- "Vladimir Lazic", "Vladimir Sharshov", "Wanderlust", "Wander Nauta",
- "Ward De Ridder", "WebCrusader", "webdr", "Wentao Tang", "wilana",
- "Wilfredo Ernesto Guerrero Campos", "Wim Champagne", "World Sucks",
- "Xabi Ezpeleta", "Xavi de Moner", "XavierToo", "XChesser",
- "Xiaodong Xu", "xyb", "Yaron", "Yasen Pramatarov", "YesPoX",
- "Yuren Ju", "Yves MATHIEU", "zekopeko", "zhuqin", "Zissan",
- "Γιάννης Κατσαμπίρης", "Артём Попов", "Миша", "Шаймарданов Максим",
- "蔡查理"
+ self.about.set_artists(['Andrew Wedderburn', 'Andrew Resch'])
+ self.about.set_translator_credits('\n'.join([
+ 'Aaron Wang Shi', 'abbigss', 'ABCdatos', 'Abcx', 'Actam', 'Adam',
+ 'adaminikisi', 'adi_oporanu', 'Adrian Goll', 'afby', 'Ahmades',
+ 'Ahmad Farghal', 'Ahmad Gharbeia أحمد غربية', 'akira', 'Aki Sivula',
+ 'Alan Pepelko', 'Alberto', 'Alberto Ferrer', 'alcatr4z', 'AlckO',
+ 'Aleksej Korgenkov', 'Alessio Treglia', 'Alexander Ilyashov',
+ 'Alexander Matveev', 'Alexander Saltykov', 'Alexander Taubenkorb',
+ 'Alexander Telenga', 'Alexander Yurtsev', 'Alexandre Martani',
+ 'Alexandre Rosenfeld', 'Alexandre Sapata Carbonell',
+ 'Alexey Osipov', 'Alin Claudiu Radut', 'allah', 'AlSim',
+ 'Alvaro Carrillanca P.', 'A.Matveev', 'Andras Hipsag',
+ 'András Kárász', 'Andrea Ratto', 'Andreas Johansson', 'Andreas Str',
+ 'André F. Oliveira', 'AndreiF', 'andrewh', 'Angel Guzman Maeso',
+ 'Aníbal Deboni Neto', 'animarval', 'Antonio Cono', 'antoniojreyes',
+ 'Anton Shestakov', 'Anton Yakutovich', 'antou',
+ 'Arkadiusz Kalinowski', 'Artin', 'artir', 'Astur',
+ 'Athanasios Lefteris', 'Athmane MOKRAOUI (ButterflyOfFire)',
+ 'Augusta Carla Klug', 'Avoledo Marco', 'axaard', 'AxelRafn',
+ 'Axezium', 'Ayont', 'b3rx', 'Bae Taegil', 'Bajusz Tamás',
+ "Balaam's Miracle", 'Ballestein', 'Bent Ole Fosse', 'berto89',
+ 'bigx', 'Bjorn Inge Berg', 'blackbird', 'Blackeyed', 'blackmx',
+ 'BlueSky', 'Blutheo', 'bmhm', 'bob00work', 'boenki',
+ 'Bogdan Bădic-Spătariu', 'bonpu', 'Boone', 'boss01',
+ 'Branislav Jovanović', 'bronze', 'brownie', 'Brus46', 'bumper',
+ 'butely', 'BXCracer', 'c0nfidencal', 'Can Kaya',
+ 'Carlos Alexandro Becker', 'cassianoleal', 'Cédric.h',
+ 'César Rubén', 'chaoswizard', 'Chen Tao', 'chicha',
+ 'Chien Cheng Wei', 'Christian Kopac', 'Christian Widell',
+ 'Christoffer Brodd-Reijer', 'christooss', 'CityAceE', 'Clopy',
+ 'Clusty', 'cnu', 'Commandant', 'Constantinos Koniaris', 'Coolmax',
+ 'cosmix', 'Costin Chirvasuta', 'CoVaLiDiTy', 'cow_2001',
+ 'Crispin Kirchner', 'crom', 'Cruster', 'Cybolic', 'Dan Bishop',
+ 'Danek', 'Dani', 'Daniel Demarco', 'Daniel Ferreira',
+ 'Daniel Frank', 'Daniel Holm', 'Daniel Høyer Iversen',
+ 'Daniel Marynicz', 'Daniel Nylander', 'Daniel Patriche',
+ 'Daniel Schildt', 'Daniil Sorokin', 'Dante Díaz', 'Daria Michalska',
+ 'DarkenCZ', 'Darren', 'Daspah', 'David Eurenius', 'davidhjelm',
+ 'David Machakhelidze', 'Dawid Dziurdzia', 'Daya Adianto ', 'dcruz',
+ 'Deady', 'Dereck Wonnacott', 'Devgru', 'Devid Antonio Filoni'
+ 'DevilDogTG', 'di0rz`', 'Dialecti Valsamou', 'Diego Medeiros',
+ 'Dkzoffy', 'Dmitrij D. Czarkoff', 'Dmitriy Geels',
+ 'Dmitry Olyenyov', 'Dominik Kozaczko', 'Dominik Lübben', 'doomster',
+ 'Dorota Król', 'Doyen Philippe', 'Dread Knight', 'DreamSonic',
+ 'duan', 'Duong Thanh An', 'DvoglavaZver', 'dwori', 'dylansmrjones',
+ 'Ebuntor', 'Edgar Alejandro Jarquin Flores', 'Eetu', 'ekerazha',
+ 'Elias Julkunen', 'elparia', 'Emberke', 'Emiliano Goday Caneda',
+ 'EndelWar', 'eng.essam', 'enubuntu', 'ercangun', 'Erdal Ronahi',
+ 'ergin üresin', 'Eric', 'Éric Lassauge', 'Erlend Finvåg', 'Errdil',
+ 'ethan shalev', 'Evgeni Spasov', 'ezekielnin', 'Fabian Ordelmans',
+ 'Fabio Mazanatti', 'Fábio Nogueira', 'FaCuZ', 'Felipe Lerena',
+ 'Fernando Pereira', 'fjetland', 'Florian Schäfer', 'FoBoS', 'Folke',
+ 'Force', 'fosk', 'fragarray', 'freddeg', 'Frédéric Perrin',
+ 'Fredrik Kilegran', 'FreeAtMind', 'Fulvio Ciucci', 'Gabor Kelemen',
+ 'Galatsanos Panagiotis', 'Gaussian', 'gdevitis', 'Georg Brzyk',
+ 'George Dumitrescu', 'Georgi Arabadjiev', 'Georg Sieber',
+ 'Gerd Radecke', 'Germán Heusdens', 'Gianni Vialetto',
+ 'Gigih Aji Ibrahim', 'Giorgio Wicklein', 'Giovanni Rapagnani',
+ 'Giuseppe', 'gl', 'glen', 'granjerox', 'Green Fish', 'greentea',
+ 'Greyhound', 'G. U.', 'Guillaume BENOIT', 'Guillaume Pelletier',
+ 'Gustavo Henrique Klug', 'gutocarvalho', 'Guybrush88',
+ 'Hans Rødtang', 'HardDisk', 'Hargas Gábor',
+ 'Heitor Thury Barreiros Barbosa', 'helios91940', 'helix84',
+ 'Helton Rodrigues', 'Hendrik Luup', 'Henrique Ferreiro',
+ 'Henry Goury-Laffont', 'Hezy Amiel', 'hidro', 'hoball', 'hokten',
+ 'Holmsss', 'hristo.num', 'Hubert Życiński', 'Hyo', 'Iarwain', 'ibe',
+ 'ibear', 'Id2ndR', 'Igor Zubarev', 'IKON (Ion)', 'imen',
+ 'Ionuț Jula', 'Isabelle STEVANT', 'István Nyitrai', 'Ivan Petrovic',
+ 'Ivan Prignano', 'IvaSerge', 'jackmc', 'Jacks0nxD', 'Jack Shen',
+ 'Jacky Yeung', 'Jacques Stadler', 'Janek Thomaschewski', 'Jan Kaláb',
+ 'Jan Niklas Hasse', 'Jasper Groenewegen', 'Javi Rodríguez',
+ 'Jayasimha (ಜಯಸಿಂಹ)', 'jeannich', 'Jeff Bailes', 'Jesse Zilstorff',
+ 'Joan Duran', 'João Santos', 'Joar Bagge', 'Joe Anderson',
+ 'Joel Calado', 'Johan Linde', 'John Garland', 'Jojan', 'jollyr0ger',
+ 'Jonas Bo Grimsgaard', 'Jonas Granqvist', 'Jonas Slivka',
+ 'Jonathan Zeppettini', 'Jørgen', 'Jørgen Tellnes', 'josé',
+ 'José Geraldo Gouvêa', 'José Iván León Islas', 'José Lou C.',
+ 'Jose Sun', 'Jr.', 'Jukka Kauppinen', 'Julián Alarcón',
+ 'julietgolf', 'Jusic', 'Justzupi', 'Kaarel', 'Kai Thomsen',
+ 'Kalman Tarnay', 'Kamil Páral', 'Kane_F', 'kaotiks@gmail.com',
+ 'Kateikyoushii', 'kaxhinaz', 'Kazuhiro NISHIYAMA', 'Kerberos',
+ 'Keresztes Ákos', 'kevintyk', 'kiersie', 'Kimbo^', 'Kim Lübbe',
+ 'kitzOgen', 'Kjetil Rydland', 'kluon', 'kmikz', 'Knedlyk',
+ 'koleoptero', 'Kőrösi Krisztián', 'Kouta', 'Krakatos',
+ 'Krešo Kunjas', 'kripken', 'Kristaps', 'Kristian Øllegaard',
+ 'Kristoffer Egil Bonarjee', 'Krzysztof Janowski',
+ 'Krzysztof Zawada', 'Larry Wei Liu', 'laughterwym', 'Laur Mõtus',
+ 'lazka', 'leandrud', 'lê bình', 'Le Coz Florent', 'Leo', 'liorda',
+ 'LKRaider', 'LoLo_SaG', 'Long Tran', 'Lorenz', 'Low Kian Seong',
+ 'Luca Andrea Rossi', 'Luca Ferretti', 'Lucky LIX', 'Luis Gomes',
+ 'Luis Reis', 'Łukasz Wyszyński', 'luojie-dune', 'maaark',
+ 'Maciej Chojnacki', 'Maciej Meller', 'Mads Peter Rommedahl',
+ 'Major Kong', 'Malaki', 'malde', 'Malte Lenz', 'Mantas Kriaučiūnas',
+ 'Mara Sorella', 'Marcin', 'Marcin Falkiewicz', 'marcobra',
+ 'Marco da Silva', 'Marco de Moulin', 'Marco Rodrigues', 'Marcos',
+ 'Marcos Escalier', 'Marcos Mobley', 'Marcus Ekstrom',
+ 'Marek Dębowski', 'Mário Buči', 'Mario Munda', 'Marius Andersen',
+ 'Marius Hudea', 'Marius Mihai', 'Mariusz Cielecki',
+ 'Mark Krapivner', 'marko-markovic', 'Markus Brummer',
+ 'Markus Sutter', 'Martin', 'Martin Dybdal', 'Martin Iglesias',
+ 'Martin Lettner', 'Martin Pihl', 'Masoud Kalali', 'mat02',
+ 'Matej Urbančič', 'Mathias-K', 'Mathieu Arès',
+ 'Mathieu D. (MatToufoutu)', 'Mathijs', 'Matrik', 'Matteo Renzulli',
+ 'Matteo Settenvini', 'Matthew Gadd', 'Matthias Benkard',
+ 'Matthias Mailänder', 'Mattias Ohlsson', 'Mauro de Carvalho',
+ 'Max Molchanov', 'Me', 'MercuryCC', 'Mert Bozkurt', 'Mert Dirik',
+ 'MFX', 'mhietar', 'mibtha', 'Michael Budde', 'Michael Kaliszka',
+ 'Michalis Makaronides', 'Michał Tokarczyk', 'Miguel Pires da Rosa',
+ 'Mihai Capotă', 'Miika Metsälä', 'Mikael Fernblad', 'Mike Sierra',
+ 'mikhalek', 'Milan Prvulović', 'Milo Casagrande', 'Mindaugas',
+ 'Miroslav Matejaš', 'misel', 'mithras', 'Mitja Pagon', 'M.Kitchen',
+ 'Mohamed Magdy', 'moonkey', 'MrBlonde', 'muczy', 'Münir Ekinci',
+ 'Mustafa Temizel', 'mvoncken', 'Mytonn', 'NagyMarton', 'neaion',
+ 'Neil Lin', 'Nemo', 'Nerijus Arlauskas', 'Nicklas Larsson',
+ 'Nicolaj Wyke', 'Nicola Piovesan', 'Nicolas Sabatier',
+ 'Nicolas Velin', 'Nightfall', 'NiKoB', 'Nikolai M. Riabov',
+ 'Niko_Thien', 'niska', 'Nithir', 'noisemonkey', 'nomemohes',
+ 'nosense', 'null', 'Nuno Estêvão', 'Nuno Santos', 'nxxs', 'nyo',
+ 'obo', 'Ojan', 'Olav Andreas Lindekleiv', 'oldbeggar',
+ 'Olivier FAURAX', 'orphe', 'osantana', 'Osman Tosun', 'OssiR',
+ 'otypoks', 'ounn', 'Oz123', 'Özgür BASKIN', 'Pablo Carmona A.',
+ 'Pablo Ledesma', 'Pablo Navarro Castillo', 'Paco Molinero',
+ 'Pål-Eivind Johnsen', 'pano', 'Paolo Naldini', 'Paracelsus',
+ 'Patryk13_03', 'Patryk Skorupa', 'PattogoTehen', 'Paul Lange',
+ 'Pavcio', 'Paweł Wysocki', 'Pedro Brites Moita',
+ 'Pedro Clemente Pereira Neto', "Pekka \"PEXI\" Niemistö", 'Penegal',
+ 'Penzo', 'perdido', 'Peter Kotrcka', 'Peter Skov',
+ 'Peter Van den Bosch', 'Petter Eklund', 'Petter Viklund',
+ 'phatsphere', 'Phenomen', 'Philipi', 'Philippides Homer', 'phoenix',
+ 'pidi', 'Pierre Quillery', 'Pierre Rudloff', 'Pierre Slamich',
+ 'Pietrao', 'Piotr Strębski', 'Piotr Wicijowski', 'Pittmann Tamás',
+ 'Playmolas', 'Prescott', 'Prescott_SK', 'pronull',
+ 'Przemysław Kulczycki', 'Pumy', 'pushpika', 'PY', 'qubicllj',
+ 'r21vo', 'Rafał Barański', 'rainofchaos', 'Rajbir', 'ras0ir', 'Rat',
+ 'rd1381', 'Renato', 'Rene Hennig', 'Rene Pärts', 'Ricardo Duarte',
+ 'Richard', 'Robert Hrovat', 'Roberth Sjonøy', 'Robert Lundmark',
+ 'Robin Jakobsson', 'Robin Kåveland', 'Rodrigo Donado',
+ 'Roel Groeneveld', 'rohmaru', 'Rolf Christensen', 'Rolf Leggewie',
+ 'Roni Kantis', 'Ronmi', 'Rostislav Raykov', 'royto', 'RuiAmaro',
+ 'Rui Araújo', 'Rui Moura', 'Rune Svendsen', 'Rusna', 'Rytis',
+ 'Sabirov Mikhail', 'salseeg', 'Sami Koskinen', 'Samir van de Sand',
+ 'Samuel Arroyo Acuña', 'Samuel R. C. Vale', 'Sanel', 'Santi',
+ 'Santi Martínez Cantelli', 'Sardan', 'Sargate Kanogan',
+ 'Sarmad Jari', 'Saša Bodiroža', 'sat0shi', 'Saulius Pranckevičius',
+ 'Savvas Radevic', 'Sebastian Krauß', 'Sebastián Porta', 'Sedir',
+ 'Sefa Denizoğlu', 'sekolands', 'Selim Suerkan', 'semsomi',
+ 'Sergii Golovatiuk', 'setarcos', 'Sheki', 'Shironeko', 'Shlomil',
+ 'silfiriel', 'Simone Tolotti', 'Simone Vendemia', 'sirkubador',
+ 'Sławomir Więch', 'slip', 'slyon', 'smoke', 'Sonja', 'spectral',
+ 'spin_555', 'spitf1r3', 'Spiziuz', 'Spyros Theodoritsis', 'SqUe',
+ 'Squigly', 'srtck', 'Stefan Horning', 'Stefano Maggiolo',
+ 'Stefano Roberto Soleti', 'steinberger', 'Stéphane Travostino',
+ 'Stephan Klein', 'Steven De Winter', 'Stevie', 'Stian24', 'stylius',
+ 'Sukarn Maini', 'Sunjae Park', 'Susana Pereira', 'szymon siglowy',
+ 'takercena', 'TAS', 'Taygeto', 'temy4', 'texxxxxx', 'thamood',
+ 'Thanos Chatziathanassiou', 'Tharawut Paripaiboon', 'Theodoor',
+ 'Théophane Anestis', 'Thor Marius K. Høgås', 'Tiago Silva',
+ 'Tiago Sousa', 'Tikkel', 'tim__b', 'Tim Bordemann', 'Tim Fuchs',
+ 'Tim Kornhammar', 'Timo', 'Timo Jyrinki', 'Timothy Babych',
+ 'TitkosRejtozo', 'Tom', 'Tomas Gustavsson', 'Tomas Valentukevičius',
+ 'Tomasz Dominikowski', 'Tomislav Plavčić', 'Tom Mannerhagen',
+ 'Tommy Mikkelsen', 'Tom Verdaat', 'Tony Manco',
+ 'Tor Erling H. Opsahl', 'Toudi', 'tqm_z', 'Trapanator', 'Tribaal',
+ 'Triton', 'TuniX12', 'Tuomo Sipola', 'turbojugend_gr', 'Turtle.net',
+ 'twilight', 'tymmej', 'Ulrik', 'Umarzuki Mochlis', 'unikob',
+ 'Vadim Gusev', 'Vagi', 'Valentin Bora', 'Valmantas Palikša',
+ 'VASKITTU', 'Vassilis Skoullis', 'vetal17', 'vicedo', 'viki',
+ 'villads hamann', 'Vincent Garibal', 'Vincent Ortalda', 'vinchi007',
+ 'Vinícius de Figueiredo Silva', 'Vinzenz Vietzke', 'virtoo',
+ 'virtual_spirit', 'Vitor Caike', 'Vitor Lamas Gatti',
+ 'Vladimir Lazic', 'Vladimir Sharshov', 'Wanderlust', 'Wander Nauta',
+ 'Ward De Ridder', 'WebCrusader', 'webdr', 'Wentao Tang', 'wilana',
+ 'Wilfredo Ernesto Guerrero Campos', 'Wim Champagne', 'World Sucks',
+ 'Xabi Ezpeleta', 'Xavi de Moner', 'XavierToo', 'XChesser',
+ 'Xiaodong Xu', 'xyb', 'Yaron', 'Yasen Pramatarov', 'YesPoX',
+ 'Yuren Ju', 'Yves MATHIEU', 'zekopeko', 'zhuqin', 'Zissan',
+ 'Γιάννης Κατσαμπίρης', 'Артём Попов', 'Миша', 'Шаймарданов Максим',
+ '蔡查理'
]))
self.about.set_wrap_license(True)
self.about.set_license(_(
- "This program is free software; you can redistribute it and/or "
- "modify it under the terms of the GNU General Public License as "
- "published by the Free Software Foundation; either version 3 of "
- "the License, or (at your option) any later version. \n\n"
- "This program "
- "is distributed in the hope that it will be useful, but WITHOUT "
- "ANY WARRANTY; without even the implied warranty of "
- "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU "
- "General Public License for more details. \n\n"
- "You should have received "
- "a copy of the GNU General Public License along with this program; "
- "if not, see <http://www.gnu.org/licenses>. \n\n"
- "In addition, as a "
- "special exception, the copyright holders give permission to link "
- "the code of portions of this program with the OpenSSL library. "
- "You must obey the GNU General Public License in all respects for "
- "all of the code used other than OpenSSL. \n\n"
- "If you modify file(s) "
- "with this exception, you may extend this exception to your "
- "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."
+ 'This program is free software; you can redistribute it and/or '
+ 'modify it under the terms of the GNU General Public License as '
+ 'published by the Free Software Foundation; either version 3 of '
+ 'the License, or (at your option) any later version. \n\n'
+ 'This program '
+ 'is distributed in the hope that it will be useful, but WITHOUT '
+ 'ANY WARRANTY; without even the implied warranty of '
+ 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU '
+ 'General Public License for more details. \n\n'
+ 'You should have received '
+ 'a copy of the GNU General Public License along with this program; '
+ 'if not, see <http://www.gnu.org/licenses>. \n\n'
+ 'In addition, as a '
+ 'special exception, the copyright holders give permission to link '
+ 'the code of portions of this program with the OpenSSL library. '
+ 'You must obey the GNU General Public License in all respects for '
+ 'all of the code used other than OpenSSL. \n\n'
+ 'If you modify file(s) '
+ 'with this exception, you may extend this exception to your '
+ '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.'
))
- self.about.set_website("http://deluge-torrent.org")
- self.about.set_website_label("deluge-torrent.org")
+ self.about.set_website('http://deluge-torrent.org')
+ self.about.set_website_label('deluge-torrent.org')
self.about.set_icon(get_deluge_icon())
- self.about.set_logo(gtk.gdk.pixbuf_new_from_file(get_pixmap("deluge-about.png")))
+ self.about.set_logo(gtk.gdk.pixbuf_new_from_file(get_pixmap('deluge-about.png')))
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()
- c = c.replace("%ltversion%", result)
+ c = c.replace('%ltversion%', result)
self.about.set_comments(c)
def on_info(result):
c = self.about.get_comments()
- c = c.replace("%coreversion%", result)
+ c = c.replace('%coreversion%', result)
self.about.set_comments(c)
client.core.get_libtorrent_version().addCallback(on_lt_version)
diff --git a/deluge/ui/gtkui/addtorrentdialog.py b/deluge/ui/gtkui/addtorrentdialog.py
index 6b7f60efa..8227fa913 100644
--- a/deluge/ui/gtkui/addtorrentdialog.py
+++ b/deluge/ui/gtkui/addtorrentdialog.py
@@ -36,36 +36,36 @@ log = logging.getLogger(__name__)
class AddTorrentDialog(component.Component):
def __init__(self):
- component.Component.__init__(self, "AddTorrentDialog")
+ component.Component.__init__(self, 'AddTorrentDialog')
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")
+ self.dialog = self.builder.get_object('dialog_add_torrent')
- self.dialog.connect("delete-event", self._on_delete_event)
+ self.dialog.connect('delete-event', self._on_delete_event)
self.builder.connect_signals({
- "on_button_file_clicked": self._on_button_file_clicked,
- "on_button_url_clicked": self._on_button_url_clicked,
- "on_button_hash_clicked": self._on_button_hash_clicked,
- "on_button_remove_clicked": self._on_button_remove_clicked,
- "on_button_trackers_clicked": self._on_button_trackers_clicked,
- "on_button_cancel_clicked": self._on_button_cancel_clicked,
- "on_button_add_clicked": self._on_button_add_clicked,
- "on_button_apply_clicked": self._on_button_apply_clicked,
- "on_button_revert_clicked": self._on_button_revert_clicked,
- "on_chk_move_completed_toggled": self._on_chk_move_completed_toggled
+ 'on_button_file_clicked': self._on_button_file_clicked,
+ 'on_button_url_clicked': self._on_button_url_clicked,
+ 'on_button_hash_clicked': self._on_button_hash_clicked,
+ 'on_button_remove_clicked': self._on_button_remove_clicked,
+ 'on_button_trackers_clicked': self._on_button_trackers_clicked,
+ 'on_button_cancel_clicked': self._on_button_cancel_clicked,
+ 'on_button_add_clicked': self._on_button_add_clicked,
+ 'on_button_apply_clicked': self._on_button_apply_clicked,
+ 'on_button_revert_clicked': self._on_button_revert_clicked,
+ 'on_chk_move_completed_toggled': self._on_chk_move_completed_toggled
})
# download?, path, filesize, sequence number, inconsistent?
@@ -81,34 +81,34 @@ class AddTorrentDialog(component.Component):
self.previous_selected_torrent = None
- self.listview_torrents = self.builder.get_object("listview_torrents")
- self.listview_files = self.builder.get_object("listview_files")
+ self.listview_torrents = self.builder.get_object('listview_torrents')
+ self.listview_files = self.builder.get_object('listview_files')
render = gtk.CellRendererText()
render.connect('edited', self._on_torrent_name_edit)
render.set_property('editable', True)
- column = gtk.TreeViewColumn(_("Torrent"), render, text=1)
+ column = gtk.TreeViewColumn(_('Torrent'), render, text=1)
self.listview_torrents.append_column(column)
render = gtk.CellRendererToggle()
- render.connect("toggled", self._on_file_toggled)
+ render.connect('toggled', self._on_file_toggled)
column = gtk.TreeViewColumn(None, render, active=0, inconsistent=4)
self.listview_files.append_column(column)
- column = gtk.TreeViewColumn(_("Filename"))
+ column = gtk.TreeViewColumn(_('Filename'))
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
- column.add_attribute(render, "stock-id", 5)
+ column.add_attribute(render, 'stock-id', 5)
render = gtk.CellRendererText()
- render.set_property("editable", True)
- render.connect("edited", self._on_filename_edited)
+ render.set_property('editable', True)
+ render.connect('edited', self._on_filename_edited)
column.pack_start(render, True)
- column.add_attribute(render, "text", 1)
+ column.add_attribute(render, 'text', 1)
column.set_expand(True)
self.listview_files.append_column(column)
render = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Size"))
+ column = gtk.TreeViewColumn(_('Size'))
column.pack_start(render)
column.set_cell_data_func(render, cell_data_size, 2)
self.listview_files.append_column(column)
@@ -119,29 +119,29 @@ class AddTorrentDialog(component.Component):
self.listview_files.set_model(self.files_treestore)
self.listview_files.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
- self.listview_torrents.get_selection().connect("changed", self._on_torrent_changed)
+ self.listview_torrents.get_selection().connect('changed', self._on_torrent_changed)
self.setup_move_completed_path_chooser()
self.setup_download_location_path_chooser()
# Get default config values from the core
self.core_keys = [
- "pre_allocate_storage",
- "max_connections_per_torrent",
- "max_upload_slots_per_torrent",
- "max_upload_speed_per_torrent",
- "max_download_speed_per_torrent",
- "prioritize_first_last_pieces",
- "sequential_download",
- "add_paused",
- "download_location",
- "download_location_paths_list",
- "move_completed",
- "move_completed_path",
- "move_completed_paths_list",
+ 'pre_allocate_storage',
+ 'max_connections_per_torrent',
+ 'max_upload_slots_per_torrent',
+ 'max_upload_speed_per_torrent',
+ 'max_download_speed_per_torrent',
+ 'prioritize_first_last_pieces',
+ 'sequential_download',
+ 'add_paused',
+ 'download_location',
+ 'download_location_paths_list',
+ 'move_completed',
+ 'move_completed_path',
+ 'move_completed_paths_list',
]
# self.core_keys += self.move_completed_path_chooser.get_config_keys()
- self.builder.get_object("notebook1").connect("switch-page", self._on_switch_page)
+ self.builder.get_object('notebook1').connect('switch-page', self._on_switch_page)
def start(self):
self.update_core_config()
@@ -150,8 +150,8 @@ class AddTorrentDialog(component.Component):
return self.update_core_config(True, focus)
def _show(self, focus=False):
- if component.get("MainWindow").is_on_active_workspace():
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ if component.get('MainWindow').is_on_active_workspace():
+ self.dialog.set_transient_for(component.get('MainWindow').window)
else:
self.dialog.set_transient_for(None)
@@ -169,7 +169,7 @@ class AddTorrentDialog(component.Component):
self.previous_selected_torrent = None
self.torrent_liststore.clear()
self.files_treestore.clear()
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ self.dialog.set_transient_for(component.get('MainWindow').window)
return None
def update_core_config(self, show=False, focus=False):
@@ -192,8 +192,8 @@ class AddTorrentDialog(component.Component):
try:
info = TorrentInfo(filename)
except Exception as ex:
- log.debug("Unable to open torrent file: %s", ex)
- ErrorDialog(_("Invalid File"), ex, self.dialog).run()
+ log.debug('Unable to open torrent file: %s', ex)
+ ErrorDialog(_('Invalid File'), ex, self.dialog).run()
continue
if info.info_hash in self.files:
@@ -212,13 +212,13 @@ class AddTorrentDialog(component.Component):
if not row and new_row:
self.listview_torrents.get_selection().select_iter(new_row)
- self.dialog.set_title(_("Add Torrents (%d)") % len(self.torrent_liststore))
+ self.dialog.set_title(_('Add Torrents (%d)') % len(self.torrent_liststore))
if already_added:
- log.debug("Tried to add %d duplicate torrents!", already_added)
+ log.debug('Tried to add %d duplicate torrents!', already_added)
ErrorDialog(
- _("Duplicate Torrent(s)"),
- _("You cannot add the same torrent twice. %d torrents were already added." % already_added),
+ _('Duplicate Torrent(s)'),
+ _('You cannot add the same torrent twice. %d torrents were already added.' % already_added),
self.dialog
).run()
@@ -228,14 +228,14 @@ class AddTorrentDialog(component.Component):
for uri in uris:
magnet = deluge.common.get_magnet_info(uri)
if not magnet:
- log.error("Invalid magnet: %s", uri)
+ log.error('Invalid magnet: %s', uri)
continue
- if magnet["info_hash"] in self.infos:
- log.info("Torrent already in Add Dialog list: %s", uri)
+ if magnet['info_hash'] in self.infos:
+ log.info('Torrent already in Add Dialog list: %s', uri)
continue
- new_row = self.torrent_liststore.append([magnet["info_hash"], magnet["name"], xml_escape(uri)])
- self.files[magnet["info_hash"]] = magnet["files_tree"]
- self.infos[magnet["info_hash"]] = None
+ new_row = self.torrent_liststore.append([magnet['info_hash'], magnet['name'], xml_escape(uri)])
+ self.files[magnet['info_hash']] = magnet['files_tree']
+ self.infos[magnet['info_hash']] = None
self.listview_torrents.get_selection().select_iter(new_row)
self.set_default_options()
self.save_torrent_options(new_row)
@@ -284,10 +284,10 @@ 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("0", False)
+ self.listview_files.expand_row('0', False)
def prepare_file(self, _file, file_name, file_num, download, files_storage):
first_slash_index = file_name.find(os.path.sep)
@@ -311,10 +311,10 @@ class AddTorrentDialog(component.Component):
ret += chunk_size
else:
self.files_treestore.append(parent_iter, [
- value[2], key, value[1]["size"],
+ value[2], key, value[1]['size'],
value[0], False, gtk.STOCK_FILE
])
- ret += value[1]["size"]
+ 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
# folder, download true, download false or inconsistent.
@@ -338,21 +338,21 @@ 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"],
+ 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"],
+ 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"])
+ self.builder.get_object('chk_move_completed').set_active(self.core_config['move_completed'])
def setup_move_completed_path_chooser(self):
- self.move_completed_hbox = self.builder.get_object("hbox_move_completed_chooser")
- self.move_completed_path_chooser = PathChooser("move_completed_paths_list")
+ self.move_completed_hbox = self.builder.get_object('hbox_move_completed_chooser')
+ self.move_completed_path_chooser = PathChooser('move_completed_paths_list')
self.move_completed_hbox.add(self.move_completed_path_chooser)
self.move_completed_hbox.show_all()
def setup_download_location_path_chooser(self):
- self.download_location_hbox = self.builder.get_object("hbox_download_location_chooser")
- self.download_location_path_chooser = PathChooser("download_location_paths_list")
+ self.download_location_hbox = self.builder.get_object('hbox_download_location_chooser')
+ self.download_location_path_chooser = PathChooser('download_location_paths_list')
self.download_location_hbox.add(self.download_location_path_chooser)
self.download_location_hbox.show_all()
@@ -363,27 +363,27 @@ class AddTorrentDialog(component.Component):
options = self.options[torrent_id]
- self.download_location_path_chooser.set_text(options["download_location"], cursor_end=True)
- 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"])
- self.builder.get_object("spin_maxup").set_value(
- options["max_upload_speed"])
- self.builder.get_object("spin_maxconnections").set_value(
- options["max_connections"])
- self.builder.get_object("spin_maxupslots").set_value(
- options["max_upload_slots"])
- self.builder.get_object("chk_paused").set_active(
- options["add_paused"])
- self.builder.get_object("chk_pre_alloc").set_active(
- options["pre_allocate_storage"])
- self.builder.get_object("chk_prioritize").set_active(
- options["prioritize_first_last_pieces"])
- self.builder.get_object("chk_sequential_download").set_active(
- options["sequential_download"])
- self.builder.get_object("chk_move_completed").set_active(
- options["move_completed"])
+ self.download_location_path_chooser.set_text(options['download_location'], cursor_end=True)
+ 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'])
+ self.builder.get_object('spin_maxup').set_value(
+ options['max_upload_speed'])
+ self.builder.get_object('spin_maxconnections').set_value(
+ options['max_connections'])
+ self.builder.get_object('spin_maxupslots').set_value(
+ options['max_upload_slots'])
+ self.builder.get_object('chk_paused').set_active(
+ options['add_paused'])
+ self.builder.get_object('chk_pre_alloc').set_active(
+ options['pre_allocate_storage'])
+ self.builder.get_object('chk_prioritize').set_active(
+ options['prioritize_first_last_pieces'])
+ self.builder.get_object('chk_sequential_download').set_active(
+ options['sequential_download'])
+ self.builder.get_object('chk_move_completed').set_active(
+ options['move_completed'])
def save_torrent_options(self, row=None):
# Keeps the torrent options dictionary up-to-date with what the user has
@@ -402,20 +402,20 @@ class AddTorrentDialog(component.Component):
else:
options = {}
- options["download_location"] = self.download_location_path_chooser.get_text()
- options["move_completed_path"] = self.move_completed_path_chooser.get_text()
- options["pre_allocate_storage"] = self.builder.get_object("chk_pre_alloc").get_active()
- options["move_completed"] = self.builder.get_object("chk_move_completed").get_active()
- options["max_download_speed"] = self.builder.get_object("spin_maxdown").get_value()
- options["max_upload_speed"] = self.builder.get_object("spin_maxup").get_value()
- options["max_connections"] = self.builder.get_object("spin_maxconnections").get_value_as_int()
- options["max_upload_slots"] = self.builder.get_object("spin_maxupslots").get_value_as_int()
- 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
- options["move_completed"] = self.builder.get_object("chk_move_completed").get_active()
- options["seed_mode"] = self.builder.get_object("chk_seed_mode").get_active()
+ options['download_location'] = self.download_location_path_chooser.get_text()
+ options['move_completed_path'] = self.move_completed_path_chooser.get_text()
+ options['pre_allocate_storage'] = self.builder.get_object('chk_pre_alloc').get_active()
+ options['move_completed'] = self.builder.get_object('chk_move_completed').get_active()
+ options['max_download_speed'] = self.builder.get_object('spin_maxdown').get_value()
+ options['max_upload_speed'] = self.builder.get_object('spin_maxup').get_value()
+ options['max_connections'] = self.builder.get_object('spin_maxconnections').get_value_as_int()
+ options['max_upload_slots'] = self.builder.get_object('spin_maxupslots').get_value_as_int()
+ 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
+ options['move_completed'] = self.builder.get_object('chk_move_completed').get_active()
+ options['seed_mode'] = self.builder.get_object('chk_seed_mode').get_active()
self.options[torrent_id] = options
@@ -426,7 +426,7 @@ class AddTorrentDialog(component.Component):
if len(files_priorities) > 0:
for i, file_dict in enumerate(self.files[torrent_id]):
- file_dict["download"] = files_priorities[i]
+ file_dict['download'] = files_priorities[i]
def build_priorities(self, _iter, priorities):
while _iter is not None:
@@ -445,32 +445,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.builder.get_object("spin_maxdown").set_value(
- 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.builder.get_object("spin_maxconnections").set_value(
- self.core_config["max_connections_per_torrent"])
- self.builder.get_object("spin_maxupslots").set_value(
- self.core_config["max_upload_slots_per_torrent"])
- self.builder.get_object("chk_paused").set_active(
- self.core_config["add_paused"])
- self.builder.get_object("chk_prioritize").set_active(
- self.core_config["prioritize_first_last_pieces"])
- self.builder.get_object("chk_sequential_download").set_active(
- self.core_config["sequential_download"])
- self.builder.get_object("chk_move_completed").set_active(
- self.core_config["move_completed"])
- self.builder.get_object("chk_seed_mode").set_active(False)
+ self.builder.get_object('chk_pre_alloc').set_active(
+ self.core_config['pre_allocate_storage'])
+ self.builder.get_object('spin_maxdown').set_value(
+ 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.builder.get_object('spin_maxconnections').set_value(
+ self.core_config['max_connections_per_torrent'])
+ self.builder.get_object('spin_maxupslots').set_value(
+ self.core_config['max_upload_slots_per_torrent'])
+ self.builder.get_object('chk_paused').set_active(
+ self.core_config['add_paused'])
+ self.builder.get_object('chk_prioritize').set_active(
+ self.core_config['prioritize_first_last_pieces'])
+ self.builder.get_object('chk_sequential_download').set_active(
+ self.core_config['sequential_download'])
+ self.builder.get_object('chk_move_completed').set_active(
+ self.core_config['move_completed'])
+ self.builder.get_object('chk_seed_mode').set_active(False)
def get_file_priorities(self, torrent_id):
# A list of priorities
files_list = []
for file_dict in self.files[torrent_id]:
- if not file_dict["download"]:
+ if not file_dict['download']:
files_list.append(0)
else:
files_list.append(1)
@@ -520,10 +520,10 @@ class AddTorrentDialog(component.Component):
return this_level_toggle
def _on_button_file_clicked(self, widget):
- log.debug("_on_button_file_clicked")
+ log.debug('_on_button_file_clicked')
# Setup the filechooserdialog
chooser = gtk.FileChooserDialog(
- _("Choose a .torrent file"),
+ _('Choose a .torrent file'),
None,
gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
@@ -532,30 +532,30 @@ class AddTorrentDialog(component.Component):
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(True)
- chooser.set_property("skip-taskbar-hint", True)
+ chooser.set_property('skip-taskbar-hint', True)
chooser.set_local_only(False)
# Add .torrent and * file filters
file_filter = gtk.FileFilter()
- file_filter.set_name(_("Torrent files"))
- file_filter.add_pattern("*." + "torrent")
+ file_filter.set_name(_('Torrent files'))
+ file_filter.add_pattern('*.' + 'torrent')
chooser.add_filter(file_filter)
file_filter = gtk.FileFilter()
- file_filter.set_name(_("All files"))
- file_filter.add_pattern("*")
+ file_filter.set_name(_('All files'))
+ file_filter.add_pattern('*')
chooser.add_filter(file_filter)
# Load the 'default_load_path' from the config
- self.config = ConfigManager("gtkui.conf")
- if self.config["default_load_path"] is not None:
- chooser.set_current_folder(self.config["default_load_path"])
+ self.config = ConfigManager('gtkui.conf')
+ if self.config['default_load_path'] is not None:
+ chooser.set_current_folder(self.config['default_load_path'])
# Run the dialog
response = chooser.run()
if response == gtk.RESPONSE_OK:
result = chooser.get_filenames()
- self.config["default_load_path"] = chooser.get_current_folder()
+ self.config['default_load_path'] = chooser.get_current_folder()
else:
chooser.destroy()
return
@@ -564,9 +564,9 @@ class AddTorrentDialog(component.Component):
self.add_from_files(result)
def _on_button_url_clicked(self, widget):
- log.debug("_on_button_url_clicked")
- dialog = self.builder.get_object("url_dialog")
- entry = self.builder.get_object("entry_url")
+ log.debug('_on_button_url_clicked')
+ dialog = self.builder.get_object('url_dialog')
+ entry = self.builder.get_object('entry_url')
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_transient_for(self.dialog)
@@ -583,16 +583,16 @@ class AddTorrentDialog(component.Component):
response = dialog.run()
if response == gtk.RESPONSE_OK:
- url = entry.get_text().decode("utf-8")
+ url = entry.get_text().decode('utf-8')
else:
url = None
- entry.set_text("")
+ entry.set_text('')
dialog.hide()
# This is where we need to fetch the .torrent file from the URL and
# add it to the list.
- log.debug("url: %s", url)
+ log.debug('url: %s', url)
if url:
if deluge.common.is_url(url):
self.add_from_url(url)
@@ -600,14 +600,14 @@ class AddTorrentDialog(component.Component):
self.add_from_magnets([url])
else:
ErrorDialog(
- _("Invalid URL"),
- "%s %s" % (url, _("is not a valid URL.")),
+ _('Invalid URL'),
+ '%s %s' % (url, _('is not a valid URL.')),
self.dialog
).run()
def add_from_url(self, url):
dialog = gtk.Dialog(
- _("Downloading..."),
+ _('Downloading...'),
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
parent=self.dialog)
dialog.set_transient_for(self.dialog)
@@ -624,23 +624,23 @@ class AddTorrentDialog(component.Component):
if total_length:
percent = current_length / total_length
pb.set_fraction(percent)
- pb.set_text("%.2f%% (%s / %s)" % (
+ pb.set_text('%.2f%% (%s / %s)' % (
percent * 100,
deluge.common.fsize(current_length),
deluge.common.fsize(total_length)))
else:
pb.pulse()
- pb.set_text("%s" % deluge.common.fsize(current_length))
+ pb.set_text('%s' % deluge.common.fsize(current_length))
def on_download_success(result):
self.add_from_files([result])
dialog.destroy()
def on_download_fail(result):
- log.debug("Download failed: %s", result)
+ log.debug('Download failed: %s', result)
dialog.destroy()
ErrorDialog(
- _("Download Failed"), "%s %s" % (_("Failed to download:"), url),
+ _('Download Failed'), '%s %s' % (_('Failed to download:'), url),
details=result.getErrorMessage(), parent=self.dialog
).run()
return result
@@ -650,10 +650,10 @@ class AddTorrentDialog(component.Component):
d.addCallbacks(on_download_success, on_download_fail)
def _on_button_hash_clicked(self, widget):
- log.debug("_on_button_hash_clicked")
- dialog = self.builder.get_object("dialog_infohash")
- entry = self.builder.get_object("entry_hash")
- textview = self.builder.get_object("text_trackers")
+ log.debug('_on_button_hash_clicked')
+ dialog = self.builder.get_object('dialog_infohash')
+ entry = self.builder.get_object('entry_hash')
+ textview = self.builder.get_object('text_trackers')
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.set_transient_for(self.dialog)
@@ -670,24 +670,24 @@ class AddTorrentDialog(component.Component):
if response == gtk.RESPONSE_OK and deluge.common.is_infohash(infohash):
trackers = []
b = textview.get_buffer()
- lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n")
- log.debug("lines: %s", lines)
+ lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n')
+ log.debug('lines: %s', lines)
for l in lines:
if deluge.common.is_url(l):
trackers.append(l)
# Convert the information to a magnet uri, this is just easier to
# handle this way.
- log.debug("trackers: %s", trackers)
+ log.debug('trackers: %s', trackers)
magnet = deluge.common.create_magnet_uri(infohash, infohash, trackers)
- log.debug("magnet uri: %s", magnet)
+ log.debug('magnet uri: %s', magnet)
self.add_from_magnets([magnet])
- entry.set_text("")
- textview.get_buffer().set_text("")
+ entry.set_text('')
+ textview.get_buffer().set_text('')
dialog.hide()
def _on_button_remove_clicked(self, widget):
- log.debug("_on_button_remove_clicked")
+ log.debug('_on_button_remove_clicked')
(model, row) = self.listview_torrents.get_selection().get_selected()
if row is None:
return
@@ -699,14 +699,14 @@ class AddTorrentDialog(component.Component):
del self.infos[torrent_id]
def _on_button_trackers_clicked(self, widget):
- log.debug("_on_button_trackers_clicked")
+ log.debug('_on_button_trackers_clicked')
def _on_button_cancel_clicked(self, widget):
- log.debug("_on_button_cancel_clicked")
+ log.debug('_on_button_cancel_clicked')
self.hide()
def _on_button_add_clicked(self, widget):
- log.debug("_on_button_add_clicked")
+ log.debug('_on_button_add_clicked')
self.add_torrents()
self.hide()
@@ -728,10 +728,10 @@ class AddTorrentDialog(component.Component):
file_priorities = self.get_file_priorities(torrent_id)
if options is not None:
- options["file_priorities"] = file_priorities
+ options['file_priorities'] = file_priorities
if deluge.common.is_magnet(filename):
- del options["file_priorities"]
+ del options['file_priorities']
client.core.add_torrent_magnet(filename, options)
else:
torrents_to_add.append((os.path.split(filename)[-1],
@@ -741,15 +741,15 @@ class AddTorrentDialog(component.Component):
def on_torrents_added(errors):
if errors:
- log.info("Failed to add %d out of %d torrents.", len(errors), len(torrents_to_add))
+ log.info('Failed to add %d out of %d torrents.', len(errors), len(torrents_to_add))
for e in errors:
- log.info("Torrent add failed: %s", e)
+ log.info('Torrent add failed: %s', e)
else:
- log.info("Successfully added %d torrents.", len(torrents_to_add))
+ log.info('Successfully added %d torrents.', len(torrents_to_add))
client.core.add_torrent_files(torrents_to_add).addCallback(on_torrents_added)
def _on_button_apply_clicked(self, widget):
- log.debug("_on_button_apply_clicked")
+ log.debug('_on_button_apply_clicked')
(model, row) = self.listview_torrents.get_selection().get_selected()
if row is None:
return
@@ -758,7 +758,7 @@ class AddTorrentDialog(component.Component):
# The options, except file renames, we want all the torrents to have
options = self.options[model.get_value(row, 0)].copy()
- options.pop("mapped_files", None)
+ options.pop('mapped_files', None)
# Set all the torrent options
row = model.get_iter_first()
@@ -768,7 +768,7 @@ class AddTorrentDialog(component.Component):
row = model.iter_next(row)
def _on_button_revert_clicked(self, widget):
- log.debug("_on_button_revert_clicked")
+ log.debug('_on_button_revert_clicked')
(model, row) = self.listview_torrents.get_selection().get_selected()
if row is None:
return
@@ -784,7 +784,7 @@ class AddTorrentDialog(component.Component):
self.hide()
return True
- def get_file_path(self, row, path=""):
+ def get_file_path(self, row, path=''):
if not row:
return path
@@ -807,8 +807,8 @@ class AddTorrentDialog(component.Component):
(model, row) = self.listview_torrents.get_selection().get_selected()
torrent_id = model[row][0]
- if "mapped_files" not in self.options[torrent_id]:
- self.options[torrent_id]["mapped_files"] = {}
+ if 'mapped_files' not in self.options[torrent_id]:
+ self.options[torrent_id]['mapped_files'] = {}
if index > -1:
# We're renaming a file! Yay! That's easy!
@@ -838,7 +838,7 @@ class AddTorrentDialog(component.Component):
# file path.
# We'll send this to the core when adding the torrent so it knows
# what to rename before adding.
- self.options[torrent_id]["mapped_files"][index] = file_path
+ self.options[torrent_id]['mapped_files'][index] = file_path
self.files[torrent_id][index]['path'] = file_path
else:
# Folder!
@@ -865,7 +865,7 @@ class AddTorrentDialog(component.Component):
file_path = file_path_base + self.files_treestore[row][1]
# Update the file path in the mapped_files dict
- self.options[torrent_id]["mapped_files"][index] = file_path
+ self.options[torrent_id]['mapped_files'][index] = file_path
self.files[torrent_id][index]['path'] = file_path
# Get the next siblings iter
@@ -895,7 +895,7 @@ class AddTorrentDialog(component.Component):
# We need to re-expand the view because it might contracted
# if we change the root iter
- self.listview_files.expand_row("0", False)
+ self.listview_files.expand_row('0', False)
else:
# This was a simple folder rename without any splits, so just
# change the path for itr
diff --git a/deluge/ui/gtkui/common.py b/deluge/ui/gtkui/common.py
index 39637c332..152a06c3e 100644
--- a/deluge/ui/gtkui/common.py
+++ b/deluge/ui/gtkui/common.py
@@ -36,9 +36,9 @@ def get_logo(size):
Returns:
gtk.gdk.Pixbuf: deluge logo
"""
- filename = "deluge.svg"
+ filename = 'deluge.svg'
if deluge.common.windows_check() or deluge.common.osx_check():
- filename = "deluge.png"
+ filename = 'deluge.png'
try:
return gtk.gdk.pixbuf_new_from_file_at_size(deluge.common.get_pixmap(filename), size, size)
except GError as ex:
@@ -46,7 +46,7 @@ def get_logo(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):
+ 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:
@@ -74,29 +74,29 @@ def build_menu_radio_list(value_list, callback, pref_value=None, suffix=None, sh
for value in sorted(value_list):
item_text = str(value)
if suffix:
- item_text += " " + suffix
+ item_text += ' ' + suffix
menuitem = gtk.RadioMenuItem(group, item_text)
group = menuitem
if pref_value and value == pref_value:
menuitem.set_active(True)
if callback:
- menuitem.connect("toggled", callback)
+ menuitem.connect('toggled', callback)
menu.append(menuitem)
if show_notset:
menuitem = gtk.RadioMenuItem(group, notset_label)
- menuitem.set_name("unlimited")
+ menuitem.set_name('unlimited')
if pref_value and pref_value < notset_lessthan:
menuitem.set_active(True)
- menuitem.connect("toggled", callback)
+ menuitem.connect('toggled', callback)
menu.append(menuitem)
if show_other:
menuitem = gtk.SeparatorMenuItem()
menu.append(menuitem)
- menuitem = gtk.MenuItem(_("Other..."))
- menuitem.set_name("other")
- menuitem.connect("activate", callback)
+ menuitem = gtk.MenuItem(_('Other...'))
+ menuitem.set_name('other')
+ menuitem.connect('activate', callback)
menu.append(menuitem)
return menu
@@ -144,7 +144,7 @@ def get_deluge_icon():
else:
try:
icon_theme = gtk.icon_theme_get_default()
- return icon_theme.load_icon("deluge", 64, 0)
+ return icon_theme.load_icon('deluge', 64, 0)
except GError:
return get_logo(64)
@@ -164,25 +164,25 @@ def associate_magnet_links(overwrite=False):
import _winreg
try:
- hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, "Magnet")
+ hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, 'Magnet')
except WindowsError: # pylint: disable=undefined-variable
overwrite = True
else:
_winreg.CloseKey(hkey)
if overwrite:
- deluge_exe = os.path.join(os.path.dirname(sys.executable), "deluge.exe")
+ deluge_exe = os.path.join(os.path.dirname(sys.executable), 'deluge.exe')
try:
- magnet_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Magnet")
+ magnet_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, 'Magnet')
except WindowsError: # pylint: disable=undefined-variable
# Could not create for all users, falling back to current user
- magnet_key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Classes\\Magnet")
+ magnet_key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, 'Software\\Classes\\Magnet')
- _winreg.SetValue(magnet_key, "", _winreg.REG_SZ, "URL:Magnet Protocol")
- _winreg.SetValueEx(magnet_key, "URL Protocol", 0, _winreg.REG_SZ, "")
- _winreg.SetValueEx(magnet_key, "BrowserFlags", 0, _winreg.REG_DWORD, 0x8)
- _winreg.SetValue(magnet_key, "DefaultIcon", _winreg.REG_SZ, "{},0".format(deluge_exe))
- _winreg.SetValue(magnet_key, r"shell\open\command", _winreg.REG_SZ, '"{}" "%1"'.format(deluge_exe))
+ _winreg.SetValue(magnet_key, '', _winreg.REG_SZ, 'URL:Magnet Protocol')
+ _winreg.SetValueEx(magnet_key, 'URL Protocol', 0, _winreg.REG_SZ, '')
+ _winreg.SetValueEx(magnet_key, 'BrowserFlags', 0, _winreg.REG_DWORD, 0x8)
+ _winreg.SetValue(magnet_key, 'DefaultIcon', _winreg.REG_SZ, '{},0'.format(deluge_exe))
+ _winreg.SetValue(magnet_key, r'shell\open\command', _winreg.REG_SZ, '"{}" "%1"'.format(deluge_exe))
_winreg.CloseKey(magnet_key)
# Don't try associate magnet on OSX see: #2420
@@ -191,20 +191,20 @@ def associate_magnet_links(overwrite=False):
try:
import gconf
except ImportError:
- log.debug("gconf not available, so will not attempt to register magnet uri handler")
+ log.debug('gconf not available, so will not attempt to register magnet uri handler')
return False
else:
- key = "/desktop/gnome/url-handlers/magnet/command"
+ key = '/desktop/gnome/url-handlers/magnet/command'
gconf_client = gconf.client_get_default()
if (gconf_client.get(key) and overwrite) or not gconf_client.get(key):
# We are either going to overwrite the key, or do it if it hasn't been set yet
if gconf_client.set_string(key, "deluge '%s'"):
- gconf_client.set_bool("/desktop/gnome/url-handlers/magnet/needs_terminal", False)
- gconf_client.set_bool("/desktop/gnome/url-handlers/magnet/enabled", True)
- log.info("Deluge registered as default magnet uri handler!")
+ gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/needs_terminal', False)
+ gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True)
+ log.info('Deluge registered as default magnet uri handler!')
return True
else:
- log.error("Unable to register Deluge as default magnet uri handler.")
+ log.error('Unable to register Deluge as default magnet uri handler.')
return False
return False
@@ -217,29 +217,29 @@ def save_pickled_state_file(filename, state):
state (state): The data to be pickled and written to file
"""
from deluge.configmanager import get_config_dir
- filepath = os.path.join(get_config_dir(), "gtkui_state", filename)
- filepath_bak = filepath + ".bak"
- filepath_tmp = filepath + ".tmp"
+ filepath = os.path.join(get_config_dir(), 'gtkui_state', filename)
+ filepath_bak = filepath + '.bak'
+ filepath_tmp = filepath + '.tmp'
try:
if os.path.isfile(filepath):
- log.debug("Creating backup of %s at: %s", filename, filepath_bak)
+ log.debug('Creating backup of %s at: %s', filename, filepath_bak)
shutil.copy2(filepath, filepath_bak)
except IOError as ex:
- log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex)
+ log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex)
else:
- log.info("Saving the %s at: %s", filename, filepath)
+ log.info('Saving the %s at: %s', filename, filepath)
try:
- with open(filepath_tmp, "wb") as _file:
+ with open(filepath_tmp, 'wb') as _file:
# Pickle the state object
cPickle.dump(state, _file)
_file.flush()
os.fsync(_file.fileno())
shutil.move(filepath_tmp, filepath)
except (IOError, EOFError, cPickle.PicklingError) as ex:
- log.error("Unable to save %s: %s", filename, ex)
+ log.error('Unable to save %s: %s', filename, ex)
if os.path.isfile(filepath_bak):
- log.info("Restoring backup of %s from: %s", filename, filepath_bak)
+ log.info('Restoring backup of %s from: %s', filename, filepath_bak)
shutil.move(filepath_bak, filepath)
@@ -253,19 +253,19 @@ def load_pickled_state_file(filename):
state: the unpickled state
"""
from deluge.configmanager import get_config_dir
- filepath = os.path.join(get_config_dir(), "gtkui_state", filename)
- filepath_bak = filepath + ".bak"
+ filepath = os.path.join(get_config_dir(), 'gtkui_state', filename)
+ filepath_bak = filepath + '.bak'
old_data_filepath = os.path.join(get_config_dir(), filename)
for _filepath in (filepath, filepath_bak, old_data_filepath):
- log.info("Opening %s for load: %s", filename, _filepath)
+ log.info('Opening %s for load: %s', filename, _filepath)
try:
- with open(_filepath, "rb") as _file:
+ with open(_filepath, 'rb') as _file:
state = cPickle.load(_file)
except (IOError, cPickle.UnpicklingError) as ex:
- log.warning("Unable to load %s: %s", _filepath, ex)
+ log.warning('Unable to load %s: %s', _filepath, ex)
else:
- log.info("Successfully loaded %s: %s", filename, _filepath)
+ log.info('Successfully loaded %s: %s', filename, _filepath)
return state
diff --git a/deluge/ui/gtkui/connectionmanager.py b/deluge/ui/gtkui/connectionmanager.py
index 383336141..89c08ceca 100644
--- a/deluge/ui/gtkui/connectionmanager.py
+++ b/deluge/ui/gtkui/connectionmanager.py
@@ -27,7 +27,7 @@ from deluge.ui.gtkui.dialogs import AuthenticationDialog, ErrorDialog
log = logging.getLogger(__name__)
-DEFAULT_HOST = "127.0.0.1"
+DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 58846
HOSTLIST_COL_ID = 0
@@ -44,17 +44,17 @@ HOSTLIST_PIXBUFS = [
]
HOSTLIST_STATUS = [
- "Offline",
- "Online",
- "Connected"
+ 'Offline',
+ 'Online',
+ 'Connected'
]
def cell_render_host(column, cell, model, row, data):
host, port, username = model.get(row, *data)
- text = host + ":" + str(port)
+ text = host + ':' + str(port)
if username:
- text = username + "@" + text
+ text = username + '@' + text
cell.set_property('text', text)
@@ -64,13 +64,13 @@ def cell_render_status(column, cell, model, row, data):
if status in HOSTLIST_STATUS:
pixbuf = HOSTLIST_PIXBUFS[HOSTLIST_STATUS.index(status)]
- cell.set_property("pixbuf", pixbuf)
+ cell.set_property('pixbuf', pixbuf)
class ConnectionManager(component.Component):
def __init__(self):
- component.Component.__init__(self, "ConnectionManager")
- self.gtkui_config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'ConnectionManager')
+ self.gtkui_config = ConfigManager('gtkui.conf')
self.config = self.__load_config()
self.running = False
@@ -87,14 +87,14 @@ class ConnectionManager(component.Component):
pass
def __load_config(self):
- auth_file = get_config_dir("auth")
+ auth_file = get_config_dir('auth')
if not os.path.exists(auth_file):
from deluge.common import create_localclient_account
create_localclient_account()
localclient_username, localclient_password = get_localhost_auth()
default_config = {
- "hosts": [(
+ 'hosts': [(
hashlib.sha1(str(time.time())).hexdigest(),
DEFAULT_HOST,
DEFAULT_PORT,
@@ -102,7 +102,7 @@ class ConnectionManager(component.Component):
localclient_password
)]
}
- config = ConfigManager("hostlist.conf.1.2", defaults=default_config, file_version=2)
+ config = ConfigManager('hostlist.conf.1.2', defaults=default_config, file_version=2)
config.run_converter((0, 1), 2, self.__migrate_config_1_to_2)
return config
@@ -116,32 +116,32 @@ class ConnectionManager(component.Component):
self.builder = gtk.Builder()
# The main dialog
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')
))
# The add host dialog
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')
))
# The ask password dialog
self.builder.add_from_file(resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "connection_manager.askpassword.ui")
+ 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.askpassword.ui')
))
- self.window = component.get("MainWindow")
+ self.window = component.get('MainWindow')
# Setup the ConnectionManager dialog
- self.connection_manager = self.builder.get_object("connection_manager")
+ self.connection_manager = self.builder.get_object('connection_manager')
self.connection_manager.set_transient_for(self.window.window)
self.connection_manager.set_icon(get_deluge_icon())
- self.builder.get_object("image1").set_from_pixbuf(get_logo(32))
+ self.builder.get_object('image1').set_from_pixbuf(get_logo(32))
- self.askpassword_dialog = self.builder.get_object("askpassword_dialog")
+ self.askpassword_dialog = self.builder.get_object('askpassword_dialog')
self.askpassword_dialog.set_transient_for(self.connection_manager)
self.askpassword_dialog.set_icon(get_deluge_icon())
- self.askpassword_dialog_entry = self.builder.get_object("askpassword_dialog_entry")
+ self.askpassword_dialog_entry = self.builder.get_object('askpassword_dialog_entry')
- self.hostlist = self.builder.get_object("hostlist")
+ self.hostlist = self.builder.get_object('hostlist')
# Create status pixbufs
if not HOSTLIST_PIXBUFS:
@@ -159,22 +159,22 @@ class ConnectionManager(component.Component):
# Setup host list treeview
self.hostlist.set_model(self.liststore)
render = gtk.CellRendererPixbuf()
- column = gtk.TreeViewColumn(_("Status"), render)
+ column = gtk.TreeViewColumn(_('Status'), render)
column.set_cell_data_func(render, cell_render_status, 3)
self.hostlist.append_column(column)
render = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Host"), render, text=HOSTLIST_COL_HOST)
+ column = gtk.TreeViewColumn(_('Host'), render, text=HOSTLIST_COL_HOST)
column.set_cell_data_func(render, cell_render_host, (1, 2, 4))
column.set_expand(True)
self.hostlist.append_column(column)
render = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Version"), render, text=HOSTLIST_COL_VERSION)
+ column = gtk.TreeViewColumn(_('Version'), render, text=HOSTLIST_COL_VERSION)
self.hostlist.append_column(column)
# Connect the signals to the handlers
self.builder.connect_signals(self)
self.hostlist.get_selection().connect(
- "changed", self.on_hostlist_selection_changed
+ 'changed', self.on_hostlist_selection_changed
)
# Load any saved host entries
@@ -187,7 +187,7 @@ class ConnectionManager(component.Component):
# if possible
self.hostlist.get_selection().unselect_all()
if len(self.liststore) > 0:
- self.hostlist.get_selection().select_path("0")
+ self.hostlist.get_selection().select_path('0')
# Run the dialog
self.connection_manager.run()
@@ -204,7 +204,7 @@ class ConnectionManager(component.Component):
del self.liststore
del self.hostlist
- def add_host(self, host, port, username="", password=""):
+ def add_host(self, host, port, username='', password=''):
"""
Adds a host to the list.
@@ -218,7 +218,7 @@ class ConnectionManager(component.Component):
# if thats the case
for entry in self.liststore:
if [entry[HOSTLIST_COL_HOST], entry[HOSTLIST_COL_PORT], entry[HOSTLIST_COL_USER]] == [host, port, username]:
- raise Exception("Host already in list!")
+ raise Exception('Host already in list!')
# Host isn't in the list, so lets add it
row = self.liststore.append()
@@ -227,7 +227,7 @@ class ConnectionManager(component.Component):
self.liststore[row][HOSTLIST_COL_PORT] = port
self.liststore[row][HOSTLIST_COL_USER] = username
self.liststore[row][HOSTLIST_COL_PASS] = password
- self.liststore[row][HOSTLIST_COL_STATUS] = "Offline"
+ self.liststore[row][HOSTLIST_COL_STATUS] = 'Offline'
# Save the host list to file
self.__save_hostlist()
@@ -241,9 +241,9 @@ class ConnectionManager(component.Component):
Save the current hostlist to the config file.
"""
# Grab the hosts from the liststore
- self.config["hosts"] = []
+ self.config['hosts'] = []
for row in self.liststore:
- self.config["hosts"].append((row[HOSTLIST_COL_ID],
+ self.config['hosts'].append((row[HOSTLIST_COL_ID],
row[HOSTLIST_COL_HOST],
row[HOSTLIST_COL_PORT],
row[HOSTLIST_COL_USER],
@@ -255,15 +255,15 @@ class ConnectionManager(component.Component):
"""
Load saved host entries
"""
- for host in self.config["hosts"]:
+ for host in self.config['hosts']:
new_row = self.liststore.append()
self.liststore[new_row][HOSTLIST_COL_ID] = host[0]
self.liststore[new_row][HOSTLIST_COL_HOST] = host[1]
self.liststore[new_row][HOSTLIST_COL_PORT] = host[2]
self.liststore[new_row][HOSTLIST_COL_USER] = host[3]
self.liststore[new_row][HOSTLIST_COL_PASS] = host[4]
- self.liststore[new_row][HOSTLIST_COL_STATUS] = "Offline"
- self.liststore[new_row][HOSTLIST_COL_VERSION] = ""
+ self.liststore[new_row][HOSTLIST_COL_STATUS] = 'Offline'
+ self.liststore[new_row][HOSTLIST_COL_VERSION] = ''
def __get_host_row(self, host_id):
"""
@@ -277,7 +277,7 @@ class ConnectionManager(component.Component):
def __update_list(self):
"""Updates the host status"""
- if not hasattr(self, "liststore"):
+ if not hasattr(self, 'liststore'):
# This callback was probably fired after the window closed
return
@@ -291,7 +291,7 @@ class ConnectionManager(component.Component):
if not self.running:
return
if row:
- row[HOSTLIST_COL_STATUS] = "Online"
+ row[HOSTLIST_COL_STATUS] = 'Online'
row[HOSTLIST_COL_VERSION] = info
self.__update_buttons()
c.disconnect()
@@ -300,7 +300,7 @@ class ConnectionManager(component.Component):
if not self.running:
return
if row:
- row[HOSTLIST_COL_STATUS] = "Offline"
+ row[HOSTLIST_COL_STATUS] = 'Offline'
self.__update_buttons()
c.disconnect()
@@ -313,8 +313,8 @@ class ConnectionManager(component.Component):
return
row = self.__get_host_row(host_id)
if row:
- row[HOSTLIST_COL_STATUS] = "Offline"
- row[HOSTLIST_COL_VERSION] = ""
+ row[HOSTLIST_COL_STATUS] = 'Offline'
+ row[HOSTLIST_COL_VERSION] = ''
self.__update_buttons()
for row in self.liststore:
@@ -326,16 +326,16 @@ class ConnectionManager(component.Component):
if client.connected() and (
gethostbyname(host),
port,
- "localclient" if not user and host in ("127.0.0.1", "localhost") else user
+ 'localclient' if not user and host in ('127.0.0.1', 'localhost') else user
) == client.connection_info():
def on_info(info, row):
if not self.running:
return
- log.debug("Client connected, query info: %s", info)
+ log.debug('Client connected, query info: %s', info)
row[HOSTLIST_COL_VERSION] = info
self.__update_buttons()
- row[HOSTLIST_COL_STATUS] = "Connected"
+ row[HOSTLIST_COL_STATUS] = 'Connected'
log.debug("Query daemon's info")
client.daemon.info().addCallback(on_info, row)
continue
@@ -350,24 +350,24 @@ class ConnectionManager(component.Component):
"""
Set the widgets to show the correct options from the config.
"""
- self.builder.get_object("chk_autoconnect").set_active(
- self.gtkui_config["autoconnect"]
+ self.builder.get_object('chk_autoconnect').set_active(
+ self.gtkui_config['autoconnect']
)
- self.builder.get_object("chk_autostart").set_active(
- self.gtkui_config["autostart_localhost"]
+ self.builder.get_object('chk_autostart').set_active(
+ self.gtkui_config['autostart_localhost']
)
- self.builder.get_object("chk_donotshow").set_active(
- not self.gtkui_config["show_connection_manager_on_start"]
+ self.builder.get_object('chk_donotshow').set_active(
+ not self.gtkui_config['show_connection_manager_on_start']
)
def __save_options(self):
"""
Set options in gtkui config from the toggle buttons.
"""
- 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()
+ 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()
def __update_buttons(self):
"""
@@ -375,19 +375,19 @@ class ConnectionManager(component.Component):
"""
if len(self.liststore) == 0:
# There is nothing in the list
- self.builder.get_object("button_startdaemon").set_sensitive(True)
- self.builder.get_object("button_connect").set_sensitive(False)
- self.builder.get_object("button_removehost").set_sensitive(False)
- self.builder.get_object("image_startdaemon").set_from_stock(
+ self.builder.get_object('button_startdaemon').set_sensitive(True)
+ self.builder.get_object('button_connect').set_sensitive(False)
+ self.builder.get_object('button_removehost').set_sensitive(False)
+ self.builder.get_object('image_startdaemon').set_from_stock(
gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU)
- self.builder.get_object("label_startdaemon").set_text("_Start Daemon")
+ self.builder.get_object('label_startdaemon').set_text('_Start Daemon')
model, row = self.hostlist.get_selection().get_selected()
if not row:
- self.builder.get_object("button_edithost").set_sensitive(False)
+ self.builder.get_object('button_edithost').set_sensitive(False)
return
- self.builder.get_object("button_edithost").set_sensitive(True)
+ self.builder.get_object('button_edithost').set_sensitive(True)
# Get some values about the selected host
status = model[row][HOSTLIST_COL_STATUS]
@@ -396,54 +396,54 @@ class ConnectionManager(component.Component):
user = model[row][HOSTLIST_COL_USER]
passwd = model[row][HOSTLIST_COL_PASS]
- log.debug("Status: %s", status)
+ log.debug('Status: %s', status)
# Check to see if we have a localhost entry selected
localhost = False
- if host in ("127.0.0.1", "localhost"):
+ if host in ('127.0.0.1', 'localhost'):
localhost = True
# Make sure buttons are sensitive at start
- self.builder.get_object("button_startdaemon").set_sensitive(True)
- self.builder.get_object("button_connect").set_sensitive(True)
- self.builder.get_object("button_removehost").set_sensitive(True)
+ self.builder.get_object('button_startdaemon').set_sensitive(True)
+ self.builder.get_object('button_connect').set_sensitive(True)
+ self.builder.get_object('button_removehost').set_sensitive(True)
# See if this is the currently connected host
- if status == "Connected":
+ if status == 'Connected':
# Display a disconnect button if we're connected to this host
- self.builder.get_object("button_connect").set_label("gtk-disconnect")
- self.builder.get_object("button_removehost").set_sensitive(False)
+ self.builder.get_object('button_connect').set_label('gtk-disconnect')
+ self.builder.get_object('button_removehost').set_sensitive(False)
else:
- self.builder.get_object("button_connect").set_label("gtk-connect")
- if status == "Offline" and not localhost:
- self.builder.get_object("button_connect").set_sensitive(False)
+ self.builder.get_object('button_connect').set_label('gtk-connect')
+ if status == 'Offline' and not localhost:
+ self.builder.get_object('button_connect').set_sensitive(False)
# Check to see if the host is online
- if status == "Connected" or status == "Online":
- self.builder.get_object("image_startdaemon").set_from_stock(
+ if status == 'Connected' or status == 'Online':
+ self.builder.get_object('image_startdaemon').set_from_stock(
gtk.STOCK_STOP, gtk.ICON_SIZE_MENU)
- self.builder.get_object("label_startdaemon").set_text(
- _("_Stop Daemon"))
+ self.builder.get_object('label_startdaemon').set_text(
+ _('_Stop Daemon'))
# Update the start daemon button if the selected host is localhost
- if localhost and status == "Offline":
+ if localhost and status == 'Offline':
# The localhost is not online
- self.builder.get_object("image_startdaemon").set_from_stock(
+ self.builder.get_object('image_startdaemon').set_from_stock(
gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU)
- self.builder.get_object("label_startdaemon").set_text(
- _("_Start Daemon"))
+ self.builder.get_object('label_startdaemon').set_text(
+ _('_Start Daemon'))
if client.connected() and (host, port, user) == client.connection_info():
# If we're connected, we can stop the dameon
- self.builder.get_object("button_startdaemon").set_sensitive(True)
+ self.builder.get_object('button_startdaemon').set_sensitive(True)
elif user and passwd:
# In this case we also have all the info to shutdown the daemon
- self.builder.get_object("button_startdaemon").set_sensitive(True)
+ self.builder.get_object('button_startdaemon').set_sensitive(True)
else:
# Can't stop non localhost daemons, specially without the necessary info
- self.builder.get_object("button_startdaemon").set_sensitive(False)
+ self.builder.get_object('button_startdaemon').set_sensitive(False)
# Make sure label is displayed correctly using mnemonics
- self.builder.get_object("label_startdaemon").set_use_underline(True)
+ self.builder.get_object('label_startdaemon').set_use_underline(True)
def start_daemon(self, port, config):
"""
@@ -456,9 +456,9 @@ class ConnectionManager(component.Component):
from errno import ENOENT
if ex.errno == ENOENT:
ErrorDialog(
- _("Unable to start daemon!"),
+ _('Unable to start daemon!'),
_("Deluge cannot find the 'deluged' executable, it is "
- "likely that you forgot to install the deluged package "
+ 'likely that you forgot to install the deluged package '
"or it's not in your PATH.")).run()
return False
else:
@@ -468,8 +468,8 @@ class ConnectionManager(component.Component):
import sys
tb = sys.exc_info()
ErrorDialog(
- _("Unable to start daemon!"),
- _("Please examine the details for more information."),
+ _('Unable to start daemon!'),
+ _('Please examine the details for more information.'),
details=traceback.format_exc(tb[2])).run()
# Signal handlers
@@ -488,8 +488,8 @@ class ConnectionManager(component.Component):
return do_connect()
def __on_connected(self, daemon_info, host_id):
- if self.gtkui_config["autoconnect"]:
- self.gtkui_config["autoconnect_host_id"] = host_id
+ if self.gtkui_config['autoconnect']:
+ self.gtkui_config['autoconnect_host_id'] = host_id
if self.running:
# When connected to a client, and then trying to connect to another,
# this component will be stopped(while the connect deferred is
@@ -500,10 +500,10 @@ class ConnectionManager(component.Component):
def __on_connected_failed(self, reason, host_id, host, port, user, passwd,
try_counter):
- log.debug("Failed to connect: %s", reason.value)
+ log.debug('Failed to connect: %s', reason.value)
if reason.check(AuthenticationRequired, BadLoginError):
- log.debug("PasswordRequired exception")
+ log.debug('PasswordRequired exception')
dialog = AuthenticationDialog(reason.value.message, reason.value.username)
def dialog_finished(response_id, host, port, user):
@@ -516,29 +516,29 @@ class ConnectionManager(component.Component):
elif reason.trap(IncompatibleClient):
dialog = ErrorDialog(
- _("Incompatible Client"), reason.value.message
+ _('Incompatible Client'), reason.value.message
)
return dialog.run()
if try_counter:
- log.info("Retrying connection.. Retries left: %s", try_counter)
+ log.info('Retrying connection.. Retries left: %s', try_counter)
return reactor.callLater(
0.5, self.__connect, host_id, host, port, user, passwd,
try_counter=try_counter - 1
)
msg = str(reason.value)
- if not self.builder.get_object("chk_autostart").get_active():
- msg += '\n' + _("Auto-starting the daemon locally is not enabled. "
+ if not self.builder.get_object('chk_autostart').get_active():
+ msg += '\n' + _('Auto-starting the daemon locally is not enabled. '
"See \"Options\" on the \"Connection Manager\".")
- ErrorDialog(_("Failed To Connect"), msg).run()
+ ErrorDialog(_('Failed To Connect'), msg).run()
def on_button_connect_clicked(self, widget=None):
model, row = self.hostlist.get_selection().get_selected()
if not row:
return
status = model[row][HOSTLIST_COL_STATUS]
- if status == "Connected":
+ if status == 'Connected':
def on_disconnect(reason):
self.__update_list()
client.disconnect().addCallback(on_disconnect)
@@ -550,10 +550,10 @@ class ConnectionManager(component.Component):
user = model[row][HOSTLIST_COL_USER]
password = model[row][HOSTLIST_COL_PASS]
- if (status == "Offline" and self.builder.get_object("chk_autostart").get_active() and
- host in ("127.0.0.1", "localhost")):
+ if (status == 'Offline' and self.builder.get_object('chk_autostart').get_active() and
+ host in ('127.0.0.1', 'localhost')):
if not self.start_daemon(port, get_config_dir()):
- log.debug("Failed to auto-start daemon")
+ log.debug('Failed to auto-start daemon')
return
return self.__connect(
host_id, host, port, user, password, try_counter=6
@@ -564,17 +564,17 @@ class ConnectionManager(component.Component):
self.connection_manager.response(gtk.RESPONSE_CLOSE)
def on_button_addhost_clicked(self, widget):
- log.debug("on_button_addhost_clicked")
- dialog = self.builder.get_object("addhost_dialog")
+ log.debug('on_button_addhost_clicked')
+ dialog = self.builder.get_object('addhost_dialog')
dialog.set_transient_for(self.connection_manager)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
- hostname_entry = self.builder.get_object("entry_hostname")
- port_spinbutton = self.builder.get_object("spinbutton_port")
- username_entry = self.builder.get_object("entry_username")
- password_entry = self.builder.get_object("entry_password")
- button_addhost_save = self.builder.get_object("button_addhost_save")
+ hostname_entry = self.builder.get_object('entry_hostname')
+ port_spinbutton = self.builder.get_object('spinbutton_port')
+ username_entry = self.builder.get_object('entry_username')
+ password_entry = self.builder.get_object('entry_password')
+ button_addhost_save = self.builder.get_object('button_addhost_save')
button_addhost_save.hide()
- button_addhost_add = self.builder.get_object("button_addhost_add")
+ button_addhost_add = self.builder.get_object('button_addhost_add')
button_addhost_add.show()
response = dialog.run()
if response == 1:
@@ -582,7 +582,7 @@ class ConnectionManager(component.Component):
password = password_entry.get_text()
hostname = hostname_entry.get_text()
- if (not password and not username or username == "localclient") and hostname in ["127.0.0.1", "localhost"]:
+ if (not password and not username or username == 'localclient') and hostname in ['127.0.0.1', 'localhost']:
username, password = get_localhost_auth()
# We add the host
@@ -590,34 +590,34 @@ class ConnectionManager(component.Component):
self.add_host(hostname, port_spinbutton.get_value_as_int(),
username, password)
except Exception as ex:
- ErrorDialog(_("Error Adding Host"), ex).run()
+ ErrorDialog(_('Error Adding Host'), ex).run()
- username_entry.set_text("")
- password_entry.set_text("")
- hostname_entry.set_text("")
+ username_entry.set_text('')
+ password_entry.set_text('')
+ hostname_entry.set_text('')
port_spinbutton.set_value(58846)
dialog.hide()
def on_button_edithost_clicked(self, widget=None):
- log.debug("on_button_edithost_clicked")
+ log.debug('on_button_edithost_clicked')
model, row = self.hostlist.get_selection().get_selected()
status = model[row][HOSTLIST_COL_STATUS]
- if status == "Connected":
+ if status == 'Connected':
def on_disconnect(reason):
self.__update_list()
client.disconnect().addCallback(on_disconnect)
return
- dialog = self.builder.get_object("addhost_dialog")
+ dialog = self.builder.get_object('addhost_dialog')
dialog.set_transient_for(self.connection_manager)
dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
- hostname_entry = self.builder.get_object("entry_hostname")
- port_spinbutton = self.builder.get_object("spinbutton_port")
- username_entry = self.builder.get_object("entry_username")
- password_entry = self.builder.get_object("entry_password")
- button_addhost_save = self.builder.get_object("button_addhost_save")
+ hostname_entry = self.builder.get_object('entry_hostname')
+ port_spinbutton = self.builder.get_object('spinbutton_port')
+ username_entry = self.builder.get_object('entry_username')
+ password_entry = self.builder.get_object('entry_password')
+ button_addhost_save = self.builder.get_object('button_addhost_save')
button_addhost_save.show()
- button_addhost_add = self.builder.get_object("button_addhost_add")
+ button_addhost_add = self.builder.get_object('button_addhost_add')
button_addhost_add.hide()
username_entry.set_text(self.liststore[row][HOSTLIST_COL_USER])
@@ -632,14 +632,14 @@ class ConnectionManager(component.Component):
password = password_entry.get_text()
hostname = hostname_entry.get_text()
- if (not password and not username or username == "localclient") and hostname in ["127.0.0.1", "localhost"]:
+ if (not password and not username or username == 'localclient') and hostname in ['127.0.0.1', 'localhost']:
username, password = get_localhost_auth()
self.liststore[row][HOSTLIST_COL_HOST] = hostname
self.liststore[row][HOSTLIST_COL_PORT] = port_spinbutton.get_value_as_int()
self.liststore[row][HOSTLIST_COL_USER] = username
self.liststore[row][HOSTLIST_COL_PASS] = password
- self.liststore[row][HOSTLIST_COL_STATUS] = "Offline"
+ self.liststore[row][HOSTLIST_COL_STATUS] = 'Offline'
# Save the host list to file
self.__save_hostlist()
@@ -647,14 +647,14 @@ class ConnectionManager(component.Component):
# Update the status of the hosts
self.__update_list()
- username_entry.set_text("")
- password_entry.set_text("")
- hostname_entry.set_text("")
+ username_entry.set_text('')
+ password_entry.set_text('')
+ hostname_entry.set_text('')
port_spinbutton.set_value(58846)
dialog.hide()
def on_button_removehost_clicked(self, widget):
- log.debug("on_button_removehost_clicked")
+ log.debug('on_button_removehost_clicked')
# Get the selected rows
paths = self.hostlist.get_selection().get_selected_rows()[1]
for path in paths:
@@ -667,7 +667,7 @@ class ConnectionManager(component.Component):
self.__save_hostlist()
def on_button_startdaemon_clicked(self, widget):
- log.debug("on_button_startdaemon_clicked")
+ log.debug('on_button_startdaemon_clicked')
if self.liststore.iter_n_children(None) < 1:
# There is nothing in the list, so lets create a localhost entry
self.add_host(DEFAULT_HOST, DEFAULT_PORT, *get_localhost_auth())
@@ -687,10 +687,10 @@ class ConnectionManager(component.Component):
user = self.liststore[paths[0]][HOSTLIST_COL_USER]
password = self.liststore[paths[0]][HOSTLIST_COL_PASS]
- if host not in ("127.0.0.1", "localhost"):
+ if host not in ('127.0.0.1', 'localhost'):
return
- if status in ("Online", "Connected"):
+ if status in ('Online', 'Connected'):
# We need to stop this daemon
# Call the shutdown method on the daemon
def on_daemon_shutdown(d):
@@ -703,12 +703,12 @@ class ConnectionManager(component.Component):
c = Client()
def on_connect(d, c):
- log.debug("on_connect")
+ log.debug('on_connect')
c.daemon.shutdown().addCallback(on_daemon_shutdown)
c.connect(host, port, user, password).addCallback(on_connect, c)
- elif status == "Offline":
+ elif status == 'Offline':
self.start_daemon(port, get_config_dir())
reactor.callLater(0.8, self.__update_list)
@@ -722,7 +722,7 @@ class ConnectionManager(component.Component):
self.__update_buttons()
def on_askpassword_dialog_connect_button_clicked(self, widget):
- log.debug("on on_askpassword_dialog_connect_button_clicked")
+ log.debug('on on_askpassword_dialog_connect_button_clicked')
self.askpassword_dialog.response(gtk.RESPONSE_OK)
def on_askpassword_dialog_entry_activate(self, entry):
@@ -733,9 +733,9 @@ class ConnectionManager(component.Component):
if not localclient_username:
# Nothing to do here, there's no auth file
return
- for idx, (_, host, _, username, _) in enumerate(config["hosts"][:]):
- if host in ("127.0.0.1", "localhost"):
+ for idx, (_, host, _, username, _) in enumerate(config['hosts'][:]):
+ if host in ('127.0.0.1', 'localhost'):
if not username:
- config["hosts"][idx][3] = localclient_username
- config["hosts"][idx][4] = localclient_password
+ config['hosts'][idx][3] = localclient_username
+ config['hosts'][idx][4] = localclient_password
return config
diff --git a/deluge/ui/gtkui/createtorrentdialog.py b/deluge/ui/gtkui/createtorrentdialog.py
index 596f73579..9734b3fc5 100644
--- a/deluge/ui/gtkui/createtorrentdialog.py
+++ b/deluge/ui/gtkui/createtorrentdialog.py
@@ -36,75 +36,75 @@ 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")
+ self.config = ConfigManager('gtkui.conf')
- self.dialog = self.builder.get_object("create_torrent_dialog")
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ self.dialog = self.builder.get_object('create_torrent_dialog')
+ self.dialog.set_transient_for(component.get('MainWindow').window)
self.builder.connect_signals({
- "on_button_file_clicked": self._on_button_file_clicked,
- "on_button_folder_clicked": self._on_button_folder_clicked,
- "on_button_remote_path_clicked": self._on_button_remote_path_clicked,
- "on_button_cancel_clicked": self._on_button_cancel_clicked,
- "on_button_save_clicked": self._on_button_save_clicked,
- "on_button_up_clicked": self._on_button_up_clicked,
- "on_button_add_clicked": self._on_button_add_clicked,
- "on_button_remove_clicked": self._on_button_remove_clicked,
- "on_button_down_clicked": self._on_button_down_clicked
+ 'on_button_file_clicked': self._on_button_file_clicked,
+ 'on_button_folder_clicked': self._on_button_folder_clicked,
+ 'on_button_remote_path_clicked': self._on_button_remote_path_clicked,
+ 'on_button_cancel_clicked': self._on_button_cancel_clicked,
+ 'on_button_save_clicked': self._on_button_save_clicked,
+ 'on_button_up_clicked': self._on_button_up_clicked,
+ 'on_button_add_clicked': self._on_button_add_clicked,
+ 'on_button_remove_clicked': self._on_button_remove_clicked,
+ 'on_button_down_clicked': self._on_button_down_clicked
})
# path, icon, size
self.files_treestore = gtk.TreeStore(str, str, gobject.TYPE_UINT64)
- column = gtk.TreeViewColumn(_("Filename"))
+ column = gtk.TreeViewColumn(_('Filename'))
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
- column.add_attribute(render, "stock-id", 1)
+ column.add_attribute(render, 'stock-id', 1)
render = gtk.CellRendererText()
column.pack_start(render, True)
- column.add_attribute(render, "text", 0)
+ column.add_attribute(render, 'text', 0)
column.set_expand(True)
- self.builder.get_object("treeview_files").append_column(column)
+ self.builder.get_object('treeview_files').append_column(column)
- column = gtk.TreeViewColumn(_("Size"))
+ column = gtk.TreeViewColumn(_('Size'))
render = gtk.CellRendererText()
column.pack_start(render)
column.set_cell_data_func(render, cell_data_size, 2)
- self.builder.get_object("treeview_files").append_column(column)
+ self.builder.get_object('treeview_files').append_column(column)
- self.builder.get_object("treeview_files").set_model(self.files_treestore)
- self.builder.get_object("treeview_files").set_show_expanders(False)
+ self.builder.get_object('treeview_files').set_model(self.files_treestore)
+ self.builder.get_object('treeview_files').set_show_expanders(False)
# tier, url
self.trackers_liststore = gtk.ListStore(int, str)
- self.builder.get_object("tracker_treeview").append_column(
- gtk.TreeViewColumn(_("Tier"), gtk.CellRendererText(), text=0))
- self.builder.get_object("tracker_treeview").append_column(
- gtk.TreeViewColumn(_("Tracker"), gtk.CellRendererText(), text=1))
+ self.builder.get_object('tracker_treeview').append_column(
+ gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0))
+ self.builder.get_object('tracker_treeview').append_column(
+ gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1))
- self.builder.get_object("tracker_treeview").set_model(self.trackers_liststore)
+ self.builder.get_object('tracker_treeview').set_model(self.trackers_liststore)
self.trackers_liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
if not client.is_localhost() and client.connected():
- self.builder.get_object("button_remote_path").show()
+ self.builder.get_object('button_remote_path').show()
else:
- self.builder.get_object("button_remote_path").hide()
+ self.builder.get_object('button_remote_path').hide()
self.dialog.show()
@@ -123,18 +123,18 @@ class CreateTorrentDialog(object):
def adjust_piece_size(self):
"""Adjusts the recommended piece based on the file/folder/path selected."""
size = self.files_treestore[0][2]
- model = self.builder.get_object("combo_piece_size").get_model()
+ model = self.builder.get_object('combo_piece_size').get_model()
for index, value in enumerate(model):
psize = self.parse_piece_size_text(value[0])
pieces = size // psize
if pieces < 2048 or (index + 1) == len(model):
- self.builder.get_object("combo_piece_size").set_active(index)
+ self.builder.get_object('combo_piece_size').set_active(index)
break
def _on_button_file_clicked(self, widget):
- log.debug("_on_button_file_clicked")
+ log.debug('_on_button_file_clicked')
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_("Choose a file"),
+ chooser = gtk.FileChooserDialog(_('Choose a file'),
self.dialog,
gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
@@ -142,7 +142,7 @@ class CreateTorrentDialog(object):
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(False)
- chooser.set_property("skip-taskbar-hint", True)
+ chooser.set_property('skip-taskbar-hint', True)
# Run the dialog
response = chooser.run()
@@ -161,9 +161,9 @@ class CreateTorrentDialog(object):
chooser.destroy()
def _on_button_folder_clicked(self, widget):
- log.debug("_on_button_folder_clicked")
+ log.debug('_on_button_folder_clicked')
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_("Choose a folder"),
+ chooser = gtk.FileChooserDialog(_('Choose a folder'),
self.dialog,
gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
@@ -171,7 +171,7 @@ class CreateTorrentDialog(object):
chooser.set_transient_for(self.dialog)
chooser.set_select_multiple(False)
- chooser.set_property("skip-taskbar-hint", True)
+ chooser.set_property('skip-taskbar-hint', True)
# Run the dialog
response = chooser.run()
@@ -189,11 +189,11 @@ class CreateTorrentDialog(object):
chooser.destroy()
def _on_button_remote_path_clicked(self, widget):
- log.debug("_on_button_remote_path_clicked")
- dialog = self.builder.get_object("remote_path_dialog")
- entry = self.builder.get_object("entry_path")
+ log.debug('_on_button_remote_path_clicked')
+ dialog = self.builder.get_object('remote_path_dialog')
+ entry = self.builder.get_object('entry_path')
dialog.set_transient_for(self.dialog)
- entry.set_text("/")
+ entry.set_text('/')
entry.grab_focus()
response = dialog.run()
@@ -201,7 +201,7 @@ class CreateTorrentDialog(object):
result = entry.get_text()
def _on_get_path_size(size):
- log.debug("size: %s", size)
+ log.debug('size: %s', size)
if size > 0:
self.files_treestore.clear()
self.files_treestore.append(None, [result, gtk.STOCK_NETWORK, size])
@@ -212,26 +212,26 @@ class CreateTorrentDialog(object):
dialog.hide()
def _on_button_cancel_clicked(self, widget):
- log.debug("_on_button_cancel_clicked")
+ log.debug('_on_button_cancel_clicked')
self.dialog.destroy()
def _on_button_save_clicked(self, widget):
- log.debug("_on_button_save_clicked")
+ log.debug('_on_button_save_clicked')
if len(self.files_treestore) == 0:
return
# Get the path
- path = self.files_treestore[0][0].rstrip("\\/")
- torrent_filename = "%s.torrent" % os.path.split(path)[-1]
+ path = self.files_treestore[0][0].rstrip('\\/')
+ torrent_filename = '%s.torrent' % os.path.split(path)[-1]
is_remote = self.files_treestore[0][1] == gtk.STOCK_NETWORK
if is_remote:
# This is a remote path
- dialog = self.builder.get_object("remote_save_dialog")
+ dialog = self.builder.get_object('remote_save_dialog')
dialog.set_transient_for(self.dialog)
- dialog_save_path = self.builder.get_object("entry_save_path")
- dialog_save_path.set_text(path + ".torrent")
+ dialog_save_path = self.builder.get_object('entry_save_path')
+ dialog_save_path.set_text(path + '.torrent')
response = dialog.run()
if response == gtk.RESPONSE_OK:
result = dialog_save_path.get_text()
@@ -241,23 +241,23 @@ class CreateTorrentDialog(object):
dialog.hide()
else:
# Setup the filechooserdialog
- chooser = gtk.FileChooserDialog(_("Save .torrent file"), self.dialog,
+ 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)
- chooser.set_property("skip-taskbar-hint", True)
+ chooser.set_property('skip-taskbar-hint', True)
# Add .torrent and * file filters
file_filter = gtk.FileFilter()
- file_filter.set_name(_("Torrent files"))
- file_filter.add_pattern("*." + "torrent")
+ file_filter.set_name(_('Torrent files'))
+ file_filter.add_pattern('*.' + 'torrent')
chooser.add_filter(file_filter)
file_filter = gtk.FileFilter()
- file_filter.set_name(_("All files"))
- file_filter.add_pattern("*")
+ file_filter.set_name(_('All files'))
+ file_filter.add_pattern('*')
chooser.add_filter(file_filter)
chooser.set_current_name(torrent_filename)
@@ -273,9 +273,9 @@ class CreateTorrentDialog(object):
# Fix up torrent filename
if len(result) < 9:
- result += ".torrent"
- elif result[-8:] != ".torrent":
- result += ".torrent"
+ result += '.torrent'
+ elif result[-8:] != '.torrent':
+ result += '.torrent'
# Get a list of trackers
trackers = []
@@ -293,24 +293,24 @@ class CreateTorrentDialog(object):
# Get a list of webseeds
webseeds = []
- b = self.builder.get_object("textview_webseeds").get_buffer()
- lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n")
+ b = self.builder.get_object('textview_webseeds').get_buffer()
+ lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n')
for l in lines:
if is_url(l):
webseeds.append(l)
# Get the piece length in bytes
- combo = self.builder.get_object("combo_piece_size")
+ combo = self.builder.get_object('combo_piece_size')
piece_length = self.parse_piece_size_text(combo.get_model()[combo.get_active()][0])
- author = self.builder.get_object("entry_author").get_text()
- comment = self.builder.get_object("entry_comments").get_text()
- private = self.builder.get_object("chk_private_flag").get_active()
- add_to_session = self.builder.get_object("chk_add_to_session").get_active()
+ author = self.builder.get_object('entry_author').get_text()
+ comment = self.builder.get_object('entry_comments').get_text()
+ private = self.builder.get_object('chk_private_flag').get_active()
+ add_to_session = self.builder.get_object('chk_add_to_session').get_active()
if is_remote:
def torrent_created():
- self.builder.get_object("progress_dialog").hide_all()
- client.deregister_event_handler("CreateTorrentProgressEvent", on_create_torrent_progress_event)
+ self.builder.get_object('progress_dialog').hide_all()
+ client.deregister_event_handler('CreateTorrentProgressEvent', on_create_torrent_progress_event)
def on_create_torrent_progress_event(piece_count, num_pieces):
self._on_create_torrent_progress(piece_count, num_pieces)
@@ -318,7 +318,7 @@ class CreateTorrentDialog(object):
from twisted.internet import reactor
reactor.callLater(0.5, torrent_created)
- client.register_event_handler("CreateTorrentProgressEvent", on_create_torrent_progress_event)
+ client.register_event_handler('CreateTorrentProgressEvent', on_create_torrent_progress_event)
client.core.create_torrent(
path,
@@ -335,7 +335,7 @@ class CreateTorrentDialog(object):
else:
def hide_progress(result):
- self.builder.get_object("progress_dialog").hide_all()
+ self.builder.get_object('progress_dialog').hide_all()
deferToThread(self.create_torrent,
path.decode('utf-8'),
@@ -351,8 +351,8 @@ class CreateTorrentDialog(object):
add_to_session).addCallback(hide_progress)
# Setup progress dialog
- self.builder.get_object("progress_dialog").set_transient_for(component.get("MainWindow").window)
- self.builder.get_object("progress_dialog").show_all()
+ self.builder.get_object('progress_dialog').set_transient_for(component.get('MainWindow').window)
+ self.builder.get_object('progress_dialog').show_all()
self.dialog.destroy()
@@ -372,17 +372,17 @@ class CreateTorrentDialog(object):
trackers=trackers)
if add_to_session:
- with open(target, "rb") as _file:
+ with open(target, 'rb') as _file:
filedump = base64.encodestring(_file.read())
client.core.add_torrent_file(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):
percent = value / num_pieces
def update_pbar_with_gobject(percent):
- pbar = self.builder.get_object("progressbar")
- pbar.set_text("%.2f%%" % (percent * 100))
+ pbar = self.builder.get_object('progressbar')
+ pbar.set_text('%.2f%%' % (percent * 100))
pbar.set_fraction(percent)
return False
@@ -392,8 +392,8 @@ class CreateTorrentDialog(object):
gobject.idle_add(update_pbar_with_gobject, percent)
def _on_button_up_clicked(self, widget):
- log.debug("_on_button_up_clicked")
- row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1]
+ log.debug('_on_button_up_clicked')
+ row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1]
if row is None:
return
if self.trackers_liststore[row][0] == 0:
@@ -402,25 +402,25 @@ class CreateTorrentDialog(object):
self.trackers_liststore[row][0] -= 1
def _on_button_down_clicked(self, widget):
- log.debug("_on_button_down_clicked")
- row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1]
+ log.debug('_on_button_down_clicked')
+ row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1]
if row is None:
return
self.trackers_liststore[row][0] += 1
def _on_button_add_clicked(self, widget):
- log.debug("_on_button_add_clicked")
+ 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 = builder.get_object('add_tracker_dialog')
dialog.set_transient_for(self.dialog)
- textview = builder.get_object("textview_trackers")
- if self.config["createtorrent.trackers"]:
- textview.get_buffer().set_text("\n".join(self.config["createtorrent.trackers"]))
+ textview = builder.get_object('textview_trackers')
+ if self.config['createtorrent.trackers']:
+ textview.get_buffer().set_text('\n'.join(self.config['createtorrent.trackers']))
else:
- textview.get_buffer().set_text("")
+ textview.get_buffer().set_text('')
textview.grab_focus()
response = dialog.run()
@@ -428,9 +428,9 @@ class CreateTorrentDialog(object):
# Create a list of trackers from the textview buffer
trackers = []
b = textview.get_buffer()
- lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n")
- self.config["createtorrent.trackers"] = lines
- log.debug("lines: %s", lines)
+ lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n')
+ self.config['createtorrent.trackers'] = lines
+ log.debug('lines: %s', lines)
for l in lines:
if is_url(l):
trackers.append(l)
@@ -447,8 +447,8 @@ class CreateTorrentDialog(object):
dialog.destroy()
def _on_button_remove_clicked(self, widget):
- log.debug("_on_button_remove_clicked")
- row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1]
+ log.debug('_on_button_remove_clicked')
+ row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1]
if row is None:
return
self.trackers_liststore.remove(row)
diff --git a/deluge/ui/gtkui/details_tab.py b/deluge/ui/gtkui/details_tab.py
index 10d69d3ff..0c71b3f0a 100644
--- a/deluge/ui/gtkui/details_tab.py
+++ b/deluge/ui/gtkui/details_tab.py
@@ -23,29 +23,29 @@ class DetailsTab(Tab):
Tab.__init__(self)
# Get the labels we need to update.
# widget name, modifier function, status keys
- builder = component.get("MainWindow").get_builder()
+ builder = component.get('MainWindow').get_builder()
- self._name = "Details"
- self._child_widget = builder.get_object("details_tab")
- self._tab_label = builder.get_object("details_tab_label")
+ self._name = 'Details'
+ self._child_widget = builder.get_object('details_tab')
+ self._tab_label = builder.get_object('details_tab_label')
self.label_widgets = [
- (builder.get_object("summary_name"), None, ("name",)),
- (builder.get_object("summary_total_size"), fsize, ("total_size",)),
- (builder.get_object("summary_num_files"), str, ("num_files",)),
- (builder.get_object("summary_completed"), fdate_or_dash, ("completed_time",)),
- (builder.get_object("summary_date_added"), fdate, ("time_added",)),
- (builder.get_object("summary_torrent_path"), None, ("download_location",)),
- (builder.get_object("summary_hash"), str, ("hash",)),
- (builder.get_object("summary_comments"), str, ("comment",)),
- (builder.get_object("summary_pieces"), fpieces_num_size, ("num_pieces", "piece_length")),
+ (builder.get_object('summary_name'), None, ('name',)),
+ (builder.get_object('summary_total_size'), fsize, ('total_size',)),
+ (builder.get_object('summary_num_files'), str, ('num_files',)),
+ (builder.get_object('summary_completed'), fdate_or_dash, ('completed_time',)),
+ (builder.get_object('summary_date_added'), fdate, ('time_added',)),
+ (builder.get_object('summary_torrent_path'), None, ('download_location',)),
+ (builder.get_object('summary_hash'), str, ('hash',)),
+ (builder.get_object('summary_comments'), str, ('comment',)),
+ (builder.get_object('summary_pieces'), fpieces_num_size, ('num_pieces', 'piece_length')),
]
self.status_keys = [status for widget in self.label_widgets for status in widget[2]]
def update(self):
# Get the first selected torrent
- selected = component.get("TorrentView").get_selected_torrents()
+ selected = component.get('TorrentView').get_selected_torrents()
# Only use the first torrent in the list or return if None selected
if selected:
@@ -55,7 +55,7 @@ class DetailsTab(Tab):
self.clear()
return
- session = component.get("SessionProxy")
+ session = component.get('SessionProxy')
session.get_torrent_status(selected, self.status_keys).addCallback(self._on_get_torrent_status)
def _on_get_torrent_status(self, status):
@@ -67,11 +67,11 @@ class DetailsTab(Tab):
for widget in self.label_widgets:
txt = xml_escape(self.get_status_for_widget(widget, status))
if widget[0].get_text() != txt:
- if widget[2][0] == "comment" and is_url(txt):
+ if widget[2][0] == 'comment' and is_url(txt):
widget[0].set_markup('<a href="%s">%s</a>' % (txt, txt))
else:
widget[0].set_markup(txt)
def clear(self):
for widget in self.label_widgets:
- widget[0].set_text("")
+ widget[0].set_text('')
diff --git a/deluge/ui/gtkui/dialogs.py b/deluge/ui/gtkui/dialogs.py
index 6a5a616e6..342f50c9d 100644
--- a/deluge/ui/gtkui/dialogs.py
+++ b/deluge/ui/gtkui/dialogs.py
@@ -32,24 +32,24 @@ class BaseDialog(gtk.Dialog):
"""
super(BaseDialog, self).__init__(
title=header,
- parent=parent if parent else component.get("MainWindow").window,
+ parent=parent if parent else component.get('MainWindow').window,
flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
buttons=buttons)
self.set_icon(get_deluge_icon())
- self.connect("delete-event", self._on_delete_event)
- self.connect("response", self._on_response)
+ self.connect('delete-event', self._on_delete_event)
+ self.connect('response', self._on_response)
# Setup all the formatting and such to make our dialog look pretty
self.set_border_width(5)
self.set_default_size(200, 100)
hbox = gtk.HBox(spacing=5)
image = gtk.Image()
- if not gtk.stock_lookup(icon) and (icon.endswith(".svg") or icon.endswith(".png")):
+ if not gtk.stock_lookup(icon) and (icon.endswith('.svg') or icon.endswith('.png')):
# Hack for Windows since it doesn't support svg
- if icon.endswith(".svg") and (windows_check() or osx_check()):
- icon = icon.rpartition(".svg")[0] + "16.png"
+ if icon.endswith('.svg') and (windows_check() or osx_check()):
+ icon = icon.rpartition('.svg')[0] + '16.png'
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(get_pixmap(icon), 32, 32)
image.set_from_pixbuf(pixbuf)
else:
@@ -156,7 +156,7 @@ class ErrorDialog(BaseDialog):
tb = sys.exc_info()
tb = traceback.format_exc(tb[2])
if details:
- details += "\n" + tb
+ details += '\n' + tb
else:
details = tb
@@ -169,7 +169,7 @@ class ErrorDialog(BaseDialog):
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
sw.set_shadow_type(gtk.SHADOW_IN)
sw.add(textview)
- label = gtk.Label(_("Details:"))
+ label = gtk.Label(_('Details:'))
label.set_alignment(0.0, 0.5)
self.vbox.pack_start(label, False, False)
self.vbox.pack_start(sw)
@@ -183,20 +183,20 @@ class AuthenticationDialog(BaseDialog):
When run(), it will return either a gtk.RESPONSE_CANCEL or a
gtk.RESPONSE_OK.
"""
- def __init__(self, err_msg="", username=None, parent=None):
+ def __init__(self, err_msg='', username=None, parent=None):
"""
:param err_msg: the error message we got back from the server
:type err_msg: string
"""
super(AuthenticationDialog, self).__init__(
- _("Authenticate"), err_msg,
+ _('Authenticate'), err_msg,
gtk.STOCK_DIALOG_AUTHENTICATION,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK),
parent)
table = gtk.Table(2, 2, False)
self.username_label = gtk.Label()
- self.username_label.set_markup("<b>" + _("Username:") + "</b>")
+ self.username_label.set_markup('<b>' + _('Username:') + '</b>')
self.username_label.set_alignment(1.0, 0.5)
self.username_label.set_padding(5, 5)
self.username_entry = gtk.Entry()
@@ -204,12 +204,12 @@ class AuthenticationDialog(BaseDialog):
table.attach(self.username_entry, 1, 2, 0, 1)
self.password_label = gtk.Label()
- self.password_label.set_markup("<b>" + _("Password:") + "</b>")
+ self.password_label.set_markup('<b>' + _('Password:') + '</b>')
self.password_label.set_alignment(1.0, 0.5)
self.password_label.set_padding(5, 5)
self.password_entry = gtk.Entry()
self.password_entry.set_visibility(False)
- self.password_entry.connect("activate", self.on_password_activate)
+ self.password_entry.connect('activate', self.on_password_activate)
table.attach(self.password_label, 0, 1, 1, 2)
table.attach(self.password_entry, 1, 2, 1, 2)
@@ -238,16 +238,16 @@ class AccountDialog(BaseDialog):
levels_mapping=None, parent=None):
if username:
super(AccountDialog, self).__init__(
- _("Edit Account"),
- _("Edit existing account"),
+ _('Edit Account'),
+ _('Edit existing account'),
gtk.STOCK_DIALOG_INFO,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_APPLY, gtk.RESPONSE_OK),
parent)
else:
super(AccountDialog, self).__init__(
- _("New Account"),
- _("Create a new account"),
+ _('New Account'),
+ _('Create a new account'),
gtk.STOCK_DIALOG_INFO,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_ADD, gtk.RESPONSE_OK),
@@ -257,7 +257,7 @@ class AccountDialog(BaseDialog):
table = gtk.Table(2, 3, False)
self.username_label = gtk.Label()
- self.username_label.set_markup("<b>" + _("Username:") + "</b>")
+ self.username_label.set_markup('<b>' + _('Username:') + '</b>')
self.username_label.set_alignment(1.0, 0.5)
self.username_label.set_padding(5, 5)
self.username_entry = gtk.Entry()
@@ -265,7 +265,7 @@ class AccountDialog(BaseDialog):
table.attach(self.username_entry, 1, 2, 0, 1)
self.authlevel_label = gtk.Label()
- self.authlevel_label.set_markup("<b>" + _("Authentication Level:") + "</b>")
+ self.authlevel_label.set_markup('<b>' + _('Authentication Level:') + '</b>')
self.authlevel_label.set_alignment(1.0, 0.5)
self.authlevel_label.set_padding(5, 5)
@@ -285,7 +285,7 @@ class AccountDialog(BaseDialog):
table.attach(self.authlevel_combo, 1, 2, 1, 2)
self.password_label = gtk.Label()
- self.password_label.set_markup("<b>" + _("Password:") + "</b>")
+ self.password_label.set_markup('<b>' + _('Password:') + '</b>')
self.password_label.set_alignment(1.0, 0.5)
self.password_label.set_padding(5, 5)
self.password_entry = gtk.Entry()
@@ -324,10 +324,10 @@ class OtherDialog(BaseDialog):
Returns:
int or float:
"""
- def __init__(self, header, text="", unit_text="", icon=None, default=0, parent=None):
+ def __init__(self, header, text='', unit_text='', icon=None, default=0, parent=None):
self.value_type = type(default)
if self.value_type not in (int, float):
- raise TypeError("default value needs to be an int or float")
+ raise TypeError('default value needs to be an int or float')
if not icon:
icon = gtk.STOCK_DIALOG_INFO
@@ -383,25 +383,25 @@ class PasswordDialog(BaseDialog):
When run(), it will return either a gtk.RESPONSE_CANCEL or a gtk.RESPONSE_OK.
"""
- def __init__(self, password_msg="", parent=None):
+ def __init__(self, password_msg='', parent=None):
"""
:param password_msg: the error message we got back from the server
:type password_msg: string
"""
super(PasswordDialog, self).__init__(
- _("Password Protected"), password_msg,
+ _('Password Protected'), password_msg,
gtk.STOCK_DIALOG_AUTHENTICATION,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK),
parent)
table = gtk.Table(1, 2, False)
self.password_label = gtk.Label()
- self.password_label.set_markup("<b>" + _("Password:") + "</b>")
+ self.password_label.set_markup('<b>' + _('Password:') + '</b>')
self.password_label.set_alignment(1.0, 0.5)
self.password_label.set_padding(5, 5)
self.password_entry = gtk.Entry()
self.password_entry.set_visibility(False)
- self.password_entry.connect("activate", self.on_password_activate)
+ self.password_entry.connect('activate', self.on_password_activate)
table.attach(self.password_label, 0, 1, 1, 2)
table.attach(self.password_entry, 1, 2, 1, 2)
diff --git a/deluge/ui/gtkui/edittrackersdialog.py b/deluge/ui/gtkui/edittrackersdialog.py
index 04718d4ad..695df07f6 100644
--- a/deluge/ui/gtkui/edittrackersdialog.py
+++ b/deluge/ui/gtkui/edittrackersdialog.py
@@ -26,26 +26,26 @@ class EditTrackersDialog(object):
def __init__(self, torrent_id, parent=None):
self.torrent_id = torrent_id
self.builder = gtk.Builder()
- self.gtkui_config = ConfigManager("gtkui.conf")
+ self.gtkui_config = ConfigManager('gtkui.conf')
# 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")
- self.treeview = self.builder.get_object("tracker_treeview")
- self.add_tracker_dialog = self.builder.get_object("add_tracker_dialog")
+ self.dialog = self.builder.get_object('edit_trackers_dialog')
+ self.treeview = self.builder.get_object('tracker_treeview')
+ self.add_tracker_dialog = self.builder.get_object('add_tracker_dialog')
self.add_tracker_dialog.set_transient_for(self.dialog)
- self.edit_tracker_entry = self.builder.get_object("edit_tracker_entry")
+ self.edit_tracker_entry = self.builder.get_object('edit_tracker_entry')
self.edit_tracker_entry.set_transient_for(self.dialog)
self.dialog.set_icon(get_deluge_icon())
@@ -56,16 +56,16 @@ class EditTrackersDialog(object):
# Connect the signals
self.builder.connect_signals({
- "on_button_up_clicked": self.on_button_up_clicked,
- "on_button_add_clicked": self.on_button_add_clicked,
- "on_button_edit_clicked": self.on_button_edit_clicked,
- "on_button_edit_cancel_clicked": self.on_button_edit_cancel_clicked,
- "on_button_edit_ok_clicked": self.on_button_edit_ok_clicked,
- "on_button_remove_clicked": self.on_button_remove_clicked,
- "on_button_down_clicked": self.on_button_down_clicked,
- "on_button_add_ok_clicked": self.on_button_add_ok_clicked,
- "on_button_add_cancel_clicked": self.on_button_add_cancel_clicked,
- "on_edit_trackers_dialog_configure_event": self.on_edit_trackers_dialog_configure_event
+ 'on_button_up_clicked': self.on_button_up_clicked,
+ 'on_button_add_clicked': self.on_button_add_clicked,
+ 'on_button_edit_clicked': self.on_button_edit_clicked,
+ 'on_button_edit_cancel_clicked': self.on_button_edit_cancel_clicked,
+ 'on_button_edit_ok_clicked': self.on_button_edit_ok_clicked,
+ 'on_button_remove_clicked': self.on_button_remove_clicked,
+ 'on_button_down_clicked': self.on_button_down_clicked,
+ 'on_button_add_ok_clicked': self.on_button_add_ok_clicked,
+ 'on_button_add_cancel_clicked': self.on_button_add_cancel_clicked,
+ 'on_edit_trackers_dialog_configure_event': self.on_edit_trackers_dialog_configure_event
})
# Create a liststore for tier, url
@@ -73,15 +73,15 @@ 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)
- self.dialog.connect("delete-event", self._on_delete_event)
- self.dialog.connect("response", self._on_response)
+ self.dialog.connect('delete-event', self._on_delete_event)
+ self.dialog.connect('response', self._on_response)
def run(self):
# Make sure we have a torrent_id.. if not just return
@@ -89,9 +89,9 @@ class EditTrackersDialog(object):
return
# Get the trackers for this torrent
- session = component.get("SessionProxy")
+ 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()
@@ -102,14 +102,14 @@ class EditTrackersDialog(object):
del self.gtkui_config
def load_edit_trackers_dialog_state(self):
- w = self.gtkui_config["edit_trackers_dialog_width"]
- h = self.gtkui_config["edit_trackers_dialog_height"]
+ w = self.gtkui_config['edit_trackers_dialog_width']
+ h = self.gtkui_config['edit_trackers_dialog_height']
if w is not None and h is not None:
self.dialog.resize(w, h)
def on_edit_trackers_dialog_configure_event(self, widget, event):
- self.gtkui_config["edit_trackers_dialog_width"] = event.width
- self.gtkui_config["edit_trackers_dialog_height"] = event.height
+ self.gtkui_config['edit_trackers_dialog_width'] = event.width
+ self.gtkui_config['edit_trackers_dialog_height'] = event.height
def _on_delete_event(self, widget, event):
self.deferred.callback(gtk.RESPONSE_DELETE_EVENT)
@@ -121,8 +121,8 @@ class EditTrackersDialog(object):
def each(model, path, _iter, data):
tracker = {}
- tracker["tier"] = model.get_value(_iter, 0)
- tracker["url"] = model.get_value(_iter, 1)
+ tracker['tier'] = model.get_value(_iter, 0)
+ tracker['url'] = model.get_value(_iter, 1)
self.trackers.append(tracker)
self.liststore.foreach(each, None)
if self.old_trackers != self.trackers:
@@ -137,9 +137,9 @@ class EditTrackersDialog(object):
def _on_get_torrent_status(self, status):
"""Display trackers dialog"""
- self.old_trackers = list(status["trackers"])
+ self.old_trackers = list(status['trackers'])
for tracker in self.old_trackers:
- self.add_tracker(tracker["tier"], tracker["url"])
+ self.add_tracker(tracker['tier'], tracker['url'])
self.treeview.set_cursor((0))
self.dialog.show()
@@ -152,43 +152,43 @@ class EditTrackersDialog(object):
return self.treeview.get_selection().get_selected()[1]
def on_button_add_clicked(self, widget):
- log.debug("on_button_add_clicked")
+ log.debug('on_button_add_clicked')
# Show the add tracker dialog
self.add_tracker_dialog.show()
- self.builder.get_object("textview_trackers").grab_focus()
+ self.builder.get_object('textview_trackers').grab_focus()
def on_button_remove_clicked(self, widget):
- log.debug("on_button_remove_clicked")
+ log.debug('on_button_remove_clicked')
selected = self.get_selected()
if selected is not None:
self.liststore.remove(selected)
def on_button_edit_clicked(self, widget):
"""edits an existing tracker"""
- log.debug("on_button_edit_clicked")
+ log.debug('on_button_edit_clicked')
selected = self.get_selected()
if selected:
tracker = self.liststore.get_value(selected, 1)
- self.builder.get_object("entry_edit_tracker").set_text(tracker)
+ self.builder.get_object('entry_edit_tracker').set_text(tracker)
self.edit_tracker_entry.show()
self.edit_tracker_entry.grab_focus()
self.dialog.set_sensitive(False)
def on_button_edit_cancel_clicked(self, widget):
- log.debug("on_button_edit_cancel_clicked")
+ log.debug('on_button_edit_cancel_clicked')
self.dialog.set_sensitive(True)
self.edit_tracker_entry.hide()
def on_button_edit_ok_clicked(self, widget):
- log.debug("on_button_edit_ok_clicked")
+ log.debug('on_button_edit_ok_clicked')
selected = self.get_selected()
- tracker = self.builder.get_object("entry_edit_tracker").get_text()
+ tracker = self.builder.get_object('entry_edit_tracker').get_text()
self.liststore.set_value(selected, 1, tracker)
self.dialog.set_sensitive(True)
self.edit_tracker_entry.hide()
def on_button_up_clicked(self, widget):
- log.debug("on_button_up_clicked")
+ log.debug('on_button_up_clicked')
selected = self.get_selected()
num_rows = self.liststore.iter_n_children(None)
if selected is not None and num_rows > 1:
@@ -200,7 +200,7 @@ class EditTrackersDialog(object):
self.liststore.set_value(selected, 0, new_tier)
def on_button_down_clicked(self, widget):
- log.debug("on_button_down_clicked")
+ log.debug('on_button_down_clicked')
selected = self.get_selected()
num_rows = self.liststore.iter_n_children(None)
if selected is not None and num_rows > 1:
@@ -210,13 +210,13 @@ class EditTrackersDialog(object):
self.liststore.set_value(selected, 0, new_tier)
def on_button_add_ok_clicked(self, widget):
- log.debug("on_button_add_ok_clicked")
+ log.debug('on_button_add_ok_clicked')
# Create a list of trackers from the textview widget
- textview = self.builder.get_object("textview_trackers")
+ textview = self.builder.get_object('textview_trackers')
trackers = []
b = textview.get_buffer()
- lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n")
+ lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n')
for l in lines:
if is_url(l):
trackers.append(l)
@@ -241,12 +241,12 @@ class EditTrackersDialog(object):
self.add_tracker(highest_tier + 1, tracker)
# Clear the entry widget and hide the dialog
- textview.get_buffer().set_text("")
+ textview.get_buffer().set_text('')
self.add_tracker_dialog.hide()
def on_button_add_cancel_clicked(self, widget):
- log.debug("on_button_add_cancel_clicked")
+ log.debug('on_button_add_cancel_clicked')
# Clear the entry widget and hide the dialog
b = gtk.TextBuffer()
- self.builder.get_object("textview_trackers").set_buffer(b)
+ self.builder.get_object('textview_trackers').set_buffer(b)
self.add_tracker_dialog.hide()
diff --git a/deluge/ui/gtkui/files_tab.py b/deluge/ui/gtkui/files_tab.py
index 36835dce4..eda87bdc2 100644
--- a/deluge/ui/gtkui/files_tab.py
+++ b/deluge/ui/gtkui/files_tab.py
@@ -32,10 +32,10 @@ def _(message):
return message
TRANSLATE = {
- "Do Not Download": _("Do Not Download"),
- "Normal Priority": _("Normal Priority"),
- "High Priority": _("High Priority"),
- "Highest Priority": _("Highest Priority"),
+ 'Do Not Download': _('Do Not Download'),
+ 'Normal Priority': _('Normal Priority'),
+ 'High Priority': _('High Priority'),
+ 'Highest Priority': _('Highest Priority'),
}
del _
@@ -50,52 +50,52 @@ def _t(text):
def cell_priority(column, cell, model, row, data):
if model.get_value(row, 5) == -1:
# This is a folder, so lets just set it blank for now
- cell.set_property("text", "")
+ cell.set_property('text', '')
return
priority = model.get_value(row, data)
- cell.set_property("text", _t(FILE_PRIORITY[priority]))
+ cell.set_property('text', _t(FILE_PRIORITY[priority]))
def cell_priority_icon(column, cell, model, row, data):
if model.get_value(row, 5) == -1:
# This is a folder, so lets just set it blank for now
- cell.set_property("stock-id", None)
+ cell.set_property('stock-id', None)
return
priority = model.get_value(row, data)
- if FILE_PRIORITY[priority] == "Do Not Download":
- cell.set_property("stock-id", gtk.STOCK_NO)
- elif FILE_PRIORITY[priority] == "Normal Priority":
- cell.set_property("stock-id", gtk.STOCK_YES)
- elif FILE_PRIORITY[priority] == "High Priority":
- cell.set_property("stock-id", gtk.STOCK_GO_UP)
- elif FILE_PRIORITY[priority] == "Highest Priority":
- cell.set_property("stock-id", gtk.STOCK_GOTO_TOP)
+ if FILE_PRIORITY[priority] == 'Do Not Download':
+ cell.set_property('stock-id', gtk.STOCK_NO)
+ elif FILE_PRIORITY[priority] == 'Normal Priority':
+ cell.set_property('stock-id', gtk.STOCK_YES)
+ elif FILE_PRIORITY[priority] == 'High Priority':
+ cell.set_property('stock-id', gtk.STOCK_GO_UP)
+ elif FILE_PRIORITY[priority] == 'Highest Priority':
+ cell.set_property('stock-id', gtk.STOCK_GOTO_TOP)
def cell_filename(column, cell, model, row, data):
"""Only show the tail portion of the file path"""
filepath = model.get_value(row, data)
- cell.set_property("text", os.path.split(filepath)[1])
+ cell.set_property('text', os.path.split(filepath)[1])
def cell_progress(column, cell, model, row, data):
text = model.get_value(row, data[0])
value = model.get_value(row, data[1])
- cell.set_property("visible", True)
- cell.set_property("text", text)
- cell.set_property("value", value)
+ cell.set_property('visible', True)
+ cell.set_property('text', text)
+ cell.set_property('value', value)
class FilesTab(Tab):
def __init__(self):
Tab.__init__(self)
- builder = component.get("MainWindow").get_builder()
+ builder = component.get('MainWindow').get_builder()
- self._name = "Files"
- self._child_widget = builder.get_object("files_tab")
- self._tab_label = builder.get_object("files_tab_label")
+ self._name = 'Files'
+ self._child_widget = builder.get_object('files_tab')
+ self._tab_label = builder.get_object('files_tab_label')
- self.listview = builder.get_object("files_listview")
+ self.listview = builder.get_object('files_listview')
# filename, size, progress string, progress value, priority, file index, icon id
self.treestore = gtk.TreeStore(str, gobject.TYPE_UINT64, str, float, int, int, str)
self.treestore.set_sort_column_id(0, gtk.SORT_ASCENDING)
@@ -105,18 +105,18 @@ class FilesTab(Tab):
self._editing_index = None
# Filename column
- self.filename_column_name = _("Filename")
+ self.filename_column_name = _('Filename')
column = gtk.TreeViewColumn(self.filename_column_name)
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
- column.add_attribute(render, "stock-id", 6)
+ column.add_attribute(render, 'stock-id', 6)
render = gtk.CellRendererText()
- render.set_property("editable", True)
- render.connect("edited", self._on_filename_edited)
- render.connect("editing-started", self._on_filename_editing_start)
- render.connect("editing-canceled", self._on_filename_editing_canceled)
+ render.set_property('editable', True)
+ render.connect('edited', self._on_filename_edited)
+ render.connect('editing-started', self._on_filename_editing_start)
+ render.connect('editing-canceled', self._on_filename_editing_canceled)
column.pack_start(render, True)
- column.add_attribute(render, "text", 0)
+ column.add_attribute(render, 'text', 0)
column.set_sort_column_id(0)
column.set_clickable(True)
column.set_resizable(True)
@@ -126,7 +126,7 @@ class FilesTab(Tab):
self.listview.append_column(column)
# Size column
- column = gtk.TreeViewColumn(_("Size"))
+ column = gtk.TreeViewColumn(_('Size'))
render = gtk.CellRendererText()
column.pack_start(render, False)
column.set_cell_data_func(render, cell_data_size, 1)
@@ -139,7 +139,7 @@ class FilesTab(Tab):
self.listview.append_column(column)
# Progress column
- column = gtk.TreeViewColumn(_("Progress"))
+ column = gtk.TreeViewColumn(_('Progress'))
render = gtk.CellRendererProgress()
column.pack_start(render)
column.set_cell_data_func(render, cell_progress, (2, 3))
@@ -152,7 +152,7 @@ class FilesTab(Tab):
self.listview.append_column(column)
# Priority column
- column = gtk.TreeViewColumn(_("Priority"))
+ column = gtk.TreeViewColumn(_('Priority'))
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
column.set_cell_data_func(render, cell_priority_icon, 4)
@@ -173,24 +173,24 @@ class FilesTab(Tab):
self.listview.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
- self.file_menu = builder.get_object("menu_file_tab")
+ self.file_menu = builder.get_object('menu_file_tab')
self.file_menu_priority_items = [
- builder.get_object("menuitem_donotdownload"),
- builder.get_object("menuitem_normal"),
- builder.get_object("menuitem_high"),
- builder.get_object("menuitem_highest"),
- builder.get_object("menuitem_priority_sep")
+ builder.get_object('menuitem_donotdownload'),
+ builder.get_object('menuitem_normal'),
+ builder.get_object('menuitem_high'),
+ builder.get_object('menuitem_highest'),
+ builder.get_object('menuitem_priority_sep')
]
self.localhost_widgets = [
- builder.get_object("menuitem_open_file"),
- builder.get_object("menuitem_show_file"),
- builder.get_object("menuitem3")
+ builder.get_object('menuitem_open_file'),
+ builder.get_object('menuitem_show_file'),
+ builder.get_object('menuitem3')
]
- self.listview.connect("row-activated", self._on_row_activated)
- self.listview.connect("key-press-event", self._on_key_press_event)
- self.listview.connect("button-press-event", self._on_button_press_event)
+ self.listview.connect('row-activated', self._on_row_activated)
+ self.listview.connect('key-press-event', self._on_key_press_event)
+ self.listview.connect('button-press-event', self._on_button_press_event)
self.listview.enable_model_drag_source(
gtk.gdk.BUTTON1_MASK,
@@ -198,23 +198,23 @@ class FilesTab(Tab):
gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE)
self.listview.enable_model_drag_dest([('text/plain', 0, 0)], gtk.gdk.ACTION_DEFAULT)
- self.listview.connect("drag_data_get", self._on_drag_data_get_data)
- self.listview.connect("drag_data_received", self._on_drag_data_received_data)
-
- component.get("MainWindow").connect_signals({
- "on_menuitem_open_file_activate": self._on_menuitem_open_file_activate,
- "on_menuitem_show_file_activate": self._on_menuitem_show_file_activate,
- "on_menuitem_donotdownload_activate": self._on_menuitem_donotdownload_activate,
- "on_menuitem_normal_activate": self._on_menuitem_normal_activate,
- "on_menuitem_high_activate": self._on_menuitem_high_activate,
- "on_menuitem_highest_activate": self._on_menuitem_highest_activate,
- "on_menuitem_expand_all_activate": self._on_menuitem_expand_all_activate
+ self.listview.connect('drag_data_get', self._on_drag_data_get_data)
+ self.listview.connect('drag_data_received', self._on_drag_data_received_data)
+
+ component.get('MainWindow').connect_signals({
+ 'on_menuitem_open_file_activate': self._on_menuitem_open_file_activate,
+ 'on_menuitem_show_file_activate': self._on_menuitem_show_file_activate,
+ 'on_menuitem_donotdownload_activate': self._on_menuitem_donotdownload_activate,
+ 'on_menuitem_normal_activate': self._on_menuitem_normal_activate,
+ 'on_menuitem_high_activate': self._on_menuitem_high_activate,
+ 'on_menuitem_highest_activate': self._on_menuitem_highest_activate,
+ 'on_menuitem_expand_all_activate': self._on_menuitem_expand_all_activate
})
# Connect to various events from the daemon
- client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event)
- client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event)
- client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event)
+ client.register_event_handler('TorrentFileRenamedEvent', self._on_torrentfilerenamed_event)
+ client.register_event_handler('TorrentFolderRenamedEvent', self._on_torrentfolderrenamed_event)
+ client.register_event_handler('TorrentRemovedEvent', self._on_torrentremoved_event)
# Attempt to load state
self.load_state()
@@ -225,7 +225,7 @@ class FilesTab(Tab):
self.torrent_id = None
def start(self):
- attr = "hide" if not client.is_localhost() else "show"
+ attr = 'hide' if not client.is_localhost() else 'show'
for widget in self.localhost_widgets:
getattr(widget, attr)()
@@ -235,47 +235,47 @@ class FilesTab(Tab):
# Setup state dict
state = {
- "columns": {},
- "sort_id": int(column_id) if column_id >= 0 else None,
- "sort_order": int(sort_order) if sort_order >= 0 else None
+ 'columns': {},
+ 'sort_id': int(column_id) if column_id >= 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()
+ state['columns'][column.get_title()] = {
+ 'position': index,
+ 'width': column.get_width()
}
- save_pickled_state_file("files_tab.state", state)
+ save_pickled_state_file('files_tab.state', state)
def load_state(self):
- state = load_pickled_state_file("files_tab.state")
+ state = load_pickled_state_file('files_tab.state')
if not state:
return
- if state["sort_id"] is not None and state["sort_order"] is not None:
- self.treestore.set_sort_column_id(state["sort_id"], state["sort_order"])
+ if state['sort_id'] is not None and state['sort_order'] is not None:
+ self.treestore.set_sort_column_id(state['sort_id'], state['sort_order'])
for (index, column) in enumerate(self.listview.get_columns()):
cname = column.get_title()
- if cname in state["columns"]:
- cstate = state["columns"][cname]
+ if cname in state['columns']:
+ cstate = state['columns'][cname]
column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
- column.set_fixed_width(cstate["width"] if cstate["width"] > 0 else 10)
- if state["sort_id"] == index and state["sort_order"] is not None:
+ column.set_fixed_width(cstate['width'] if cstate['width'] > 0 else 10)
+ if state['sort_id'] == index and state['sort_order'] is not None:
column.set_sort_indicator(True)
- column.set_sort_order(state["sort_order"])
- if cstate["position"] != index:
+ column.set_sort_order(state['sort_order'])
+ if cstate['position'] != index:
# Column is in wrong position
- if cstate["position"] == 0:
+ if cstate['position'] == 0:
self.listview.move_column_after(column, None)
- elif self.listview.get_columns()[cstate["position"] - 1].get_title() != cname:
- self.listview.move_column_after(column, self.listview.get_columns()[cstate["position"] - 1])
+ elif self.listview.get_columns()[cstate['position'] - 1].get_title() != cname:
+ self.listview.move_column_after(column, self.listview.get_columns()[cstate['position'] - 1])
def update(self):
# Get the first selected torrent
- torrent_id = component.get("TorrentView").get_selected_torrents()
+ torrent_id = component.get('TorrentView').get_selected_torrents()
# Only use the first torrent in the list or return if None selected
if len(torrent_id) != 0:
@@ -285,12 +285,12 @@ class FilesTab(Tab):
self.clear()
return
- status_keys = ["file_progress", "file_priorities"]
+ status_keys = ['file_progress', 'file_priorities']
if torrent_id != self.torrent_id:
# We only want to do this if the torrent_id has changed
self.treestore.clear()
self.torrent_id = torrent_id
- status_keys += ["storage_mode", "is_seed"]
+ status_keys += ['storage_mode', 'is_seed']
if self.torrent_id in self.files_list:
# We already have the files list stored, so just update the view
@@ -298,10 +298,10 @@ class FilesTab(Tab):
if self.torrent_id not in self.files_list or not self.files_list[self.torrent_id]:
# We need to get the files list
- log.debug("Getting file list from core..")
- status_keys += ["files"]
+ log.debug('Getting file list from core..')
+ status_keys += ['files']
- component.get("SessionProxy").get_torrent_status(
+ component.get('SessionProxy').get_torrent_status(
self.torrent_id, status_keys).addCallback(self._on_get_torrent_status, self.torrent_id)
def clear(self):
@@ -311,7 +311,7 @@ class FilesTab(Tab):
def _on_row_activated(self, tree, path, view_column):
self._on_menuitem_open_file_activate(None)
- def get_file_path(self, row, path=""):
+ def get_file_path(self, row, path=''):
if not row:
return path
@@ -325,8 +325,8 @@ class FilesTab(Tab):
selected.append(self.treestore.get_iter(path))
for select in selected:
- path = self.get_file_path(select).split("/")
- filepath = os.path.join(status["download_location"], *path)
+ path = self.get_file_path(select).split('/')
+ filepath = os.path.join(status['download_location'], *path)
log.debug("Open file '%s'", filepath)
timestamp = gtk.get_current_event_time()
open_file(filepath, timestamp=timestamp)
@@ -338,8 +338,8 @@ class FilesTab(Tab):
selected.append(self.treestore.get_iter(path))
for select in selected:
- path = self.get_file_path(select).split("/")
- filepath = os.path.join(status["download_location"], *path)
+ path = self.get_file_path(select).split('/')
+ filepath = os.path.join(status['download_location'], *path)
log.debug("Show file '%s'", filepath)
timestamp = gtk.get_current_event_time()
show_file(filepath, timestamp=timestamp)
@@ -348,11 +348,11 @@ class FilesTab(Tab):
def prepare_file_store(self, torrent_files):
split_files = {}
for index, torrent_file in enumerate(torrent_files):
- self.prepare_file(torrent_file, torrent_file["path"], index, split_files)
+ self.prepare_file(torrent_file, torrent_file['path'], index, split_files)
self.add_files(None, split_files)
def prepare_file(self, torrent_file, file_name, file_num, files_storage):
- first_slash_index = file_name.find("/")
+ first_slash_index = file_name.find('/')
if first_slash_index == -1:
files_storage[file_name] = (file_num, torrent_file)
else:
@@ -365,22 +365,22 @@ class FilesTab(Tab):
def add_files(self, parent_iter, split_files):
chunk_size_total = 0
for key, value in split_files.iteritems():
- if key.endswith("/"):
+ if key.endswith('/'):
chunk_iter = self.treestore.append(parent_iter,
- [key, 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY])
+ [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])
- chunk_size_total += value[1]["size"]
+ [key, value[1]['size'], '', 0, 0, value[0], gtk.STOCK_FILE])
+ chunk_size_total += value[1]['size']
return chunk_size_total
def update_files(self):
with listview_replace_treestore(self.listview):
self.prepare_file_store(self.files_list[self.torrent_id])
- self.listview.expand_row("0", False)
+ self.listview.expand_row('0', False)
def get_selected_files(self):
"""Returns a list of file indexes that are selected."""
@@ -435,7 +435,7 @@ class FilesTab(Tab):
# Catch the unusal error found when moving folders around
value = 0
self.treestore[parent][3] = value
- self.treestore[parent][2] = "%i%%" % value
+ self.treestore[parent][2] = '%i%%' % value
return completed_bytes
get_completed_bytes(self.treestore.iter_children(root))
@@ -445,11 +445,11 @@ class FilesTab(Tab):
if self.torrent_id != torrent_id:
return
- if "is_seed" in status:
- self.__is_seed = status["is_seed"]
+ if 'is_seed' in status:
+ self.__is_seed = status['is_seed']
- if "files" in status:
- self.files_list[self.torrent_id] = status["files"]
+ if 'files' in status:
+ self.files_list[self.torrent_id] = status['files']
self.update_files()
# (index, iter)
@@ -462,15 +462,15 @@ class FilesTab(Tab):
continue
try:
- progress_string = "%i%%" % (status["file_progress"][index] * 100)
+ progress_string = '%i%%' % (status['file_progress'][index] * 100)
except IndexError:
continue
if row[2] != progress_string:
row[2] = progress_string
- progress_value = status["file_progress"][index] * 100
+ progress_value = status['file_progress'][index] * 100
if row[3] != progress_value:
row[3] = progress_value
- file_priority = status["file_priorities"][index]
+ file_priority = status['file_priorities'][index]
if row[4] != file_priority:
row[4] = file_priority
if self._editing_index != -1:
@@ -479,7 +479,7 @@ class FilesTab(Tab):
def _on_button_press_event(self, widget, event):
"""This is a callback for showing the right-click context menu."""
- log.debug("on_button_press_event")
+ log.debug('on_button_press_event')
# We only care about right-clicks
if event.button == 3:
x, y = event.get_coords()
@@ -520,13 +520,13 @@ 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)
+ component.get('SessionProxy').get_torrent_status(
+ 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)
+ component.get('SessionProxy').get_torrent_status(
+ 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'"""
@@ -542,36 +542,36 @@ class FilesTab(Tab):
self.treestore.foreach(set_file_priority, None)
file_priorities.sort()
priorities = [p[1] for p in file_priorities]
- log.debug("priorities: %s", priorities)
+ log.debug('priorities: %s', priorities)
client.core.set_torrent_file_priorities(self.torrent_id, priorities)
def _on_menuitem_donotdownload_activate(self, menuitem):
self._set_file_priorities_on_user_change(
self.get_selected_files(),
- FILE_PRIORITY["Do Not Download"])
+ FILE_PRIORITY['Do Not Download'])
def _on_menuitem_normal_activate(self, menuitem):
self._set_file_priorities_on_user_change(
self.get_selected_files(),
- FILE_PRIORITY["Normal Priority"])
+ FILE_PRIORITY['Normal Priority'])
def _on_menuitem_high_activate(self, menuitem):
self._set_file_priorities_on_user_change(
self.get_selected_files(),
- FILE_PRIORITY["High Priority"])
+ FILE_PRIORITY['High Priority'])
def _on_menuitem_highest_activate(self, menuitem):
self._set_file_priorities_on_user_change(
self.get_selected_files(),
- FILE_PRIORITY["Highest Priority"])
+ FILE_PRIORITY['Highest Priority'])
def _on_menuitem_expand_all_activate(self, menuitem):
self.listview.expand_all()
def _on_filename_edited(self, renderer, path, new_text):
index = self.treestore[path][5]
- log.debug("new_text: %s", new_text)
+ log.debug('new_text: %s', new_text)
# Don't do anything if the text hasn't changed
if new_text == self.treestore[path][0]:
@@ -585,7 +585,7 @@ class FilesTab(Tab):
def get_filepath(i):
ip = self.treestore.iter_parent(i)
- fp = ""
+ fp = ''
while ip:
fp = self.treestore[ip][0] + fp
ip = self.treestore.iter_parent(ip)
@@ -597,14 +597,14 @@ class FilesTab(Tab):
else:
filepath = new_text
- log.debug("filepath: %s", filepath)
+ log.debug('filepath: %s', filepath)
client.core.rename_files(self.torrent_id, [(index, filepath)])
else:
# We are renaming a folder
folder = self.treestore[path][0]
- parent_path = ""
+ parent_path = ''
itr = self.treestore.iter_parent(self.treestore.get_iter(path))
while itr:
parent_path = self.treestore[itr][0] + parent_path
@@ -621,45 +621,45 @@ class FilesTab(Tab):
self._editing_index = None
def _on_torrentfilerenamed_event(self, torrent_id, index, name):
- log.debug("index: %s name: %s", index, name)
+ log.debug('index: %s name: %s', index, name)
if torrent_id not in self.files_list:
return
- old_name = self.files_list[torrent_id][index]["path"]
- self.files_list[torrent_id][index]["path"] = name
+ old_name = self.files_list[torrent_id][index]['path']
+ self.files_list[torrent_id][index]['path'] = name
# We need to update the filename displayed if we're currently viewing
# this torrents files.
if torrent_id != self.torrent_id:
return
- old_name_parent = old_name.split("/")[:-1]
- parent_path = name.split("/")[:-1]
+ old_name_parent = old_name.split('/')[:-1]
+ parent_path = name.split('/')[:-1]
if old_name_parent != parent_path:
if parent_path:
for i, p in enumerate(parent_path):
- p_itr = self.get_iter_at_path("/".join(parent_path[:i + 1]) + "/")
+ p_itr = self.get_iter_at_path('/'.join(parent_path[:i + 1]) + '/')
if not p_itr:
- p_itr = self.get_iter_at_path("/".join(parent_path[:i]) + "/")
+ 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 = self.get_iter_at_path("/".join(parent_path) + "/")
+ 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, *xrange(self.treestore.get_n_columns())))
self.treestore.remove(old_name_itr)
# Remove old parent path
- p_itr = self.get_iter_at_path("/".join(old_name_parent) + "/")
+ p_itr = self.get_iter_at_path('/'.join(old_name_parent) + '/')
self.remove_childless_folders(p_itr)
else:
- new_folders = name.split("/")[:-1]
+ new_folders = name.split('/')[:-1]
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, *xrange(self.treestore.get_n_columns())))
@@ -675,26 +675,26 @@ class FilesTab(Tab):
def get_iter_at_path(self, filepath):
"""Returns the gtkTreeIter for filepath."""
- log.debug("get_iter_at_path: %s", filepath)
+ log.debug('get_iter_at_path: %s', filepath)
is_dir = False
- if filepath[-1] == "/":
+ if filepath[-1] == '/':
is_dir = True
- filepath = filepath.split("/")
- if "" in filepath:
- filepath.remove("")
+ filepath = filepath.split('/')
+ if '' in filepath:
+ filepath.remove('')
path_iter = None
itr = self.treestore.iter_children(None)
level = 0
while itr:
ipath = self.treestore[itr][0]
- if (level + 1) != len(filepath) and ipath == filepath[level] + "/":
+ if (level + 1) != len(filepath) and ipath == filepath[level] + '/':
# We're not at the last index, but we do have a match
itr = self.treestore.iter_children(itr)
level += 1
continue
- elif (level + 1) == len(filepath) and ipath == (filepath[level] + "/" if is_dir else filepath[level]):
+ elif (level + 1) == len(filepath) and ipath == (filepath[level] + '/' if is_dir else filepath[level]):
# This is the iter we've been searching for
path_iter = itr
break
@@ -711,33 +711,33 @@ class FilesTab(Tab):
itr = parent
def _on_torrentfolderrenamed_event(self, torrent_id, old_folder, new_folder):
- log.debug("on_torrent_folder_renamed_signal")
- log.debug("old_folder: %s new_folder: %s", old_folder, new_folder)
+ log.debug('on_torrent_folder_renamed_signal')
+ log.debug('old_folder: %s new_folder: %s', old_folder, new_folder)
if torrent_id not in self.files_list:
return
- if old_folder[-1] != "/":
- old_folder += "/"
+ if old_folder[-1] != '/':
+ old_folder += '/'
- if len(new_folder) > 0 and new_folder[-1] != "/":
- new_folder += "/"
+ if len(new_folder) > 0 and new_folder[-1] != '/':
+ new_folder += '/'
for fd in self.files_list[torrent_id]:
- if fd["path"].startswith(old_folder):
- fd["path"] = fd["path"].replace(old_folder, new_folder, 1)
+ if fd['path'].startswith(old_folder):
+ fd['path'] = fd['path'].replace(old_folder, new_folder, 1)
if torrent_id == self.torrent_id:
- old_split = old_folder.split("/")
+ old_split = old_folder.split('/')
try:
- old_split.remove("")
+ old_split.remove('')
except ValueError:
pass
- new_split = new_folder.split("/")
+ new_split = new_folder.split('/')
try:
- new_split.remove("")
+ new_split.remove('')
except ValueError:
pass
@@ -748,7 +748,7 @@ class FilesTab(Tab):
if len(new_split) == len(old_split):
# These are at the same tree depth, so it's a simple rename
- self.treestore[old_folder_iter][0] = new_split[-1] + "/"
+ self.treestore[old_folder_iter][0] = new_split[-1] + '/'
return
if new_folder_iter:
# This means that a folder by this name already exists
@@ -757,9 +757,9 @@ class FilesTab(Tab):
parent = old_folder_iter_parent
if new_split:
for ns in new_split[:-1]:
- parent = self.treestore.append(parent, [ns + "/", 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY])
+ parent = self.treestore.append(parent, [ns + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY])
- self.treestore[old_folder_iter][0] = new_split[-1] + "/"
+ self.treestore[old_folder_iter][0] = new_split[-1] + '/'
reparent_iter(self.treestore, old_folder_iter, parent)
else:
child_itr = self.treestore.iter_children(old_folder_iter)
@@ -781,15 +781,15 @@ class FilesTab(Tab):
try:
selected = cPickle.loads(selection.data)
except cPickle.UnpicklingError:
- log.debug("Invalid selection data: %s", selection.data)
+ log.debug('Invalid selection data: %s', selection.data)
return
- log.debug("selection.data: %s", selected)
+ log.debug('selection.data: %s', selected)
drop_info = treeview.get_dest_row_at_pos(x, y)
model = treeview.get_model()
if drop_info:
itr = model.get_iter(drop_info[0])
parent_iter = model.iter_parent(itr)
- parent_path = ""
+ parent_path = ''
if model[itr][5] == -1:
parent_path += model[itr][0]
@@ -798,10 +798,10 @@ class FilesTab(Tab):
parent_iter = model.iter_parent(parent_iter)
if model[selected[0]][5] == -1:
- log.debug("parent_path: %s", parent_path)
- log.debug("rename_to: %s", parent_path + model[selected[0]][0])
+ log.debug('parent_path: %s', parent_path)
+ log.debug('rename_to: %s', parent_path + model[selected[0]][0])
# Get the full path of the folder we want to rename
- pp = ""
+ pp = ''
itr = self.treestore.iter_parent(self.treestore.get_iter(selected[0]))
while itr:
pp = self.treestore[itr][0] + pp
@@ -813,5 +813,5 @@ class FilesTab(Tab):
to_rename = []
for s in selected:
to_rename.append((model[s][5], parent_path + model[s][0]))
- log.debug("to_rename: %s", to_rename)
+ log.debug('to_rename: %s', to_rename)
client.core.rename_files(self.torrent_id, to_rename)
diff --git a/deluge/ui/gtkui/filtertreeview.py b/deluge/ui/gtkui/filtertreeview.py
index c788048ec..f257f3556 100644
--- a/deluge/ui/gtkui/filtertreeview.py
+++ b/deluge/ui/gtkui/filtertreeview.py
@@ -25,21 +25,21 @@ from deluge.ui.client import client
log = logging.getLogger(__name__)
STATE_PIX = {
- "All": "all",
- "Downloading": "downloading",
- "Seeding": "seeding",
- "Paused": "inactive",
- "Checking": "checking",
- "Queued": "queued",
- "Error": "alert",
- "Active": "active",
- "Allocating": "checking",
- "Moving": "checking"
+ 'All': 'all',
+ 'Downloading': 'downloading',
+ 'Seeding': 'seeding',
+ 'Paused': 'inactive',
+ 'Checking': 'checking',
+ 'Queued': 'queued',
+ 'Error': 'alert',
+ 'Active': 'active',
+ 'Allocating': 'checking',
+ 'Moving': 'checking'
}
TRACKER_PIX = {
- "All": "tracker_all",
- "Error": "tracker_warning",
+ 'All': 'tracker_all',
+ 'Error': 'tracker_warning',
}
FILTER_COLUMN = 5
@@ -47,25 +47,25 @@ FILTER_COLUMN = 5
class FilterTreeView(component.Component):
def __init__(self):
- component.Component.__init__(self, "FilterTreeView", interval=2)
- self.window = component.get("MainWindow")
- self.config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'FilterTreeView', interval=2)
+ self.window = component.get('MainWindow')
+ self.config = ConfigManager('gtkui.conf')
- self.tracker_icons = component.get("TrackerIcons")
+ self.tracker_icons = component.get('TrackerIcons')
- self.sidebar = component.get("SideBar")
+ self.sidebar = component.get('SideBar')
self.treeview = gtk.TreeView()
- self.sidebar.add_tab(self.treeview, "filters", "Filters")
+ self.sidebar.add_tab(self.treeview, 'filters', 'Filters')
# set filter to all when hidden:
- self.sidebar.notebook.connect("hide", self._on_hide)
+ self.sidebar.notebook.connect('hide', self._on_hide)
# Create the treestore
# cat, value, label, count, pixmap, visible
self.treestore = gtk.TreeStore(str, str, str, int, gtk.gdk.Pixbuf, bool)
# Create the column and cells
- column = gtk.TreeViewColumn("Filters")
+ column = gtk.TreeViewColumn('Filters')
column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
# icon cell
self.cell_pix = gtk.CellRendererPixbuf()
@@ -93,10 +93,10 @@ class FilterTreeView(component.Component):
class "GtkTreeView" style "treeview-style" """)
self.treeview.set_model(self.treestore)
- self.treeview.get_selection().connect("changed", self.on_selection_changed)
+ self.treeview.get_selection().connect('changed', self.on_selection_changed)
self.create_model_filter()
- self.treeview.connect("button-press-event", self.on_button_press_event)
+ self.treeview.connect('button-press-event', self.on_button_press_event)
# colors using current theme.
style = self.window.window.get_style()
@@ -105,12 +105,12 @@ class FilterTreeView(component.Component):
# filtertree menu
builder = gtk.Builder()
- builder.add_from_file(resource_filename("deluge.ui.gtkui", os.path.join("glade", "filtertree_menu.ui")))
- self.menu = builder.get_object("filtertree_menu")
+ builder.add_from_file(resource_filename('deluge.ui.gtkui', os.path.join('glade', 'filtertree_menu.ui')))
+ self.menu = builder.get_object('filtertree_menu')
builder.connect_signals({
- "select_all": self.on_select_all,
- "pause_all": self.on_pause_all,
- "resume_all": self.on_resume_all
+ 'select_all': self.on_select_all,
+ 'pause_all': self.on_pause_all,
+ 'resume_all': self.on_resume_all
})
self.default_menu_items = self.menu.get_children()
@@ -121,19 +121,19 @@ class FilterTreeView(component.Component):
self.filters = {}
# initial order of state filter:
- self.cat_nodes["state"] = self.treestore.append(None, ["cat", "state", _("States"), 0, None, False])
- for state in ["All", "Active"] + TORRENT_STATE:
- self.update_row("state", state, 0, _(state))
+ self.cat_nodes['state'] = self.treestore.append(None, ['cat', 'state', _('States'), 0, None, False])
+ 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.update_row("tracker_host", "All", 0, _("All"))
- self.update_row("tracker_host", "Error", 0, _("Error"))
- self.update_row("tracker_host", "", 0, _("None"))
+ 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'))
- self.cat_nodes["owner"] = self.treestore.append(None, ["cat", "owner", _("Owner"), 0, None, False])
- self.update_row("owner", "localclient", 0, _("Admin"))
- self.update_row("owner", "", 0, _("None"))
+ self.cat_nodes['owner'] = self.treestore.append(None, ['cat', 'owner', _('Owner'), 0, None, False])
+ self.update_row('owner', 'localclient', 0, _('Admin'))
+ self.update_row('owner', '', 0, _('None'))
# We set to this expand the rows on start-up
self.expand_rows = True
@@ -153,9 +153,9 @@ class FilterTreeView(component.Component):
for cat in filter_items:
if cat not in self.cat_nodes:
label = _(cat)
- if cat == "label":
- label = _("Labels")
- self.cat_nodes[cat] = self.treestore.append(None, ["cat", cat, label, 0, None, False])
+ if cat == 'label':
+ label = _('Labels')
+ self.cat_nodes[cat] = self.treestore.append(None, ['cat', cat, label, 0, None, False])
# update rows
visible_filters = []
@@ -191,18 +191,18 @@ class FilterTreeView(component.Component):
else:
pix = self.get_pixmap(cat, value)
- if value == "":
- if cat == "label":
- label = _("No Label")
- elif cat == "owner":
- label = _("No Owner")
+ if value == '':
+ if cat == 'label':
+ label = _('No Label')
+ elif cat == 'owner':
+ label = _('No Owner')
elif not label and value:
label = _(value)
row = self.treestore.append(self.cat_nodes[cat], [cat, value, label, count, pix, True])
self.filters[(cat, value)] = row
- if cat == "tracker_host" and value not in ("All", "Error") and value:
+ if cat == 'tracker_host' and value not in ('All', 'Error') and value:
d = self.tracker_icons.fetch(value)
d.addCallback(on_get_icon)
@@ -216,35 +216,35 @@ class FilterTreeView(component.Component):
# Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
original_filters = warnings.filters[:]
- warnings.simplefilter("ignore")
+ warnings.simplefilter('ignore')
try:
pix = model.get_value(row, 4)
finally:
warnings.filters = original_filters
- self.cell_pix.set_property("visible", True if pix else False)
+ self.cell_pix.set_property('visible', True if pix else False)
- if cat == "cat":
- self.cell_count.set_property("visible", False)
+ if cat == 'cat':
+ self.cell_count.set_property('visible', False)
cell.set_padding(10, 2)
- label = "<b>%s</b>" % label
+ label = '<b>%s</b>' % label
else:
- count_txt = "<small>%s</small>" % count
+ count_txt = '<small>%s</small>' % count
self.cell_count.set_property('markup', count_txt)
- self.cell_count.set_property("visible", True)
+ self.cell_count.set_property('visible', True)
cell.set_padding(2, 1)
cell.set_property('markup', label)
def get_pixmap(self, cat, value):
pix = None
- if cat == "state":
+ if cat == 'state':
pix = STATE_PIX.get(value, None)
- elif cat == "tracker_host":
+ elif cat == 'tracker_host':
pix = TRACKER_PIX.get(value, None)
if pix:
try:
- return gtk.gdk.pixbuf_new_from_file(get_pixmap("%s16.png" % pix))
+ return gtk.gdk.pixbuf_new_from_file(get_pixmap('%s16.png' % pix))
except GError as ex:
log.warning(ex)
return self.get_transparent_pix(16, 16)
@@ -271,17 +271,17 @@ class FilterTreeView(component.Component):
try:
(model, row) = self.treeview.get_selection().get_selected()
if not row:
- log.debug("nothing selected")
+ log.debug('nothing selected')
return
cat = model.get_value(row, 0)
value = model.get_value(row, 1)
filter_dict = {cat: [value]}
- if value == "All" or cat == "cat":
+ if value == 'All' or cat == 'cat':
filter_dict = {}
- component.get("TorrentView").set_filter(filter_dict)
+ component.get('TorrentView').set_filter(filter_dict)
self.selected_path = model.get_path(row)
@@ -293,11 +293,11 @@ class FilterTreeView(component.Component):
def update(self):
try:
hide_cat = []
- if not self.config["sidebar_show_trackers"]:
- 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"],
+ if not self.config['sidebar_show_trackers']:
+ 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)
except Exception as ex:
log.debug(ex)
@@ -314,7 +314,7 @@ class FilterTreeView(component.Component):
if event.button == 1:
# Prevent selecting a category label
- if cat == "cat":
+ if cat == 'cat':
if self.treeview.row_expanded(path):
self.treeview.collapse_row(path)
else:
@@ -342,37 +342,37 @@ class FilterTreeView(component.Component):
self.menu.popup(None, None, None, event.button, event.time)
self.menu.show()
- if cat == "cat":
+ if cat == 'cat':
# Do not select the row
return True
def set_menu_sensitivity(self):
# select-all/pause/resume
- sensitive = (self.cat != "cat" and self.count != 0)
+ sensitive = (self.cat != 'cat' and self.count != 0)
for item in self.default_menu_items:
item.set_sensitive(sensitive)
def select_all(self):
- "for use in popup menu"
- component.get("TorrentView").treeview.get_selection().select_all()
+ 'for use in popup menu'
+ component.get('TorrentView').treeview.get_selection().select_all()
def on_select_all(self, event):
self.select_all()
def on_pause_all(self, event):
self.select_all()
- func = getattr(component.get("MenuBar"), "on_menuitem_%s_activate" % "pause")
+ func = getattr(component.get('MenuBar'), 'on_menuitem_%s_activate' % 'pause')
func(event)
def on_resume_all(self, event):
self.select_all()
- func = getattr(component.get("MenuBar"), "on_menuitem_%s_activate" % "resume")
+ func = getattr(component.get('MenuBar'), 'on_menuitem_%s_activate' % 'resume')
func(event)
def _on_hide(self, *args):
self.select_default_filter()
def select_default_filter(self):
- row = self.filters[("state", "All")]
+ row = self.filters[('state', 'All')]
path = self.treestore.get_path(row)
self.treeview.get_selection().select_path(path)
diff --git a/deluge/ui/gtkui/gtkui.py b/deluge/ui/gtkui/gtkui.py
index b9201611b..e676f76b2 100644
--- a/deluge/ui/gtkui/gtkui.py
+++ b/deluge/ui/gtkui/gtkui.py
@@ -56,7 +56,7 @@ from deluge.ui.tracker_icons import TrackerIcons
from deluge.ui.util import lang
-gobject.set_prgname("deluge")
+gobject.set_prgname('deluge')
log = logging.getLogger(__name__)
@@ -71,64 +71,64 @@ except ImportError:
DEFAULT_PREFS = {
- "standalone": True,
- "interactive_add": True,
- "focus_add_dialog": True,
- "enable_system_tray": True,
- "close_to_tray": False,
- "start_in_tray": False,
- "enable_appindicator": False,
- "lock_tray": False,
- "tray_password": "",
- "check_new_releases": True,
- "default_load_path": None,
- "window_maximized": False,
- "window_x_pos": 0,
- "window_y_pos": 0,
- "window_width": 640,
- "window_height": 480,
- "pref_dialog_width": None,
- "pref_dialog_height": None,
- "edit_trackers_dialog_width": None,
- "edit_trackers_dialog_height": None,
- "window_pane_position": 235,
- "tray_download_speed_list": [5.0, 10.0, 30.0, 80.0, 300.0],
- "tray_upload_speed_list": [5.0, 10.0, 30.0, 80.0, 300.0],
- "connection_limit_list": [50, 100, 200, 300, 500],
- "enabled_plugins": [],
- "show_connection_manager_on_start": True,
- "autoconnect": False,
- "autoconnect_host_id": None,
- "autostart_localhost": False,
- "autoadd_queued": False,
- "choose_directory_dialog_path": deluge.common.get_default_download_dir(),
- "show_new_releases": True,
- "ntf_tray_blink": True,
- "ntf_sound": False,
- "ntf_sound_path": deluge.common.get_default_download_dir(),
- "ntf_popup": False,
- "ntf_email": False,
- "ntf_email_add": "",
- "ntf_username": "",
- "ntf_pass": "",
- "ntf_server": "",
- "ntf_security": None,
- "show_sidebar": True,
- "show_toolbar": True,
- "show_statusbar": True,
- "sidebar_show_zero": False,
- "sidebar_show_trackers": True,
- "sidebar_show_owners": True,
- "sidebar_position": 170,
- "show_rate_in_title": False,
- "createtorrent.trackers": [],
- "show_piecesbar": False,
- "pieces_color_missing": [65535, 0, 0],
- "pieces_color_waiting": [4874, 56494, 0],
- "pieces_color_downloading": [65535, 55255, 0],
- "pieces_color_completed": [4883, 26985, 56540],
- "focus_main_window_on_add": True,
- "language": None,
+ 'standalone': True,
+ 'interactive_add': True,
+ 'focus_add_dialog': True,
+ 'enable_system_tray': True,
+ 'close_to_tray': False,
+ 'start_in_tray': False,
+ 'enable_appindicator': False,
+ 'lock_tray': False,
+ 'tray_password': '',
+ 'check_new_releases': True,
+ 'default_load_path': None,
+ 'window_maximized': False,
+ 'window_x_pos': 0,
+ 'window_y_pos': 0,
+ 'window_width': 640,
+ 'window_height': 480,
+ 'pref_dialog_width': None,
+ 'pref_dialog_height': None,
+ 'edit_trackers_dialog_width': None,
+ 'edit_trackers_dialog_height': None,
+ 'window_pane_position': 235,
+ 'tray_download_speed_list': [5.0, 10.0, 30.0, 80.0, 300.0],
+ 'tray_upload_speed_list': [5.0, 10.0, 30.0, 80.0, 300.0],
+ 'connection_limit_list': [50, 100, 200, 300, 500],
+ 'enabled_plugins': [],
+ 'show_connection_manager_on_start': True,
+ 'autoconnect': False,
+ 'autoconnect_host_id': None,
+ 'autostart_localhost': False,
+ 'autoadd_queued': False,
+ 'choose_directory_dialog_path': deluge.common.get_default_download_dir(),
+ 'show_new_releases': True,
+ 'ntf_tray_blink': True,
+ 'ntf_sound': False,
+ 'ntf_sound_path': deluge.common.get_default_download_dir(),
+ 'ntf_popup': False,
+ 'ntf_email': False,
+ 'ntf_email_add': '',
+ 'ntf_username': '',
+ 'ntf_pass': '',
+ 'ntf_server': '',
+ 'ntf_security': None,
+ 'show_sidebar': True,
+ 'show_toolbar': True,
+ 'show_statusbar': True,
+ 'sidebar_show_zero': False,
+ 'sidebar_show_trackers': True,
+ 'sidebar_show_owners': True,
+ 'sidebar_position': 170,
+ 'show_rate_in_title': False,
+ 'createtorrent.trackers': [],
+ 'show_piecesbar': False,
+ 'pieces_color_missing': [65535, 0, 0],
+ 'pieces_color_waiting': [4874, 56494, 0],
+ 'pieces_color_downloading': [65535, 55255, 0],
+ 'pieces_color_completed': [4883, 26985, 56540],
+ 'focus_main_window_on_add': True,
+ 'language': None,
}
@@ -147,10 +147,10 @@ class GtkUI(object):
SetConsoleCtrlHandler(on_die, True)
log.debug("Win32 'die' handler registered")
elif deluge.common.osx_check():
- if gtk.gdk.WINDOWING == "quartz":
+ if gtk.gdk.WINDOWING == 'quartz':
import gtkosx_application
self.osxapp = gtkosx_application.gtkosx_application_get()
- self.osxapp.connect("NSApplicationWillTerminate", on_die)
+ self.osxapp.connect('NSApplicationWillTerminate', on_die)
log.debug("OSX quartz 'die' handler registered")
# Set process name again to fix gtk issue
@@ -161,15 +161,15 @@ class GtkUI(object):
associate_magnet_links(False)
# Make sure gtkui.conf has at least the defaults set
- self.config = ConfigManager("gtkui.conf", DEFAULT_PREFS)
+ self.config = ConfigManager('gtkui.conf', DEFAULT_PREFS)
# Make sure the gtkui state folder has been created
- if not os.path.exists(os.path.join(get_config_dir(), "gtkui_state")):
- os.makedirs(os.path.join(get_config_dir(), "gtkui_state"))
+ if not os.path.exists(os.path.join(get_config_dir(), 'gtkui_state')):
+ os.makedirs(os.path.join(get_config_dir(), 'gtkui_state'))
# Set language
- if self.config["language"] is not None:
- lang.set_language(self.config["language"])
+ if self.config['language'] is not None:
+ lang.set_language(self.config['language'])
# Start the IPC Interface before anything else.. Just in case we are
# already running.
@@ -197,13 +197,13 @@ class GtkUI(object):
self.statusbar = StatusBar()
self.addtorrentdialog = AddTorrentDialog()
- if deluge.common.osx_check() and gtk.gdk.WINDOWING == "quartz":
+ if deluge.common.osx_check() and gtk.gdk.WINDOWING == 'quartz':
def nsapp_open_file(osxapp, filename):
# Ignore command name which is raised at app launch (python opening main script).
if filename == sys.argv[0]:
return True
process_args([filename])
- self.osxapp.connect("NSApplicationOpenFile", nsapp_open_file)
+ self.osxapp.connect('NSApplicationOpenFile', nsapp_open_file)
from deluge.ui.gtkui.menubar_osx import menubar_osx
menubar_osx(self, self.osxapp)
self.osxapp.ready()
@@ -221,7 +221,7 @@ class GtkUI(object):
self.closing = False
# Twisted catches signals to terminate, so have it call a pre_shutdown method.
- reactor.addSystemEventTrigger("before", "gtkui_close", self.close)
+ reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)
def gtkui_sigint_handler(num, frame):
log.debug("SIGINT signal caught - firing event: 'gtkui_close'")
@@ -240,7 +240,7 @@ class GtkUI(object):
gtk.gdk.threads_leave()
def shutdown(self, *args, **kwargs):
- log.debug("GTKUI shutting down...")
+ log.debug('GTKUI shutting down...')
# Shutdown all components
if client.is_standalone:
return component.shutdown()
@@ -276,21 +276,21 @@ class GtkUI(object):
self.daemon_bps = (t, sent, recv)
sent_rate = deluge.common.fspeed(delta_sent / delta_time)
recv_rate = deluge.common.fspeed(delta_recv / delta_time)
- log.debug("RPC: Sent %s (%s) Recv %s (%s)",
+ log.debug('RPC: Sent %s (%s) Recv %s (%s)',
deluge.common.fsize(sent), sent_rate, deluge.common.fsize(recv), recv_rate)
def _on_reactor_start(self):
- log.debug("_on_reactor_start")
+ log.debug('_on_reactor_start')
self.mainwindow.first_show()
- if self.config["standalone"]:
+ if self.config['standalone']:
def on_dialog_response(response):
if response != gtk.RESPONSE_YES:
# The user does not want to turn Standalone Mode off, so just quit
self.mainwindow.quit()
return
# Turning off standalone
- self.config["standalone"] = False
+ self.config['standalone'] = False
self.__start_thinclient()
try:
@@ -298,19 +298,19 @@ class GtkUI(object):
client.start_standalone()
except DaemonRunningError:
d = YesNoDialog(
- _("Switch to Thin Client Mode?"),
- _("A Deluge daemon process (deluged) is already running. "
- "To use Standalone mode, stop this daemon and restart Deluge."
- "\n\n"
- "Continue in Thin Client mode?")).run()
+ _('Switch to Thin Client Mode?'),
+ _('A Deluge daemon process (deluged) is already running. '
+ 'To use Standalone mode, stop this daemon and restart Deluge.'
+ '\n\n'
+ 'Continue in Thin Client mode?')).run()
d.addCallback(on_dialog_response)
except ImportError as ex:
- if "No module named libtorrent" in ex.message:
+ if 'No module named libtorrent' in ex.message:
d = YesNoDialog(
- _("Switch to Thin Client Mode?"),
- _("Only Thin Client mode is available because libtorrent is not installed."
- "\n\n"
- "To use Deluge Standalone mode, please install libtorrent.")).run()
+ _('Switch to Thin Client Mode?'),
+ _('Only Thin Client mode is available because libtorrent is not installed.'
+ '\n\n'
+ 'To use Deluge Standalone mode, please install libtorrent.')).run()
d.addCallback(on_dialog_response)
else:
raise ex
@@ -321,15 +321,15 @@ class GtkUI(object):
import traceback
tb = sys.exc_info()
ed = ErrorDialog(
- _("Error Starting Core"),
- _("An error occurred starting the core component required to run Deluge in Standalone mode."
- "\n\n"
- "Please see the details below for more information."), details=traceback.format_exc(tb[2])).run()
+ _('Error Starting Core'),
+ _('An error occurred starting the core component required to run Deluge in Standalone mode.'
+ '\n\n'
+ 'Please see the details below for more information.'), details=traceback.format_exc(tb[2])).run()
def on_ed_response(response):
d = YesNoDialog(
- _("Switch to Thin Client Mode?"),
- _("Unable to start Standalone mode would you like to continue in Thin Client mode?")
+ _('Switch to Thin Client Mode?'),
+ _('Unable to start Standalone mode would you like to continue in Thin Client mode?')
).run()
d.addCallback(on_dialog_response)
ed.addCallback(on_ed_response)
@@ -339,35 +339,35 @@ class GtkUI(object):
def __start_thinclient(self):
# Autoconnect to a host
- if self.config["autoconnect"]:
+ if self.config['autoconnect']:
def update_connection_manager():
if not self.connectionmanager.running:
return
- self.connectionmanager.builder.get_object("button_refresh").emit("clicked")
+ self.connectionmanager.builder.get_object('button_refresh').emit('clicked')
def close_connection_manager():
if not self.connectionmanager.running:
return
- self.connectionmanager.builder.get_object("button_close").emit("clicked")
+ self.connectionmanager.builder.get_object('button_close').emit('clicked')
- for host_config in self.connectionmanager.config["hosts"]:
+ for host_config in self.connectionmanager.config['hosts']:
hostid, host, port, user, passwd = host_config
- if hostid == self.config["autoconnect_host_id"]:
+ if hostid == self.config['autoconnect_host_id']:
try_connect = True
# Check to see if we need to start the localhost daemon
- if self.config["autostart_localhost"] and host in ("localhost", "127.0.0.1"):
- log.debug("Autostarting localhost:%s", host)
+ if self.config['autostart_localhost'] and host in ('localhost', '127.0.0.1'):
+ log.debug('Autostarting localhost:%s', host)
try_connect = client.start_daemon(
port, get_config_dir()
)
- log.debug("Localhost started: %s", try_connect)
+ log.debug('Localhost started: %s', try_connect)
if not try_connect:
ErrorDialog(
- _("Error Starting Daemon"),
- _("There was an error starting the daemon "
- "process. Try running it from a console "
- "to see if there is an error.")
+ _('Error Starting Daemon'),
+ _('There was an error starting the daemon '
+ 'process. Try running it from a console '
+ 'to see if there is an error.')
).run()
# Daemon Started, let's update it's info
@@ -384,7 +384,7 @@ class GtkUI(object):
return
if reason.check(AuthenticationRequired, BadLoginError):
- log.debug("PasswordRequired exception")
+ log.debug('PasswordRequired exception')
dialog = AuthenticationDialog(reason.value.message, reason.value.username)
def dialog_finished(response_id, host, port):
@@ -396,15 +396,15 @@ class GtkUI(object):
dialog.run().addCallback(dialog_finished, host, port)
return
- log.info("Connection to host failed..")
- log.info("Retrying connection.. Retries left: "
- "%s", try_counter)
+ log.info('Connection to host failed..')
+ log.info('Retrying connection.. Retries left: '
+ '%s', try_counter)
reactor.callLater(0.5, update_connection_manager)
reactor.callLater(0.5, do_connect, try_counter - 1,
host, port, user, passwd)
def do_connect(try_counter, host, port, user, passwd):
- log.debug("Trying to connect to %s@%s:%s",
+ log.debug('Trying to connect to %s@%s:%s',
user, host, port)
d = client.connect(host, port, user, passwd)
d.addCallback(on_connect)
@@ -417,7 +417,7 @@ class GtkUI(object):
)
break
- if self.config["show_connection_manager_on_start"]:
+ if self.config['show_connection_manager_on_start']:
if deluge.common.windows_check():
# Call to simulate() required to workaround showing daemon status (see #2813)
reactor.simulate()
diff --git a/deluge/ui/gtkui/ipcinterface.py b/deluge/ui/gtkui/ipcinterface.py
index 22eaa7a23..ba83c5682 100644
--- a/deluge/ui/gtkui/ipcinterface.py
+++ b/deluge/ui/gtkui/ipcinterface.py
@@ -39,10 +39,10 @@ class IPCProtocolServer(Protocol):
pass
def dataReceived(self, data): # NOQA
- config = ConfigManager("gtkui.conf")
+ config = ConfigManager('gtkui.conf')
data = rencode.loads(data, decode_utf8=True)
- if not data or config["focus_main_window_on_add"]:
- component.get("MainWindow").present()
+ if not data or config['focus_main_window_on_add']:
+ component.get('MainWindow').present()
process_args(data)
@@ -67,25 +67,25 @@ class IPCClientFactory(ClientFactory):
self.stop = False
def clientConnectionFailed(self, connector, reason): # NOQA
- log.warning("Connection to running instance failed.")
+ log.warning('Connection to running instance failed.')
reactor.stop()
class IPCInterface(component.Component):
def __init__(self, args):
- component.Component.__init__(self, "IPCInterface")
+ component.Component.__init__(self, 'IPCInterface')
self.listener = None
- ipc_dir = get_config_dir("ipc")
+ ipc_dir = get_config_dir('ipc')
if not os.path.exists(ipc_dir):
os.makedirs(ipc_dir)
- socket = os.path.join(ipc_dir, "deluge-gtk")
+ socket = os.path.join(ipc_dir, 'deluge-gtk')
if windows_check():
# If we're on windows we need to check the global mutex to see if deluge is
# already running.
import win32event
import win32api
import winerror
- self.mutex = win32event.CreateMutex(None, False, "deluge")
+ self.mutex = win32event.CreateMutex(None, False, 'deluge')
if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS:
# Create listen socket
self.factory = Factory()
@@ -94,7 +94,7 @@ class IPCInterface(component.Component):
port = random.randrange(20000, 65535)
self.listener = reactor.listenTCP(port, self.factory)
# Store the port number in the socket file
- with open(socket, "w") as _file:
+ with open(socket, 'w') as _file:
_file.write(str(port))
# We need to process any args when starting this process
process_args(args)
@@ -105,7 +105,7 @@ class IPCInterface(component.Component):
self.factory = ClientFactory()
self.factory.args = args
self.factory.protocol = IPCProtocolClient
- reactor.connectTCP("127.0.0.1", port, self.factory)
+ reactor.connectTCP('127.0.0.1', port, self.factory)
reactor.run()
sys.exit(0)
else:
@@ -113,8 +113,8 @@ class IPCInterface(component.Component):
restart_tempfile = glob(os.path.join(ipc_dir, 'restart.*'))
for f in restart_tempfile:
os.remove(f)
- lockfile = socket + ".lock"
- log.debug("Checking if lockfile exists: %s", lockfile)
+ lockfile = socket + '.lock'
+ log.debug('Checking if lockfile exists: %s', lockfile)
if os.path.lexists(lockfile):
def delete_lockfile():
log.debug("Removing lockfile since it's stale.")
@@ -122,7 +122,7 @@ class IPCInterface(component.Component):
os.remove(lockfile)
os.remove(socket)
except OSError as ex:
- log.error("Failed to delete lockfile: %s", ex)
+ log.error('Failed to delete lockfile: %s', ex)
try:
os.kill(int(os.readlink(lockfile)), 0)
@@ -130,26 +130,26 @@ class IPCInterface(component.Component):
delete_lockfile()
else:
if restart_tempfile:
- log.warning("Found running PID but it is not a Deluge process, removing lockfile...")
+ log.warning('Found running PID but it is not a Deluge process, removing lockfile...')
delete_lockfile()
try:
self.factory = Factory()
self.factory.protocol = IPCProtocolServer
self.listener = reactor.listenUNIX(socket, self.factory, wantPID=True)
except twisted.internet.error.CannotListenError as ex:
- log.info("Deluge is already running! Sending arguments to running instance...")
+ log.info('Deluge is already running! Sending arguments to running instance...')
self.factory = IPCClientFactory()
self.factory.args = args
reactor.connectUNIX(socket, self.factory, checkPID=True)
reactor.run()
if self.factory.stop:
- log.info("Success sending arguments to running Deluge.")
+ log.info('Success sending arguments to running Deluge.')
import gtk
gtk.gdk.notify_startup_complete()
sys.exit(0)
else:
if restart_tempfile:
- log.error("Deluge restart failed: %s", ex)
+ log.error('Deluge restart failed: %s', ex)
sys.exit(1)
else:
log.warning('Restarting Deluge... (%s)', ex)
@@ -171,49 +171,49 @@ def process_args(args):
"""Process arguments sent to already running Deluge"""
# Make sure args is a list
args = list(args)
- log.debug("Processing args from other process: %s", args)
+ log.debug('Processing args from other process: %s', args)
if not client.connected():
# We're not connected so add these to the queue
- log.debug("Not connected to host.. Adding to queue.")
- component.get("QueuedTorrents").add_to_queue(args)
+ log.debug('Not connected to host.. Adding to queue.')
+ component.get('QueuedTorrents').add_to_queue(args)
return
- config = ConfigManager("gtkui.conf")
+ config = ConfigManager('gtkui.conf')
for arg in args:
if not arg.strip():
continue
- log.debug("arg: %s", arg)
+ log.debug('arg: %s', arg)
if is_url(arg):
- log.debug("Attempting to add url (%s) from external source...", arg)
- if config["interactive_add"]:
- component.get("AddTorrentDialog").add_from_url(arg)
- component.get("AddTorrentDialog").show(config["focus_add_dialog"])
+ log.debug('Attempting to add url (%s) from external source...', arg)
+ if config['interactive_add']:
+ component.get('AddTorrentDialog').add_from_url(arg)
+ component.get('AddTorrentDialog').show(config['focus_add_dialog'])
else:
client.core.add_torrent_url(arg, None)
elif is_magnet(arg):
- log.debug("Attempting to add magnet (%s) from external source...", arg)
- if config["interactive_add"]:
- component.get("AddTorrentDialog").add_from_magnets([arg])
- component.get("AddTorrentDialog").show(config["focus_add_dialog"])
+ log.debug('Attempting to add magnet (%s) from external source...', arg)
+ if config['interactive_add']:
+ component.get('AddTorrentDialog').add_from_magnets([arg])
+ component.get('AddTorrentDialog').show(config['focus_add_dialog'])
else:
client.core.add_torrent_magnet(arg, {})
else:
- log.debug("Attempting to add file (%s) from external source...", arg)
- if urlparse(arg).scheme == "file":
+ log.debug('Attempting to add file (%s) from external source...', arg)
+ if urlparse(arg).scheme == 'file':
arg = url2pathname(urlparse(arg).path)
path = os.path.abspath(decode_string(arg))
if not os.path.exists(path):
- log.error("No such file: %s", path)
+ log.error('No such file: %s', path)
continue
- if config["interactive_add"]:
- component.get("AddTorrentDialog").add_from_files([path])
- component.get("AddTorrentDialog").show(config["focus_add_dialog"])
+ if config['interactive_add']:
+ component.get('AddTorrentDialog').add_from_files([path])
+ component.get('AddTorrentDialog').show(config['focus_add_dialog'])
else:
- with open(path, "rb") as _file:
+ with open(path, 'rb') as _file:
filedump = base64.encodestring(_file.read())
client.core.add_torrent_file(os.path.split(path)[-1], filedump, None)
diff --git a/deluge/ui/gtkui/listview.py b/deluge/ui/gtkui/listview.py
index 004560973..27ea626b8 100644
--- a/deluge/ui/gtkui/listview.py
+++ b/deluge/ui/gtkui/listview.py
@@ -124,7 +124,7 @@ class ListView(object):
self.set_attributes(renderer, **kw)
def __init__(self, treeview_widget=None, state_file=None):
- log.debug("ListView initialized..")
+ log.debug('ListView initialized..')
if treeview_widget is not None:
# User supplied a treeview widget
@@ -169,7 +169,7 @@ class ListView(object):
self.default_sort_column_id = None
# Create the model filter and column
- self.add_bool_column("filter", hidden=True)
+ self.add_bool_column('filter', hidden=True)
def create_model_filter(self):
"""create new filter-model
@@ -177,10 +177,10 @@ 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)
+ self.model_filter.connect('sort-column-changed', self.on_model_sort_changed)
+ self.model_filter.connect('row-inserted', self.on_model_row_inserted)
self.treeview.set_model(self.model_filter)
self.set_sort_functions()
self.set_model_sort()
@@ -350,7 +350,7 @@ class ListView(object):
if column.column.get_visible() is True:
menuitem.set_active(True)
# Connect to the 'toggled' event
- menuitem.connect("toggled", self.on_menuitem_toggled)
+ menuitem.connect('toggled', self.on_menuitem_toggled)
# Add the new checkmenuitem to the menu
menu.append(menuitem)
@@ -388,23 +388,23 @@ class ListView(object):
column = self.columns[header]
tree_column = self.columns[header].column
- if column.column_type == "text":
+ if column.column_type == 'text':
if add:
tree_column.pack_start(column.renderer)
tree_column.set_col_attributes(column.renderer, add=add,
text=column.column_indices[column.text_index])
- elif column.column_type == "bool":
+ elif column.column_type == 'bool':
if add:
tree_column.pack_start(column.renderer)
tree_column.set_col_attributes(column.renderer, active=column.column_indices[0])
- elif column.column_type == "func":
+ elif column.column_type == 'func':
if add:
tree_column.pack_start(column.renderer, True)
indice_arg = column.column_indices[0]
if len(column.column_indices) > 1:
indice_arg = tuple(column.column_indices)
tree_column.set_cell_data_func(column.renderer, column.data_func, indice_arg)
- elif column.column_type == "progress":
+ elif column.column_type == 'progress':
if add:
tree_column.pack_start(column.renderer)
if column.data_func is None:
@@ -414,7 +414,7 @@ class ListView(object):
else:
tree_column.set_cell_data_func(column.renderer, column.data_func,
tuple(column.column_indices))
- elif column.column_type == "texticon":
+ 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)
@@ -563,7 +563,7 @@ 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",
+ 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.
@@ -578,7 +578,7 @@ class ListView(object):
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):
+ 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,
@@ -587,7 +587,7 @@ class ListView(object):
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):
+ 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."""
@@ -600,7 +600,7 @@ class ListView(object):
def add_progress_column(self, header, col_types=None, sortid=0,
hidden=False, position=None, status_field=None,
- function=None, column_type="progress",
+ function=None, column_type='progress',
tooltip=None, sort_func=None, default=True):
"""Add a progress column to the listview."""
@@ -616,7 +616,7 @@ class ListView(object):
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,
+ 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:
@@ -632,7 +632,7 @@ class ListView(object):
return True
def on_keypress_search_by_name(self, model, column, key, _iter):
- torrent_name_col = self.columns["Name"].column_indices[1]
+ torrent_name_col = self.columns['Name'].column_indices[1]
return not model[_iter][torrent_name_col].lower().startswith(key.lower())
def restore_columns_order_from_state(self):
diff --git a/deluge/ui/gtkui/mainwindow.py b/deluge/ui/gtkui/mainwindow.py
index c365daac5..a02a2dd06 100644
--- a/deluge/ui/gtkui/mainwindow.py
+++ b/deluge/ui/gtkui/mainwindow.py
@@ -44,7 +44,7 @@ class _GtkBuilderSignalsHolder(object):
for name, handler in mapping_or_class.iteritems():
if hasattr(self, name):
raise RuntimeError(
- "A handler for signal %r has already been registered: %s" %
+ 'A handler for signal %r has already been registered: %s' %
(name, getattr(self, name))
)
setattr(self, name, handler)
@@ -53,7 +53,7 @@ class _GtkBuilderSignalsHolder(object):
if not name.startswith('on_'):
continue
if hasattr(self, name):
- raise RuntimeError("A handler for signal %r has already been registered: %s" %
+ raise RuntimeError('A handler for signal %r has already been registered: %s' %
(name, getattr(self, name)))
setattr(self, name, getattr(mapping_or_class, name))
@@ -62,8 +62,8 @@ class MainWindow(component.Component):
def __init__(self):
if wnck:
self.screen = wnck.screen_get_default()
- component.Component.__init__(self, "MainWindow", interval=2)
- self.config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'MainWindow', interval=2)
+ self.config = ConfigManager('gtkui.conf')
self.gtk_builder_signals_holder = _GtkBuilderSignalsHolder()
self.main_builder = gtk.Builder()
# Patch this GtkBuilder to avoid connecting signals from elsewhere
@@ -74,32 +74,32 @@ 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 "
+ 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 the gtk builder file for the main window
self.main_builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "main_window.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'main_window.ui')))
# The new release dialog
self.main_builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "main_window.new_release.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'main_window.new_release.ui')))
# The tabs
self.main_builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.ui')))
# The tabs file menu
self.main_builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.menu_file.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.menu_file.ui')))
# The tabs peer menu
self.main_builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.menu_peer.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.menu_peer.ui')))
- self.window = self.main_builder.get_object("main_window")
+ self.window = self.main_builder.get_object('main_window')
self.window.set_icon(deluge.ui.gtkui.common.get_deluge_icon())
- self.vpaned = self.main_builder.get_object("vpaned")
+ self.vpaned = self.main_builder.get_object('vpaned')
- self.initial_vpaned_position = self.config["window_pane_position"]
+ self.initial_vpaned_position = self.config['window_pane_position']
# Load the window state
self.load_window_state()
@@ -111,25 +111,25 @@ class MainWindow(component.Component):
self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, [('text/uri-list', 0, 80)], gtk.gdk.ACTION_COPY)
# Connect events
- self.window.connect("window-state-event", self.on_window_state_event)
- self.window.connect("configure-event", self.on_window_configure_event)
- self.window.connect("delete-event", self.on_window_delete_event)
- self.window.connect("drag-data-received", self.on_drag_data_received_event)
- self.vpaned.connect("notify::position", self.on_vpaned_position_event)
- self.window.connect("expose-event", self.on_expose_event)
+ self.window.connect('window-state-event', self.on_window_state_event)
+ self.window.connect('configure-event', self.on_window_configure_event)
+ self.window.connect('delete-event', self.on_window_delete_event)
+ self.window.connect('drag-data-received', self.on_drag_data_received_event)
+ self.vpaned.connect('notify::position', self.on_vpaned_position_event)
+ self.window.connect('expose-event', self.on_expose_event)
- self.config.register_set_function("show_rate_in_title", self._on_set_show_rate_in_title, apply_now=False)
+ self.config.register_set_function('show_rate_in_title', self._on_set_show_rate_in_title, apply_now=False)
- client.register_event_handler("NewVersionAvailableEvent", self.on_newversionavailable_event)
+ client.register_event_handler('NewVersionAvailableEvent', self.on_newversionavailable_event)
def connect_signals(self, mapping_or_class):
self.gtk_builder_signals_holder.connect_signals(mapping_or_class)
def first_show(self):
- if not(self.config["start_in_tray"] and
- self.config["enable_system_tray"]) and not \
- self.window.get_property("visible"):
- log.debug("Showing window")
+ if not(self.config['start_in_tray'] and
+ self.config['enable_system_tray']) and not \
+ self.window.get_property('visible'):
+ log.debug('Showing window')
self.main_builder.prev_connect_signals(self.gtk_builder_signals_holder)
self.vpaned.set_position(self.initial_vpaned_position)
self.show()
@@ -138,18 +138,18 @@ class MainWindow(component.Component):
def show(self):
try:
- component.resume("TorrentView")
- component.resume("StatusBar")
- component.resume("TorrentDetails")
+ component.resume('TorrentView')
+ component.resume('StatusBar')
+ component.resume('TorrentDetails')
except Exception:
pass
self.window.show()
def hide(self):
- component.pause("TorrentView")
- component.get("TorrentView").save_state()
- component.pause("StatusBar")
- component.pause("TorrentDetails")
+ component.pause('TorrentView')
+ component.get('TorrentView').save_state()
+ component.pause('StatusBar')
+ component.pause('TorrentDetails')
# Store the x, y positions for when we restore the window
self.window_x_pos = self.window.get_position()[0]
self.window_y_pos = self.window.get_position()[1]
@@ -160,29 +160,29 @@ class MainWindow(component.Component):
# Restore the proper x,y coords for the window prior to showing it
try:
if self.window_x_pos == -32000 or self.window_y_pos == -32000:
- self.config["window_x_pos"] = 0
- self.config["window_y_pos"] = 0
+ self.config['window_x_pos'] = 0
+ self.config['window_y_pos'] = 0
else:
- self.config["window_x_pos"] = self.window_x_pos
- self.config["window_y_pos"] = self.window_y_pos
+ self.config['window_x_pos'] = self.window_x_pos
+ self.config['window_y_pos'] = self.window_y_pos
except Exception:
pass
try:
- component.resume("TorrentView")
- component.resume("StatusBar")
- component.resume("TorrentDetails")
+ component.resume('TorrentView')
+ component.resume('StatusBar')
+ component.resume('TorrentDetails')
except Exception:
pass
self.window.present()
self.load_window_state()
- if self.config["lock_tray"] and not self.visible():
- dialog = PasswordDialog(_("Enter your password to show Deluge..."))
+ if self.config['lock_tray'] and not self.visible():
+ dialog = PasswordDialog(_('Enter your password to show Deluge...'))
def on_dialog_response(response_id):
if response_id == gtk.RESPONSE_OK:
- if self.config["tray_password"] == sha(dialog.get_password()).hexdigest():
+ if self.config['tray_password'] == sha(dialog.get_password()).hexdigest():
restore()
dialog.run().addCallback(on_dialog_response)
else:
@@ -194,7 +194,7 @@ class MainWindow(component.Component):
def visible(self):
"""Returns True if window is visible, False if not."""
- return self.window.get_property("visible")
+ return self.window.get_property('visible')
def get_builder(self):
"""Returns a reference to the main window GTK builder object."""
@@ -212,7 +212,7 @@ class MainWindow(component.Component):
try:
reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')
except ReactorNotRunning:
- log.debug("Attempted to stop the reactor but it is not running...")
+ log.debug('Attempted to stop the reactor but it is not running...')
if shutdown:
client.daemon.shutdown().addCallback(stop_gtk_reactor)
@@ -221,59 +221,59 @@ class MainWindow(component.Component):
else:
stop_gtk_reactor()
- if self.config["lock_tray"] and not self.visible():
- dialog = PasswordDialog(_("Enter your password to Quit Deluge..."))
+ if self.config['lock_tray'] and not self.visible():
+ dialog = PasswordDialog(_('Enter your password to Quit Deluge...'))
def on_dialog_response(response_id):
if response_id == gtk.RESPONSE_OK:
- if self.config["tray_password"] == sha(dialog.get_password()).hexdigest():
+ if self.config['tray_password'] == sha(dialog.get_password()).hexdigest():
quit_gtkui()
dialog.run().addCallback(on_dialog_response)
else:
quit_gtkui()
def load_window_state(self):
- x = self.config["window_x_pos"]
- y = self.config["window_y_pos"]
- w = self.config["window_width"]
- h = self.config["window_height"]
+ x = self.config['window_x_pos']
+ y = self.config['window_y_pos']
+ w = self.config['window_width']
+ h = self.config['window_height']
self.window.move(x, y)
self.window.resize(w, h)
- if self.config["window_maximized"]:
+ if self.config['window_maximized']:
self.window.maximize()
def on_window_configure_event(self, widget, event):
- if not self.config["window_maximized"] and self.visible:
- self.config["window_x_pos"] = self.window.get_position()[0]
- self.config["window_y_pos"] = self.window.get_position()[1]
- self.config["window_width"] = event.width
- self.config["window_height"] = event.height
+ if not self.config['window_maximized'] and self.visible:
+ self.config['window_x_pos'] = self.window.get_position()[0]
+ self.config['window_y_pos'] = self.window.get_position()[1]
+ self.config['window_width'] = event.width
+ self.config['window_height'] = event.height
def on_window_state_event(self, widget, event):
if event.changed_mask & gtk.gdk.WINDOW_STATE_MAXIMIZED:
if event.new_window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED:
- log.debug("pos: %s", self.window.get_position())
- self.config["window_maximized"] = True
+ log.debug('pos: %s', self.window.get_position())
+ self.config['window_maximized'] = True
elif not event.new_window_state & gtk.gdk.WINDOW_STATE_WITHDRAWN:
- self.config["window_maximized"] = False
+ self.config['window_maximized'] = False
if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED:
if event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED:
- log.debug("MainWindow is minimized..")
- component.pause("TorrentView")
- component.pause("StatusBar")
+ log.debug('MainWindow is minimized..')
+ component.pause('TorrentView')
+ component.pause('StatusBar')
self.is_minimized = True
else:
- log.debug("MainWindow is not minimized..")
+ log.debug('MainWindow is not minimized..')
try:
- component.resume("TorrentView")
- component.resume("StatusBar")
+ component.resume('TorrentView')
+ component.resume('StatusBar')
except Exception:
pass
self.is_minimized = False
return False
def on_window_delete_event(self, widget, event):
- if self.config["close_to_tray"] and self.config["enable_system_tray"]:
+ if self.config['close_to_tray'] and self.config['enable_system_tray']:
self.hide()
else:
self.quit()
@@ -281,10 +281,10 @@ class MainWindow(component.Component):
return True
def on_vpaned_position_event(self, obj, param):
- self.config["window_pane_position"] = self.vpaned.get_position()
+ self.config['window_pane_position'] = self.vpaned.get_position()
def on_drag_data_received_event(self, widget, drag_context, x, y, selection_data, info, timestamp):
- log.debug("Selection(s) dropped on main window %s", selection_data.data)
+ log.debug('Selection(s) dropped on main window %s', selection_data.data)
if selection_data.get_uris():
process_args(selection_data.get_uris())
else:
@@ -292,29 +292,29 @@ class MainWindow(component.Component):
drag_context.finish(True, True)
def on_expose_event(self, widget, event):
- component.get("SystemTray").blink(False)
+ component.get('SystemTray').blink(False)
def stop(self):
- self.window.set_title("Deluge")
+ self.window.set_title('Deluge')
def update(self):
# Update the window title
def _on_get_session_status(status):
- download_rate = deluge.common.fspeed(status["payload_download_rate"], precision=0, shortform=True)
- upload_rate = deluge.common.fspeed(status["payload_upload_rate"], precision=0, shortform=True)
- 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)
+ download_rate = deluge.common.fspeed(status['payload_download_rate'], precision=0, shortform=True)
+ upload_rate = deluge.common.fspeed(status['payload_upload_rate'], precision=0, shortform=True)
+ 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)
def _on_set_show_rate_in_title(self, key, value):
if value:
self.update()
else:
- self.window.set_title(_("Deluge"))
+ self.window.set_title(_('Deluge'))
def on_newversionavailable_event(self, new_version):
- if self.config["show_new_releases"]:
+ if self.config['show_new_releases']:
from deluge.ui.gtkui.new_release_dialog import NewReleaseDialog
reactor.callLater(5.0, NewReleaseDialog().show, new_version)
diff --git a/deluge/ui/gtkui/menubar.py b/deluge/ui/gtkui/menubar.py
index b36f45e71..e002d5006 100644
--- a/deluge/ui/gtkui/menubar.py
+++ b/deluge/ui/gtkui/menubar.py
@@ -31,131 +31,131 @@ log = logging.getLogger(__name__)
class MenuBar(component.Component):
def __init__(self):
- log.debug("MenuBar init..")
- component.Component.__init__(self, "MenuBar")
- self.window = component.get("MainWindow")
+ log.debug('MenuBar init..')
+ component.Component.__init__(self, 'MenuBar')
+ self.window = component.get('MainWindow')
self.main_builder = self.window.get_builder()
- self.config = ConfigManager("gtkui.conf")
+ self.config = ConfigManager('gtkui.conf')
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
- torrent_queue_menu = self.builder.get_object("queue_torrent_menu")
- self.builder.get_object("menuitem_queue").set_submenu(torrent_queue_menu)
+ torrent_queue_menu = self.builder.get_object('queue_torrent_menu')
+ self.builder.get_object('menuitem_queue').set_submenu(torrent_queue_menu)
# Attach options torrent menu
- torrent_options_menu = self.builder.get_object("options_torrent_menu")
- self.builder.get_object("menuitem_options").set_submenu(torrent_options_menu)
+ torrent_options_menu = self.builder.get_object('options_torrent_menu')
+ self.builder.get_object('menuitem_options').set_submenu(torrent_options_menu)
- 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"))
+ 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 = gtk.MenuItem(_('Set Unlimited'))
item.set_name(menuitem)
- item.connect("activate", self.on_menuitem_set_unlimited)
+ item.connect('activate', self.on_menuitem_set_unlimited)
submenu.append(item)
- item = gtk.MenuItem(_("Other..."))
+ item = gtk.MenuItem(_('Other...'))
item.set_name(menuitem)
- item.connect("activate", self.on_menuitem_set_other)
+ item.connect('activate', self.on_menuitem_set_other)
submenu.append(item)
submenu.show_all()
self.builder.get_object(menuitem).set_submenu(submenu)
submenu = gtk.Menu()
- item = gtk.MenuItem(_("On"))
- item.connect("activate", self.on_menuitem_set_automanaged_on)
+ item = gtk.MenuItem(_('On'))
+ item.connect('activate', self.on_menuitem_set_automanaged_on)
submenu.append(item)
- item = gtk.MenuItem(_("Off"))
- item.connect("activate", self.on_menuitem_set_automanaged_off)
+ item = gtk.MenuItem(_('Off'))
+ item.connect('activate', self.on_menuitem_set_automanaged_off)
submenu.append(item)
submenu.show_all()
- self.builder.get_object("menuitem_auto_managed").set_submenu(submenu)
+ self.builder.get_object('menuitem_auto_managed').set_submenu(submenu)
submenu = gtk.Menu()
- item = gtk.MenuItem(_("Disable"))
- item.connect("activate", self.on_menuitem_set_stop_seed_at_ratio_disable)
+ item = gtk.MenuItem(_('Disable'))
+ item.connect('activate', self.on_menuitem_set_stop_seed_at_ratio_disable)
submenu.append(item)
- item = gtk.MenuItem(_("Enable..."))
- item.set_name("menuitem_stop_seed_at_ratio")
- item.connect("activate", self.on_menuitem_set_other)
+ item = gtk.MenuItem(_('Enable...'))
+ item.set_name('menuitem_stop_seed_at_ratio')
+ item.connect('activate', self.on_menuitem_set_other)
submenu.append(item)
submenu.show_all()
- self.builder.get_object("menuitem_stop_seed_at_ratio").set_submenu(submenu)
+ self.builder.get_object('menuitem_stop_seed_at_ratio').set_submenu(submenu)
- self.torrentmenu = self.builder.get_object("torrent_menu")
- self.menu_torrent = self.main_builder.get_object("menu_torrent")
+ self.torrentmenu = self.builder.get_object('torrent_menu')
+ self.menu_torrent = self.main_builder.get_object('menu_torrent')
# Attach the torrent_menu to the Torrent file menu
self.menu_torrent.set_submenu(self.torrentmenu)
# Make sure the view menuitems are showing the correct active state
- self.main_builder.get_object("menuitem_toolbar").set_active(self.config["show_toolbar"])
- self.main_builder.get_object("menuitem_sidebar").set_active(self.config["show_sidebar"])
- self.main_builder.get_object("menuitem_statusbar").set_active(self.config["show_statusbar"])
- self.main_builder.get_object("sidebar_show_zero").set_active(self.config["sidebar_show_zero"])
- self.main_builder.get_object("sidebar_show_trackers").set_active(self.config["sidebar_show_trackers"])
- self.main_builder.get_object("sidebar_show_owners").set_active(self.config["sidebar_show_owners"])
+ self.main_builder.get_object('menuitem_toolbar').set_active(self.config['show_toolbar'])
+ self.main_builder.get_object('menuitem_sidebar').set_active(self.config['show_sidebar'])
+ self.main_builder.get_object('menuitem_statusbar').set_active(self.config['show_statusbar'])
+ self.main_builder.get_object('sidebar_show_zero').set_active(self.config['sidebar_show_zero'])
+ self.main_builder.get_object('sidebar_show_trackers').set_active(self.config['sidebar_show_trackers'])
+ self.main_builder.get_object('sidebar_show_owners').set_active(self.config['sidebar_show_owners'])
# Connect main window Signals #
- component.get("MainWindow").connect_signals({
+ component.get('MainWindow').connect_signals({
# File Menu
- "on_menuitem_addtorrent_activate": self.on_menuitem_addtorrent_activate,
- "on_menuitem_createtorrent_activate": self.on_menuitem_createtorrent_activate,
- "on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate,
- "on_menuitem_quit_activate": self.on_menuitem_quit_activate,
+ 'on_menuitem_addtorrent_activate': self.on_menuitem_addtorrent_activate,
+ 'on_menuitem_createtorrent_activate': self.on_menuitem_createtorrent_activate,
+ 'on_menuitem_quitdaemon_activate': self.on_menuitem_quitdaemon_activate,
+ 'on_menuitem_quit_activate': self.on_menuitem_quit_activate,
# Edit Menu
- "on_menuitem_preferences_activate": self.on_menuitem_preferences_activate,
- "on_menuitem_connectionmanager_activate": self.on_menuitem_connectionmanager_activate,
+ 'on_menuitem_preferences_activate': self.on_menuitem_preferences_activate,
+ 'on_menuitem_connectionmanager_activate': self.on_menuitem_connectionmanager_activate,
# View Menu
- "on_menuitem_toolbar_toggled": self.on_menuitem_toolbar_toggled,
- "on_menuitem_sidebar_toggled": self.on_menuitem_sidebar_toggled,
- "on_menuitem_statusbar_toggled": self.on_menuitem_statusbar_toggled,
+ 'on_menuitem_toolbar_toggled': self.on_menuitem_toolbar_toggled,
+ 'on_menuitem_sidebar_toggled': self.on_menuitem_sidebar_toggled,
+ 'on_menuitem_statusbar_toggled': self.on_menuitem_statusbar_toggled,
# Help Menu
- "on_menuitem_homepage_activate": self.on_menuitem_homepage_activate,
- "on_menuitem_faq_activate": self.on_menuitem_faq_activate,
- "on_menuitem_community_activate": self.on_menuitem_community_activate,
- "on_menuitem_about_activate": self.on_menuitem_about_activate,
- "on_menuitem_sidebar_zero_toggled": self.on_menuitem_sidebar_zero_toggled,
- "on_menuitem_sidebar_trackers_toggled": self.on_menuitem_sidebar_trackers_toggled,
- "on_menuitem_sidebar_owners_toggled": self.on_menuitem_sidebar_owners_toggled
+ 'on_menuitem_homepage_activate': self.on_menuitem_homepage_activate,
+ 'on_menuitem_faq_activate': self.on_menuitem_faq_activate,
+ 'on_menuitem_community_activate': self.on_menuitem_community_activate,
+ 'on_menuitem_about_activate': self.on_menuitem_about_activate,
+ 'on_menuitem_sidebar_zero_toggled': self.on_menuitem_sidebar_zero_toggled,
+ 'on_menuitem_sidebar_trackers_toggled': self.on_menuitem_sidebar_trackers_toggled,
+ 'on_menuitem_sidebar_owners_toggled': self.on_menuitem_sidebar_owners_toggled
})
# Connect menubar signals
self.builder.connect_signals({
# Torrent Menu
- "on_menuitem_pause_activate": self.on_menuitem_pause_activate,
- "on_menuitem_resume_activate": self.on_menuitem_resume_activate,
- "on_menuitem_updatetracker_activate": self.on_menuitem_updatetracker_activate,
- "on_menuitem_edittrackers_activate": self.on_menuitem_edittrackers_activate,
- "on_menuitem_remove_activate": self.on_menuitem_remove_activate,
- "on_menuitem_recheck_activate": self.on_menuitem_recheck_activate,
- "on_menuitem_open_folder_activate": self.on_menuitem_open_folder_activate,
- "on_menuitem_move_activate": self.on_menuitem_move_activate,
- "on_menuitem_queue_top_activate": self.on_menuitem_queue_top_activate,
- "on_menuitem_queue_up_activate": self.on_menuitem_queue_up_activate,
- "on_menuitem_queue_down_activate": self.on_menuitem_queue_down_activate,
- "on_menuitem_queue_bottom_activate": self.on_menuitem_queue_bottom_activate
+ 'on_menuitem_pause_activate': self.on_menuitem_pause_activate,
+ 'on_menuitem_resume_activate': self.on_menuitem_resume_activate,
+ 'on_menuitem_updatetracker_activate': self.on_menuitem_updatetracker_activate,
+ 'on_menuitem_edittrackers_activate': self.on_menuitem_edittrackers_activate,
+ 'on_menuitem_remove_activate': self.on_menuitem_remove_activate,
+ 'on_menuitem_recheck_activate': self.on_menuitem_recheck_activate,
+ 'on_menuitem_open_folder_activate': self.on_menuitem_open_folder_activate,
+ 'on_menuitem_move_activate': self.on_menuitem_move_activate,
+ 'on_menuitem_queue_top_activate': self.on_menuitem_queue_top_activate,
+ 'on_menuitem_queue_up_activate': self.on_menuitem_queue_up_activate,
+ 'on_menuitem_queue_down_activate': self.on_menuitem_queue_down_activate,
+ 'on_menuitem_queue_bottom_activate': self.on_menuitem_queue_bottom_activate
})
self.change_sensitivity = [
- "menuitem_addtorrent"
+ 'menuitem_addtorrent'
]
def start(self):
@@ -164,8 +164,8 @@ class MenuBar(component.Component):
# Only show open_folder menuitem and separator if connected to a localhost daemon.
localhost_items = [
- "menuitem_open_folder",
- "separator4"
+ 'menuitem_open_folder',
+ 'separator4'
]
if client.is_localhost():
for widget in localhost_items:
@@ -176,9 +176,9 @@ class MenuBar(component.Component):
self.builder.get_object(widget).hide()
self.builder.get_object(widget).set_no_show_all(True)
- self.main_builder.get_object("separatormenuitem").set_visible(not self.config["standalone"])
- self.main_builder.get_object("menuitem_quitdaemon").set_visible(not self.config["standalone"])
- self.main_builder.get_object("menuitem_connectionmanager").set_visible(not self.config["standalone"])
+ self.main_builder.get_object('separatormenuitem').set_visible(not self.config['standalone'])
+ self.main_builder.get_object('menuitem_quitdaemon').set_visible(not self.config['standalone'])
+ self.main_builder.get_object('menuitem_connectionmanager').set_visible(not self.config['standalone'])
# Show the Torrent menu because we're connected to a host
self.menu_torrent.show()
@@ -188,18 +188,18 @@ class MenuBar(component.Component):
client.core.get_known_accounts().addCallback(
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)
- client.register_event_handler("SessionPausedEvent", self.on_sessionpaused_event)
- client.register_event_handler("SessionResumedEvent", self.on_sessionresumed_event)
+ client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
+ client.register_event_handler('TorrentResumedEvent', self.on_torrentresumed_event)
+ client.register_event_handler('SessionPausedEvent', self.on_sessionpaused_event)
+ client.register_event_handler('SessionResumedEvent', self.on_sessionresumed_event)
def stop(self):
- log.debug("MenuBar stopping")
+ log.debug('MenuBar stopping')
- client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event)
- client.deregister_event_handler("TorrentResumedEvent", self.on_torrentresumed_event)
- client.deregister_event_handler("SessionPausedEvent", self.on_sessionpaused_event)
- client.deregister_event_handler("SessionResumedEvent", self.on_sessionresumed_event)
+ client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
+ client.deregister_event_handler('TorrentResumedEvent', self.on_torrentresumed_event)
+ client.deregister_event_handler('SessionPausedEvent', self.on_sessionpaused_event)
+ client.deregister_event_handler('SessionResumedEvent', self.on_sessionresumed_event)
for widget in self.change_sensitivity:
self.main_builder.get_object(widget).set_sensitive(False)
@@ -207,8 +207,8 @@ class MenuBar(component.Component):
# Hide the Torrent menu
self.menu_torrent.hide()
- self.main_builder.get_object("separatormenuitem").hide()
- self.main_builder.get_object("menuitem_quitdaemon").hide()
+ self.main_builder.get_object('separatormenuitem').hide()
+ self.main_builder.get_object('menuitem_quitdaemon').hide()
def update_menu(self):
selected = component.get('TorrentView').get_selected_torrents()
@@ -229,7 +229,7 @@ class MenuBar(component.Component):
# Callbacks #
def on_torrentstatechanged_event(self, torrent_id, state):
- if state == "Paused":
+ if state == 'Paused':
self.update_menu()
def on_torrentresumed_event(self, torrent_id):
@@ -243,99 +243,99 @@ class MenuBar(component.Component):
# File Menu #
def on_menuitem_addtorrent_activate(self, data=None):
- log.debug("on_menuitem_addtorrent_activate")
- component.get("AddTorrentDialog").show()
+ log.debug('on_menuitem_addtorrent_activate')
+ component.get('AddTorrentDialog').show()
def on_menuitem_createtorrent_activate(self, data=None):
- log.debug("on_menuitem_createtorrent_activate")
+ log.debug('on_menuitem_createtorrent_activate')
from deluge.ui.gtkui.createtorrentdialog import CreateTorrentDialog
CreateTorrentDialog().show()
def on_menuitem_quitdaemon_activate(self, data=None):
- log.debug("on_menuitem_quitdaemon_activate")
+ log.debug('on_menuitem_quitdaemon_activate')
self.window.quit(shutdown=True)
def on_menuitem_quit_activate(self, data=None):
- log.debug("on_menuitem_quit_activate")
+ log.debug('on_menuitem_quit_activate')
self.window.quit()
# Edit Menu #
def on_menuitem_preferences_activate(self, data=None):
- log.debug("on_menuitem_preferences_activate")
- component.get("Preferences").show()
+ log.debug('on_menuitem_preferences_activate')
+ component.get('Preferences').show()
def on_menuitem_connectionmanager_activate(self, data=None):
- log.debug("on_menuitem_connectionmanager_activate")
- component.get("ConnectionManager").show()
+ log.debug('on_menuitem_connectionmanager_activate')
+ component.get('ConnectionManager').show()
# Torrent Menu #
def on_menuitem_pause_activate(self, data=None):
- log.debug("on_menuitem_pause_activate")
+ 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")
+ 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")
+ 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")
+ log.debug('on_menuitem_edittrackers_activate')
from deluge.ui.gtkui.edittrackersdialog import EditTrackersDialog
dialog = EditTrackersDialog(
- component.get("TorrentView").get_selected_torrent(),
- component.get("MainWindow").window)
+ component.get('TorrentView').get_selected_torrent(),
+ component.get('MainWindow').window)
dialog.run()
def on_menuitem_remove_activate(self, data=None):
- log.debug("on_menuitem_remove_activate")
- torrent_ids = component.get("TorrentView").get_selected_torrents()
+ log.debug('on_menuitem_remove_activate')
+ torrent_ids = component.get('TorrentView').get_selected_torrents()
if torrent_ids:
from deluge.ui.gtkui.removetorrentdialog import RemoveTorrentDialog
RemoveTorrentDialog(torrent_ids).run()
def on_menuitem_recheck_activate(self, data=None):
- log.debug("on_menuitem_recheck_activate")
+ 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")
+ log.debug('on_menuitem_open_folder')
def _on_torrent_status(status):
timestamp = gtk.get_current_event_time()
- path = os.path.join(status["download_location"], status["files"][0]["path"].split('/')[0])
+ path = os.path.join(status['download_location'], status['files'][0]['path'].split('/')[0])
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)
+ 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)
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)
+ 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)
def show_move_storage_dialog(self, status):
- log.debug("show_move_storage_dialog")
+ 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
- self.move_storage_dialog = builder.get_object("move_storage_dialog")
+ self.move_storage_dialog = builder.get_object('move_storage_dialog')
self.move_storage_dialog.set_transient_for(self.window.window)
- self.move_storage_dialog_hbox = builder.get_object("hbox_entry")
- self.move_storage_path_chooser = PathChooser("move_completed_paths_list")
+ self.move_storage_dialog_hbox = builder.get_object('hbox_entry')
+ self.move_storage_path_chooser = PathChooser('move_completed_paths_list')
self.move_storage_dialog_hbox.add(self.move_storage_path_chooser)
self.move_storage_dialog_hbox.show_all()
- self.move_storage_path_chooser.set_text(status["download_location"])
+ self.move_storage_path_chooser.set_text(status['download_location'])
def on_dialog_response_event(widget, response_id):
def on_core_result(result):
@@ -348,95 +348,95 @@ class MenuBar(component.Component):
on_core_result(None)
if response_id == gtk.RESPONSE_OK:
- log.debug("Moving torrents to %s",
+ 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)
+ self.move_storage_dialog.connect('response', on_dialog_response_event)
self.move_storage_dialog.show()
def on_menuitem_queue_top_activate(self, value):
- log.debug("on_menuitem_queue_top_activate")
- client.core.queue_top(component.get("TorrentView").get_selected_torrents())
+ log.debug('on_menuitem_queue_top_activate')
+ client.core.queue_top(component.get('TorrentView').get_selected_torrents())
def on_menuitem_queue_up_activate(self, value):
- log.debug("on_menuitem_queue_up_activate")
- client.core.queue_up(component.get("TorrentView").get_selected_torrents())
+ log.debug('on_menuitem_queue_up_activate')
+ client.core.queue_up(component.get('TorrentView').get_selected_torrents())
def on_menuitem_queue_down_activate(self, value):
- log.debug("on_menuitem_queue_down_activate")
- client.core.queue_down(component.get("TorrentView").get_selected_torrents())
+ log.debug('on_menuitem_queue_down_activate')
+ client.core.queue_down(component.get('TorrentView').get_selected_torrents())
def on_menuitem_queue_bottom_activate(self, value):
- log.debug("on_menuitem_queue_bottom_activate")
- client.core.queue_bottom(component.get("TorrentView").get_selected_torrents())
+ log.debug('on_menuitem_queue_bottom_activate')
+ client.core.queue_bottom(component.get('TorrentView').get_selected_torrents())
# View Menu #
def on_menuitem_toolbar_toggled(self, value):
- log.debug("on_menuitem_toolbar_toggled")
- component.get("ToolBar").visible(value.get_active())
+ log.debug('on_menuitem_toolbar_toggled')
+ component.get('ToolBar').visible(value.get_active())
def on_menuitem_sidebar_toggled(self, value):
- log.debug("on_menuitem_sidebar_toggled")
- component.get("SideBar").visible(value.get_active())
+ log.debug('on_menuitem_sidebar_toggled')
+ component.get('SideBar').visible(value.get_active())
def on_menuitem_statusbar_toggled(self, value):
- log.debug("on_menuitem_statusbar_toggled")
- component.get("StatusBar").visible(value.get_active())
+ log.debug('on_menuitem_statusbar_toggled')
+ component.get('StatusBar').visible(value.get_active())
# Help Menu #
def on_menuitem_homepage_activate(self, data=None):
- log.debug("on_menuitem_homepage_activate")
- deluge.common.open_url_in_browser("http://deluge-torrent.org")
+ log.debug('on_menuitem_homepage_activate')
+ deluge.common.open_url_in_browser('http://deluge-torrent.org')
def on_menuitem_faq_activate(self, data=None):
- log.debug("on_menuitem_faq_activate")
- deluge.common.open_url_in_browser("http://dev.deluge-torrent.org/wiki/Faq")
+ log.debug('on_menuitem_faq_activate')
+ deluge.common.open_url_in_browser('http://dev.deluge-torrent.org/wiki/Faq')
def on_menuitem_community_activate(self, data=None):
- log.debug("on_menuitem_community_activate")
- deluge.common.open_url_in_browser("http://forum.deluge-torrent.org/")
+ log.debug('on_menuitem_community_activate')
+ deluge.common.open_url_in_browser('http://forum.deluge-torrent.org/')
def on_menuitem_about_activate(self, data=None):
- log.debug("on_menuitem_about_activate")
+ log.debug('on_menuitem_about_activate')
from deluge.ui.gtkui.aboutdialog import AboutDialog
AboutDialog().run()
def on_menuitem_set_unlimited(self, widget):
- log.debug("widget.name: %s", widget.name)
+ log.debug('widget.name: %s', widget.name)
funcs = {
- "menuitem_down_speed": client.core.set_torrent_max_download_speed,
- "menuitem_up_speed": client.core.set_torrent_max_upload_speed,
- "menuitem_max_connections": client.core.set_torrent_max_connections,
- "menuitem_upload_slots": client.core.set_torrent_max_upload_slots
+ 'menuitem_down_speed': client.core.set_torrent_max_download_speed,
+ 'menuitem_up_speed': client.core.set_torrent_max_upload_speed,
+ 'menuitem_max_connections': client.core.set_torrent_max_connections,
+ 'menuitem_upload_slots': client.core.set_torrent_max_upload_slots
}
if widget.name in funcs.keys():
- for torrent in component.get("TorrentView").get_selected_torrents():
+ for torrent in component.get('TorrentView').get_selected_torrents():
funcs[widget.name](torrent, -1)
def on_menuitem_set_other(self, widget):
- log.debug("widget.name: %s", widget.name)
+ log.debug('widget.name: %s', widget.name)
status_map = {
- "menuitem_down_speed": ["max_download_speed", "max_download_speed"],
- "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_down_speed': ['max_download_speed', 'max_download_speed'],
+ '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']
}
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.name][0]
@@ -453,44 +453,44 @@ class MenuBar(component.Component):
if value == 0:
value += -1
options = {core_key: value}
- if core_key == "stop_ratio":
- options["stop_at_ratio"] = True
+ if core_key == 'stop_ratio':
+ options['stop_at_ratio'] = True
client.core.set_torrent_options(torrent_ids, options)
dialog = OtherDialog(*other_dialog)
dialog.run().addCallback(set_value)
- torrent_ids = component.get("TorrentView").get_selected_torrents()
+ torrent_ids = component.get('TorrentView').get_selected_torrents()
if len(torrent_ids) == 1:
core_key_global = core_key
- d = component.get("SessionProxy").get_torrent_status(torrent_ids[0], [core_key])
+ d = component.get('SessionProxy').get_torrent_status(torrent_ids[0], [core_key])
else:
d = client.core.get_config_values([core_key_global])
d.addCallback(_on_torrent_status)
def on_menuitem_set_automanaged_on(self, widget):
- for torrent in component.get("TorrentView").get_selected_torrents():
+ for torrent in component.get('TorrentView').get_selected_torrents():
client.core.set_torrent_auto_managed(torrent, True)
def on_menuitem_set_automanaged_off(self, widget):
- for torrent in component.get("TorrentView").get_selected_torrents():
+ for torrent in component.get('TorrentView').get_selected_torrents():
client.core.set_torrent_auto_managed(torrent, 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()
- component.get("FilterTreeView").update()
+ self.config['sidebar_show_zero'] = widget.get_active()
+ component.get('FilterTreeView').update()
def on_menuitem_sidebar_trackers_toggled(self, widget):
- self.config["sidebar_show_trackers"] = widget.get_active()
- component.get("FilterTreeView").update()
+ self.config['sidebar_show_trackers'] = widget.get_active()
+ component.get('FilterTreeView').update()
def on_menuitem_sidebar_owners_toggled(self, widget):
- self.config["sidebar_show_owners"] = widget.get_active()
- component.get("FilterTreeView").update()
+ self.config['sidebar_show_owners'] = widget.get_active()
+ component.get('FilterTreeView').update()
def _on_known_accounts(self, known_accounts):
known_accounts_to_log = []
@@ -501,11 +501,11 @@ class MenuBar(component.Component):
value = '*' * len(value)
account_to_log[key] = value
known_accounts_to_log.append(account_to_log)
- log.debug("_on_known_accounts: %s", known_accounts_to_log)
+ log.debug('_on_known_accounts: %s', known_accounts_to_log)
if len(known_accounts) <= 1:
return
- self.builder.get_object("menuitem_change_owner").set_visible(True)
+ self.builder.get_object('menuitem_change_owner').set_visible(True)
self.change_owner_submenu = gtk.Menu()
self.change_owner_submenu_items = {}
@@ -514,41 +514,41 @@ class MenuBar(component.Component):
self.change_owner_submenu_items[None] = gtk.RadioMenuItem(maingroup)
for account in known_accounts:
- username = account["username"]
+ username = account['username']
item = gtk.RadioMenuItem(maingroup, username)
self.change_owner_submenu_items[username] = item
self.change_owner_submenu.append(item)
- item.connect("toggled", self._on_change_owner_toggled, username)
+ item.connect('toggled', self._on_change_owner_toggled, username)
self.change_owner_submenu.show_all()
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
+ self.builder.get_object('menuitem_change_owner').connect(
+ 'activate', self._on_change_owner_submenu_active
)
- self.builder.get_object("menuitem_change_owner").set_submenu(self.change_owner_submenu)
+ self.builder.get_object('menuitem_change_owner').set_submenu(self.change_owner_submenu)
def _on_known_accounts_fail(self, reason):
- self.builder.get_object("menuitem_change_owner").set_visible(False)
+ self.builder.get_object('menuitem_change_owner').set_visible(False)
def _on_change_owner_submenu_active(self, widget):
- log.debug("_on_change_owner_submenu_active")
- selected = component.get("TorrentView").get_selected_torrents()
+ log.debug('_on_change_owner_submenu_active')
+ selected = component.get('TorrentView').get_selected_torrents()
if len(selected) > 1:
self.change_owner_submenu_items[None].set_active(True)
return
- torrent_owner = component.get("TorrentView").get_torrent_status(selected[0])["owner"]
+ torrent_owner = component.get('TorrentView').get_torrent_status(selected[0])['owner']
for username, item in self.change_owner_submenu_items.iteritems():
item.set_active(username == torrent_owner)
def _on_change_owner_toggled(self, widget, username):
- log.debug("_on_change_owner_toggled")
+ log.debug('_on_change_owner_toggled')
update_torrents = []
- selected = component.get("TorrentView").get_selected_torrents()
+ selected = component.get('TorrentView').get_selected_torrents()
for torrent_id in selected:
- torrent_status = component.get("TorrentView").get_torrent_status(torrent_id)
- if torrent_status["owner"] != username:
+ torrent_status = component.get('TorrentView').get_torrent_status(torrent_id)
+ if torrent_status['owner'] != username:
update_torrents.append(torrent_id)
if update_torrents:
@@ -556,8 +556,8 @@ class MenuBar(component.Component):
def failed_change_owner(failure):
ErrorDialog(
- _("Ownership Change Error"),
- _("There was an error while trying changing ownership."),
+ _('Ownership Change Error'),
+ _('There was an error while trying changing ownership.'),
self.window.window, details=failure.value.logable()
).run()
client.core.set_owner(
diff --git a/deluge/ui/gtkui/menubar_osx.py b/deluge/ui/gtkui/menubar_osx.py
index 5593cd155..7b5a6a4fe 100644
--- a/deluge/ui/gtkui/menubar_osx.py
+++ b/deluge/ui/gtkui/menubar_osx.py
@@ -14,7 +14,7 @@ from deluge.configmanager import ConfigManager
def accel_swap(item, group, skey, smod, dkey, dmod):
item.remove_accelerator(group, ord(skey), smod)
- item.add_accelerator("activate", group, ord(dkey), dmod, gtk.ACCEL_VISIBLE)
+ item.add_accelerator('activate', group, ord(dkey), dmod, gtk.ACCEL_VISIBLE)
def accel_meta(item, group, key):
@@ -24,16 +24,16 @@ def accel_meta(item, group, key):
def menubar_osx(gtkui, osxapp):
window = gtkui.mainwindow
main_builder = window.get_builder()
- menubar = main_builder.get_object("menubar")
+ menubar = main_builder.get_object('menubar')
group = gtk.accel_groups_from_object(window.window)[0]
- config = ConfigManager("gtkui.conf")
+ config = ConfigManager('gtkui.conf')
# NOTE: accel maps doesn't work with glade file format
# because of libglade not setting MenuItem accel groups
# That's why we remove / set accelerators by hand... (dirty)
# Clean solution: migrate glades files to gtkbuilder format
- file_menu = main_builder.get_object("menu_file").get_submenu()
+ file_menu = main_builder.get_object('menu_file').get_submenu()
file_items = file_menu.get_children()
accel_meta(file_items[0], group, 'o')
accel_meta(file_items[1], group, 'n')
@@ -43,7 +43,7 @@ def menubar_osx(gtkui, osxapp):
for item in range(2, len(file_items)): # remove quits
file_menu.remove(file_items[item])
- menu_widget = main_builder.get_object("menu_edit")
+ menu_widget = main_builder.get_object('menu_edit')
edit_menu = menu_widget.get_submenu()
edit_items = edit_menu.get_children()
pref_item = edit_items[0]
@@ -56,7 +56,7 @@ def menubar_osx(gtkui, osxapp):
menubar.remove(menu_widget)
- help_menu = main_builder.get_object("menu_help").get_submenu()
+ help_menu = main_builder.get_object('menu_help').get_submenu()
help_items = help_menu.get_children()
about_item = help_items[4]
help_menu.remove(about_item)
@@ -68,7 +68,7 @@ def menubar_osx(gtkui, osxapp):
osxapp.insert_app_menu_item(about_item, 0)
osxapp.insert_app_menu_item(gtk.SeparatorMenuItem(), 1)
osxapp.insert_app_menu_item(pref_item, 2)
- if not config["standalone"]:
+ if not config['standalone']:
osxapp.insert_app_menu_item(conn_item, 3)
if quit_all_item.get_visible():
osxapp.insert_app_menu_item(gtk.SeparatorMenuItem(), 4)
diff --git a/deluge/ui/gtkui/new_release_dialog.py b/deluge/ui/gtkui/new_release_dialog.py
index cff8ce93d..fd0a0c960 100644
--- a/deluge/ui/gtkui/new_release_dialog.py
+++ b/deluge/ui/gtkui/new_release_dialog.py
@@ -19,41 +19,41 @@ class NewReleaseDialog(object):
pass
def show(self, available_version):
- self.config = ConfigManager("gtkui.conf")
- builder = component.get("MainWindow").get_builder()
- self.dialog = builder.get_object("new_release_dialog")
+ self.config = ConfigManager('gtkui.conf')
+ builder = component.get('MainWindow').get_builder()
+ self.dialog = builder.get_object('new_release_dialog')
# Set the version labels
if deluge.common.windows_check() or deluge.common.osx_check():
- builder.get_object("image_new_release").set_from_file(
- deluge.common.get_pixmap("deluge16.png"))
+ builder.get_object('image_new_release').set_from_file(
+ deluge.common.get_pixmap('deluge16.png'))
else:
- builder.get_object("image_new_release").set_from_icon_name("deluge", 4)
- builder.get_object("label_available_version").set_text(available_version)
- builder.get_object("label_client_version").set_text(
+ builder.get_object('image_new_release').set_from_icon_name('deluge', 4)
+ builder.get_object('label_available_version').set_text(available_version)
+ builder.get_object('label_client_version').set_text(
deluge.common.get_version())
- self.chk_not_show_dialog = builder.get_object("chk_do_not_show_new_release")
- builder.get_object("button_goto_downloads").connect(
- "clicked", self._on_button_goto_downloads)
- builder.get_object("button_close_new_release").connect(
- "clicked", self._on_button_close_new_release)
+ self.chk_not_show_dialog = builder.get_object('chk_do_not_show_new_release')
+ builder.get_object('button_goto_downloads').connect(
+ 'clicked', self._on_button_goto_downloads)
+ builder.get_object('button_close_new_release').connect(
+ 'clicked', self._on_button_close_new_release)
if client.connected():
def on_info(version):
- builder.get_object("label_server_version").set_text(version)
- builder.get_object("label_server_version").show()
- builder.get_object("label_server_version_text").show()
+ builder.get_object('label_server_version').set_text(version)
+ builder.get_object('label_server_version').show()
+ builder.get_object('label_server_version_text').show()
if not client.is_standalone():
- builder.get_object("label_client_version_text").set_label(_("<i>Client Version</i>"))
+ builder.get_object('label_client_version_text').set_label(_('<i>Client Version</i>'))
client.daemon.info().addCallback(on_info)
self.dialog.show()
def _on_button_goto_downloads(self, widget):
- deluge.common.open_url_in_browser("http://deluge-torrent.org")
- self.config["show_new_releases"] = not self.chk_not_show_dialog.get_active()
+ deluge.common.open_url_in_browser('http://deluge-torrent.org')
+ self.config['show_new_releases'] = not self.chk_not_show_dialog.get_active()
self.dialog.destroy()
def _on_button_close_new_release(self, widget):
- self.config["show_new_releases"] = not self.chk_not_show_dialog.get_active()
+ self.config['show_new_releases'] = not self.chk_not_show_dialog.get_active()
self.dialog.destroy()
diff --git a/deluge/ui/gtkui/options_tab.py b/deluge/ui/gtkui/options_tab.py
index 485659485..a17d0c9bf 100644
--- a/deluge/ui/gtkui/options_tab.py
+++ b/deluge/ui/gtkui/options_tab.py
@@ -18,52 +18,52 @@ from deluge.ui.gtkui.torrentdetails import Tab
class OptionsTab(Tab):
def __init__(self):
Tab.__init__(self)
- builder = component.get("MainWindow").get_builder()
-
- self._name = "Options"
- self._child_widget = builder.get_object("options_tab")
- self._tab_label = builder.get_object("options_tab_label")
-
- self.spin_max_download = builder.get_object("spin_max_download")
- self.spin_max_upload = builder.get_object("spin_max_upload")
- self.spin_max_connections = builder.get_object("spin_max_connections")
- self.spin_max_upload_slots = builder.get_object("spin_max_upload_slots")
- self.chk_prioritize_first_last = builder.get_object("chk_prioritize_first_last")
- self.chk_sequential_download = builder.get_object("chk_sequential_download")
- self.chk_auto_managed = builder.get_object("chk_auto_managed")
- self.chk_stop_at_ratio = builder.get_object("chk_stop_at_ratio")
- self.chk_remove_at_ratio = builder.get_object("chk_remove_at_ratio")
- self.spin_stop_ratio = builder.get_object("spin_stop_ratio")
- self.chk_move_completed = builder.get_object("chk_move_completed")
- self.entry_move_completed = builder.get_object("entry_move_completed")
- self.chk_shared = builder.get_object("chk_shared")
- self.button_apply = builder.get_object("button_apply")
- self.summary_owner = builder.get_object("summary_owner")
-
- self.move_completed_hbox = builder.get_object("hbox_move_completed_path_chooser")
- self.move_completed_path_chooser = PathChooser("move_completed_paths_list")
+ builder = component.get('MainWindow').get_builder()
+
+ self._name = 'Options'
+ self._child_widget = builder.get_object('options_tab')
+ self._tab_label = builder.get_object('options_tab_label')
+
+ self.spin_max_download = builder.get_object('spin_max_download')
+ self.spin_max_upload = builder.get_object('spin_max_upload')
+ self.spin_max_connections = builder.get_object('spin_max_connections')
+ self.spin_max_upload_slots = builder.get_object('spin_max_upload_slots')
+ self.chk_prioritize_first_last = builder.get_object('chk_prioritize_first_last')
+ self.chk_sequential_download = builder.get_object('chk_sequential_download')
+ self.chk_auto_managed = builder.get_object('chk_auto_managed')
+ self.chk_stop_at_ratio = builder.get_object('chk_stop_at_ratio')
+ self.chk_remove_at_ratio = builder.get_object('chk_remove_at_ratio')
+ self.spin_stop_ratio = builder.get_object('spin_stop_ratio')
+ self.chk_move_completed = builder.get_object('chk_move_completed')
+ self.entry_move_completed = builder.get_object('entry_move_completed')
+ self.chk_shared = builder.get_object('chk_shared')
+ self.button_apply = builder.get_object('button_apply')
+ self.summary_owner = builder.get_object('summary_owner')
+
+ self.move_completed_hbox = builder.get_object('hbox_move_completed_path_chooser')
+ self.move_completed_path_chooser = PathChooser('move_completed_paths_list')
self.move_completed_path_chooser.set_sensitive(self.chk_move_completed.get_active())
self.move_completed_hbox.add(self.move_completed_path_chooser)
self.move_completed_hbox.show_all()
- self.move_completed_path_chooser.connect("text-changed", self._on_path_chooser_text_changed_event)
+ self.move_completed_path_chooser.connect('text-changed', self._on_path_chooser_text_changed_event)
self.prev_torrent_id = None
self.prev_status = None
- component.get("MainWindow").connect_signals({
- "on_button_apply_clicked": self._on_button_apply_clicked,
- "on_chk_move_completed_toggled": self._on_chk_move_completed_toggled,
- "on_chk_stop_at_ratio_toggled": self._on_chk_stop_at_ratio_toggled,
- "on_chk_toggled": self._on_chk_toggled,
- "on_spin_value_changed": self._on_spin_value_changed,
- "on_move_completed_file_set": self._on_move_completed_file_set
+ component.get('MainWindow').connect_signals({
+ 'on_button_apply_clicked': self._on_button_apply_clicked,
+ 'on_chk_move_completed_toggled': self._on_chk_move_completed_toggled,
+ 'on_chk_stop_at_ratio_toggled': self._on_chk_stop_at_ratio_toggled,
+ 'on_chk_toggled': self._on_chk_toggled,
+ 'on_spin_value_changed': self._on_spin_value_changed,
+ 'on_move_completed_file_set': self._on_move_completed_file_set
})
- self.spin_max_download.connect("key-press-event", self._on_key_press_event)
- self.spin_max_upload.connect("key-press-event", self._on_key_press_event)
- self.spin_max_connections.connect("key-press-event", self._on_key_press_event)
- self.spin_max_upload_slots.connect("key-press-event", self._on_key_press_event)
- self.spin_stop_ratio.connect("key-press-event", self._on_key_press_event)
+ self.spin_max_download.connect('key-press-event', self._on_key_press_event)
+ self.spin_max_upload.connect('key-press-event', self._on_key_press_event)
+ self.spin_max_connections.connect('key-press-event', self._on_key_press_event)
+ self.spin_max_upload_slots.connect('key-press-event', self._on_key_press_event)
+ self.spin_stop_ratio.connect('key-press-event', self._on_key_press_event)
def start(self):
pass
@@ -73,7 +73,7 @@ class OptionsTab(Tab):
def update(self):
# Get the first selected torrent
- torrent_id = component.get("TorrentView").get_selected_torrents()
+ torrent_id = component.get('TorrentView').get_selected_torrents()
# Only use the first torrent in the list or return if None selected
if torrent_id:
@@ -87,22 +87,22 @@ class OptionsTab(Tab):
if torrent_id != self.prev_torrent_id:
self.prev_status = None
- component.get("SessionProxy").get_torrent_status(torrent_id, [
- "max_download_speed",
- "max_upload_speed",
- "max_connections",
- "max_upload_slots",
- "prioritize_first_last",
- "is_auto_managed",
- "stop_at_ratio",
- "stop_ratio",
- "remove_at_ratio",
- "storage_mode",
- "sequential_download",
- "move_on_completed",
- "move_on_completed_path",
- "shared",
- "owner"
+ component.get('SessionProxy').get_torrent_status(torrent_id, [
+ 'max_download_speed',
+ 'max_upload_speed',
+ 'max_connections',
+ 'max_upload_slots',
+ 'prioritize_first_last',
+ 'is_auto_managed',
+ 'stop_at_ratio',
+ 'stop_ratio',
+ 'remove_at_ratio',
+ 'storage_mode',
+ 'sequential_download',
+ 'move_on_completed',
+ 'move_on_completed_path',
+ 'shared',
+ 'owner'
]).addCallback(self._on_get_torrent_status)
self.prev_torrent_id = torrent_id
@@ -117,43 +117,43 @@ class OptionsTab(Tab):
self.prev_status = {}.fromkeys(status.keys(), None)
if status != self.prev_status:
- if status["max_download_speed"] != self.prev_status["max_download_speed"]:
- self.spin_max_download.set_value(status["max_download_speed"])
- if status["max_upload_speed"] != self.prev_status["max_upload_speed"]:
- self.spin_max_upload.set_value(status["max_upload_speed"])
- if status["max_connections"] != self.prev_status["max_connections"]:
- self.spin_max_connections.set_value(status["max_connections"])
- if status["max_upload_slots"] != self.prev_status["max_upload_slots"]:
- self.spin_max_upload_slots.set_value(status["max_upload_slots"])
- if status["prioritize_first_last"] != self.prev_status["prioritize_first_last"]:
- self.chk_prioritize_first_last.set_active(status["prioritize_first_last"])
- if status["is_auto_managed"] != self.prev_status["is_auto_managed"]:
- self.chk_auto_managed.set_active(status["is_auto_managed"])
- if status["stop_at_ratio"] != self.prev_status["stop_at_ratio"]:
- self.chk_stop_at_ratio.set_active(status["stop_at_ratio"])
- self.spin_stop_ratio.set_sensitive(status["stop_at_ratio"])
- self.chk_remove_at_ratio.set_sensitive(status["stop_at_ratio"])
- if status["stop_ratio"] != self.prev_status["stop_ratio"]:
- self.spin_stop_ratio.set_value(status["stop_ratio"])
- if status["remove_at_ratio"] != self.prev_status["remove_at_ratio"]:
- self.chk_remove_at_ratio.set_active(status["remove_at_ratio"])
- if status["move_on_completed"] != self.prev_status["move_on_completed"]:
- self.chk_move_completed.set_active(status["move_on_completed"])
- if status["move_on_completed_path"] != self.prev_status["move_on_completed_path"]:
- self.move_completed_path_chooser.set_text(status["move_on_completed_path"],
+ if status['max_download_speed'] != self.prev_status['max_download_speed']:
+ self.spin_max_download.set_value(status['max_download_speed'])
+ if status['max_upload_speed'] != self.prev_status['max_upload_speed']:
+ self.spin_max_upload.set_value(status['max_upload_speed'])
+ if status['max_connections'] != self.prev_status['max_connections']:
+ self.spin_max_connections.set_value(status['max_connections'])
+ if status['max_upload_slots'] != self.prev_status['max_upload_slots']:
+ self.spin_max_upload_slots.set_value(status['max_upload_slots'])
+ if status['prioritize_first_last'] != self.prev_status['prioritize_first_last']:
+ self.chk_prioritize_first_last.set_active(status['prioritize_first_last'])
+ if status['is_auto_managed'] != self.prev_status['is_auto_managed']:
+ self.chk_auto_managed.set_active(status['is_auto_managed'])
+ if status['stop_at_ratio'] != self.prev_status['stop_at_ratio']:
+ self.chk_stop_at_ratio.set_active(status['stop_at_ratio'])
+ self.spin_stop_ratio.set_sensitive(status['stop_at_ratio'])
+ self.chk_remove_at_ratio.set_sensitive(status['stop_at_ratio'])
+ if status['stop_ratio'] != self.prev_status['stop_ratio']:
+ self.spin_stop_ratio.set_value(status['stop_ratio'])
+ if status['remove_at_ratio'] != self.prev_status['remove_at_ratio']:
+ self.chk_remove_at_ratio.set_active(status['remove_at_ratio'])
+ if status['move_on_completed'] != self.prev_status['move_on_completed']:
+ self.chk_move_completed.set_active(status['move_on_completed'])
+ if status['move_on_completed_path'] != self.prev_status['move_on_completed_path']:
+ self.move_completed_path_chooser.set_text(status['move_on_completed_path'],
cursor_end=False, default_text=True)
- if status["shared"] != self.prev_status["shared"]:
- self.chk_shared.set_active(status["shared"])
- if status["owner"] != self.prev_status["owner"]:
- self.summary_owner.set_text(status["owner"])
-
- if status["prioritize_first_last"] != self.prev_status["prioritize_first_last"]:
- self.chk_prioritize_first_last.set_active(status["prioritize_first_last"])
- if not self.chk_prioritize_first_last.get_property("visible"):
+ if status['shared'] != self.prev_status['shared']:
+ self.chk_shared.set_active(status['shared'])
+ if status['owner'] != self.prev_status['owner']:
+ self.summary_owner.set_text(status['owner'])
+
+ if status['prioritize_first_last'] != self.prev_status['prioritize_first_last']:
+ self.chk_prioritize_first_last.set_active(status['prioritize_first_last'])
+ if not self.chk_prioritize_first_last.get_property('visible'):
self.chk_prioritize_first_last.show()
- if status["sequential_download"] != self.prev_status["sequential_download"]:
- self.chk_sequential_download.set_active(status["sequential_download"])
- if not self.chk_sequential_download.get_property("visible"):
+ if status['sequential_download'] != self.prev_status['sequential_download']:
+ self.chk_sequential_download.set_active(status['sequential_download'])
+ if not self.chk_sequential_download.get_property('visible'):
self.chk_sequential_download.show()
if self.button_apply.is_sensitive():
@@ -162,36 +162,36 @@ class OptionsTab(Tab):
self.prev_status = status
def _on_button_apply_clicked(self, button):
- if self.spin_max_download.get_value() != self.prev_status["max_download_speed"]:
+ if self.spin_max_download.get_value() != self.prev_status['max_download_speed']:
client.core.set_torrent_max_download_speed(self.prev_torrent_id, self.spin_max_download.get_value())
- if self.spin_max_upload.get_value() != self.prev_status["max_upload_speed"]:
+ if self.spin_max_upload.get_value() != self.prev_status['max_upload_speed']:
client.core.set_torrent_max_upload_speed(self.prev_torrent_id, self.spin_max_upload.get_value())
- if self.spin_max_connections.get_value_as_int() != self.prev_status["max_connections"]:
+ if self.spin_max_connections.get_value_as_int() != self.prev_status['max_connections']:
client.core.set_torrent_max_connections(
self.prev_torrent_id, self.spin_max_connections.get_value_as_int())
- if self.spin_max_upload_slots.get_value_as_int() != self.prev_status["max_upload_slots"]:
+ if self.spin_max_upload_slots.get_value_as_int() != self.prev_status['max_upload_slots']:
client.core.set_torrent_max_upload_slots(
self.prev_torrent_id, self.spin_max_upload_slots.get_value_as_int())
- if self.chk_prioritize_first_last.get_active() != self.prev_status["prioritize_first_last"]:
+ if self.chk_prioritize_first_last.get_active() != self.prev_status['prioritize_first_last']:
client.core.set_torrent_prioritize_first_last(
self.prev_torrent_id, self.chk_prioritize_first_last.get_active())
- if self.chk_sequential_download.get_active() != self.prev_status["sequential_download"]:
+ if self.chk_sequential_download.get_active() != self.prev_status['sequential_download']:
client.core.set_torrent_options(
- [self.prev_torrent_id], {"sequential_download": self.chk_sequential_download.get_active()})
- if self.chk_auto_managed.get_active() != self.prev_status["is_auto_managed"]:
+ [self.prev_torrent_id], {'sequential_download': self.chk_sequential_download.get_active()})
+ if self.chk_auto_managed.get_active() != self.prev_status['is_auto_managed']:
client.core.set_torrent_auto_managed(self.prev_torrent_id, self.chk_auto_managed.get_active())
- if self.chk_stop_at_ratio.get_active() != self.prev_status["stop_at_ratio"]:
+ if self.chk_stop_at_ratio.get_active() != self.prev_status['stop_at_ratio']:
client.core.set_torrent_stop_at_ratio(self.prev_torrent_id, self.chk_stop_at_ratio.get_active())
- if self.spin_stop_ratio.get_value() != self.prev_status["stop_ratio"]:
+ if self.spin_stop_ratio.get_value() != self.prev_status['stop_ratio']:
client.core.set_torrent_stop_ratio(self.prev_torrent_id, self.spin_stop_ratio.get_value())
- if self.chk_remove_at_ratio.get_active() != self.prev_status["remove_at_ratio"]:
+ if self.chk_remove_at_ratio.get_active() != self.prev_status['remove_at_ratio']:
client.core.set_torrent_remove_at_ratio(self.prev_torrent_id, self.chk_remove_at_ratio.get_active())
- if self.chk_move_completed.get_active() != self.prev_status["move_on_completed"]:
+ if self.chk_move_completed.get_active() != self.prev_status['move_on_completed']:
client.core.set_torrent_move_completed(self.prev_torrent_id, self.chk_move_completed.get_active())
if self.chk_move_completed.get_active():
path = self.move_completed_path_chooser.get_text()
client.core.set_torrent_move_completed_path(self.prev_torrent_id, path)
- if self.chk_shared.get_active() != self.prev_status["shared"]:
+ if self.chk_shared.get_active() != self.prev_status['shared']:
client.core.set_torrents_shared(self.prev_torrent_id, self.chk_shared.get_active())
self.button_apply.set_sensitive(False)
@@ -220,8 +220,8 @@ class OptionsTab(Tab):
self.button_apply.set_sensitive(True)
def _on_key_press_event(self, widget, event):
- keyname = gtk.gdk.keyval_name(event.keyval).lstrip("KP_").lower()
- if keyname.isdigit() or keyname in ["period", "minus", "delete", "backspace"]:
+ keyname = gtk.gdk.keyval_name(event.keyval).lstrip('KP_').lower()
+ if keyname.isdigit() or keyname in ['period', 'minus', 'delete', 'backspace']:
if not self.button_apply.is_sensitive():
self.button_apply.set_sensitive(True)
diff --git a/deluge/ui/gtkui/path_chooser.py b/deluge/ui/gtkui/path_chooser.py
index 21f8b23c2..d0a82be62 100644
--- a/deluge/ui/gtkui/path_chooser.py
+++ b/deluge/ui/gtkui/path_chooser.py
@@ -31,19 +31,19 @@ class PathChoosersHandler(component.Component):
def __init__(self, paths_config_key=None):
# self.chooser_name = "PathChooser_%d" % (len(PathChooser.path_choosers) +1)
- component.Component.__init__(self, "PathChoosersHandler")
+ component.Component.__init__(self, 'PathChoosersHandler')
self.path_choosers = []
self.paths_list_keys = []
self.config_properties = {}
self.started = False
self.config_keys_to_funcs_mapping = {
- "path_chooser_show_chooser_button_on_localhost": "filechooser_button_visible",
- "path_chooser_show_path_entry": "path_entry_visible",
- "path_chooser_auto_complete_enabled": "auto_complete_enabled",
- "path_chooser_show_folder_name": "show_folder_name_on_button",
- "path_chooser_accelerator_string": "accelerator_string",
- "path_chooser_show_hidden_files": "show_hidden_files",
- "path_chooser_max_popup_rows": "max_popup_rows",
+ 'path_chooser_show_chooser_button_on_localhost': 'filechooser_button_visible',
+ 'path_chooser_show_path_entry': 'path_entry_visible',
+ 'path_chooser_auto_complete_enabled': 'auto_complete_enabled',
+ 'path_chooser_show_folder_name': 'show_folder_name_on_button',
+ 'path_chooser_accelerator_string': 'accelerator_string',
+ 'path_chooser_show_hidden_files': 'show_hidden_files',
+ 'path_chooser_max_popup_rows': 'max_popup_rows',
}
def start(self):
@@ -66,8 +66,8 @@ class PathChoosersHandler(component.Component):
chooser.config_key_funcs = {}
for key in self.config_keys_to_funcs_mapping:
chooser.config_key_funcs[key] = [None, None]
- chooser.config_key_funcs[key][0] = getattr(chooser, "get_%s" % self.config_keys_to_funcs_mapping[key])
- chooser.config_key_funcs[key][1] = getattr(chooser, "set_%s" % self.config_keys_to_funcs_mapping[key])
+ chooser.config_key_funcs[key][0] = getattr(chooser, 'get_%s' % self.config_keys_to_funcs_mapping[key])
+ chooser.config_key_funcs[key][1] = getattr(chooser, 'set_%s' % self.config_keys_to_funcs_mapping[key])
self.path_choosers.append(chooser)
if chooser.paths_config_key not in self.paths_list_keys:
@@ -82,7 +82,7 @@ class PathChoosersHandler(component.Component):
chooser.config_key_funcs[key][1](value)
# Save to core
- if key is not "path_chooser_max_popup_rows":
+ if key is not 'path_chooser_max_popup_rows':
client.core.set_config({key: value})
else:
# Since the max rows value can be changed fast with a spinbutton, we
@@ -92,7 +92,7 @@ class PathChoosersHandler(component.Component):
def update(value_):
# The value hasn't been changed in one second, so save to core
if self.max_rows_value_set == value_:
- client.core.set_config({"path_chooser_max_popup_rows": value})
+ client.core.set_config({'path_chooser_max_popup_rows': value})
from twisted.internet import reactor
reactor.callLater(1, update, value)
@@ -120,35 +120,35 @@ class PathChooser(PathChooserComboBox):
self.chooser_handler = PathChoosersHandler()
self.chooser_handler.register_chooser(self)
self.set_auto_completer_func(self.on_completion)
- self.connect("list-values-changed", self.on_list_values_changed_event)
- self.connect("auto-complete-enabled-toggled", self.on_auto_complete_enabled_toggled)
- self.connect("show-filechooser-toggled", self.on_show_filechooser_toggled)
- self.connect("show-folder-name-on-button", self.on_show_folder_on_button_toggled)
- self.connect("show-path-entry-toggled", self.on_show_path_entry_toggled)
- self.connect("accelerator-set", self.on_accelerator_set)
- self.connect("max-rows-changed", self.on_max_rows_changed)
- self.connect("show-hidden-files-toggled", self.on_show_hidden_files_toggled)
+ self.connect('list-values-changed', self.on_list_values_changed_event)
+ self.connect('auto-complete-enabled-toggled', self.on_auto_complete_enabled_toggled)
+ self.connect('show-filechooser-toggled', self.on_show_filechooser_toggled)
+ self.connect('show-folder-name-on-button', self.on_show_folder_on_button_toggled)
+ self.connect('show-path-entry-toggled', self.on_show_path_entry_toggled)
+ self.connect('accelerator-set', self.on_accelerator_set)
+ self.connect('max-rows-changed', self.on_max_rows_changed)
+ self.connect('show-hidden-files-toggled', self.on_show_hidden_files_toggled)
def on_auto_complete_enabled_toggled(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_auto_complete_enabled")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_auto_complete_enabled')
def on_show_filechooser_toggled(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_chooser_button_on_localhost")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_chooser_button_on_localhost')
def on_show_folder_on_button_toggled(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_folder_name")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_folder_name')
def on_show_path_entry_toggled(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_path_entry")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_path_entry')
def on_accelerator_set(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_accelerator_string")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_accelerator_string')
def on_show_hidden_files_toggled(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_hidden_files")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_hidden_files')
def on_max_rows_changed(self, widget, value):
- self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_max_popup_rows")
+ self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_max_popup_rows')
def on_list_values_changed_event(self, widget, values):
self.chooser_handler.on_list_values_changed(values, self.paths_config_key, self)
@@ -160,7 +160,7 @@ class PathChooser(PathChooserComboBox):
try:
self.config_key_funcs[key][1](config[key])
except TypeError as ex:
- log.warn("TypeError: %s", ex)
+ log.warn('TypeError: %s', ex)
# Set the saved paths
if self.paths_config_key and self.paths_config_key in config:
diff --git a/deluge/ui/gtkui/path_combo_chooser.py b/deluge/ui/gtkui/path_combo_chooser.py
index 95b6c61a4..b033cc32c 100755
--- a/deluge/ui/gtkui/path_combo_chooser.py
+++ b/deluge/ui/gtkui/path_combo_chooser.py
@@ -52,8 +52,8 @@ def key_is_enter(keyval):
def path_without_trailing_path_sep(path):
- while path.endswith("/") or path.endswith("\\"):
- if path == "/":
+ while path.endswith('/') or path.endswith('\\'):
+ if path == '/':
return path
path = path[0:-1]
return path
@@ -106,8 +106,8 @@ class ValueList(object):
self.handle_list_scroll(path=tree_path)
if emit_signal:
- self.emit("list-value-added", paths)
- self.emit("list-values-changed", self.get_values())
+ self.emit('list-value-added', paths)
+ self.emit('list-values-changed', self.get_values())
def set_values(self, paths, scroll_to_row=False, preserve_selection=True):
"""
@@ -155,8 +155,8 @@ class ValueList(object):
path = (index, )
self.treeview.set_cursor(path)
self.set_path_selected(path)
- self.emit("list-value-removed", path_value)
- self.emit("list-values-changed", self.get_values())
+ self.emit('list-value-removed', path_value)
+ self.emit('list-values-changed', self.get_values())
def set_selected_value(self, value, select_first=False):
"""
@@ -300,8 +300,8 @@ class ValueList(object):
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.emit("list-values-reordered", [p1, p2])
- self.emit("list-values-changed", self.get_values())
+ self.emit('list-values-reordered', [p1, p2])
+ self.emit('list-values-changed', self.get_values())
path = new_path
self.treeview.set_cursor(path)
@@ -313,21 +313,21 @@ class ValueList(object):
class StoredValuesList(ValueList):
def __init__(self):
- self.tree_store = self.builder.get_object("stored_values_tree_store")
- self.tree_column = self.builder.get_object("stored_values_treeview_column")
- self.rendererText = self.builder.get_object("stored_values_cellrenderertext")
+ self.tree_store = self.builder.get_object('stored_values_tree_store')
+ self.tree_column = self.builder.get_object('stored_values_treeview_column')
+ self.rendererText = self.builder.get_object('stored_values_cellrenderertext')
self.paths_without_trailing_path_sep = False
# Add signal handlers
- self.signal_handlers["on_stored_values_treeview_mouse_button_press_event"] = \
+ self.signal_handlers['on_stored_values_treeview_mouse_button_press_event'] = \
self.on_treeview_mouse_button_press_event
- self.signal_handlers["on_stored_values_treeview_key_press_event"] = \
+ self.signal_handlers['on_stored_values_treeview_key_press_event'] = \
self.on_stored_values_treeview_key_press_event
- self.signal_handlers["on_stored_values_treeview_key_release_event"] = \
+ self.signal_handlers['on_stored_values_treeview_key_release_event'] = \
self.on_stored_values_treeview_key_release_event
- self.signal_handlers["on_cellrenderertext_edited"] = self.on_cellrenderertext_edited
+ self.signal_handlers['on_cellrenderertext_edited'] = self.on_cellrenderertext_edited
def on_cellrenderertext_edited(self, cellrenderertext, path, new_text):
"""
@@ -376,9 +376,9 @@ class StoredValuesList(ValueList):
treeview.set_cursor(path, col, 0)
self.path_list_popup = gtk.Menu()
- menuitem_edit = gtk.MenuItem("Edit path")
+ menuitem_edit = gtk.MenuItem('Edit path')
self.path_list_popup.append(menuitem_edit)
- menuitem_remove = gtk.MenuItem("Remove path")
+ menuitem_remove = gtk.MenuItem('Remove path')
self.path_list_popup.append(menuitem_remove)
def on_edit_clicked(widget, path):
@@ -387,8 +387,8 @@ class StoredValuesList(ValueList):
def on_remove_clicked(widget, path):
self.remove_selected_path()
- menuitem_edit.connect("activate", on_edit_clicked, path)
- menuitem_remove.connect("activate", on_remove_clicked, path)
+ menuitem_edit.connect('activate', on_edit_clicked, path)
+ menuitem_remove.connect('activate', on_remove_clicked, path)
self.path_list_popup.popup(None, None, None, event.button, time, data=path)
self.path_list_popup.show_all()
@@ -449,17 +449,17 @@ class StoredValuesList(ValueList):
class CompletionList(ValueList):
def __init__(self):
- self.tree_store = self.builder.get_object("completion_tree_store")
- self.tree_column = self.builder.get_object("completion_treeview_column")
- self.rendererText = self.builder.get_object("completion_cellrenderertext")
- self.completion_scrolled_window = self.builder.get_object("completion_scrolled_window")
- self.signal_handlers["on_completion_treeview_key_press_event"] = \
+ self.tree_store = self.builder.get_object('completion_tree_store')
+ self.tree_column = self.builder.get_object('completion_treeview_column')
+ self.rendererText = self.builder.get_object('completion_cellrenderertext')
+ self.completion_scrolled_window = self.builder.get_object('completion_scrolled_window')
+ self.signal_handlers['on_completion_treeview_key_press_event'] = \
self.on_completion_treeview_key_press_event
- self.signal_handlers["on_completion_treeview_motion_notify_event"] = \
+ self.signal_handlers['on_completion_treeview_motion_notify_event'] = \
self.on_completion_treeview_motion_notify_event
# Add super class signal handler
- self.signal_handlers["on_completion_treeview_mouse_button_press_event"] = \
+ self.signal_handlers['on_completion_treeview_mouse_button_press_event'] = \
super(CompletionList, self).on_treeview_mouse_button_press_event
def reduce_values(self, prefix):
@@ -709,9 +709,9 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup):
"""
def __init__(self, builder, path_entry, max_visible_rows, popup_alignment_widget):
self.builder = builder
- self.treeview = self.builder.get_object("stored_values_treeview")
- self.popup_window = self.builder.get_object("stored_values_popup_window")
- self.button_default = self.builder.get_object("button_default")
+ self.treeview = self.builder.get_object('stored_values_treeview')
+ self.popup_window = self.builder.get_object('stored_values_popup_window')
+ self.button_default = self.builder.get_object('button_default')
self.path_entry = path_entry
self.text_entry = path_entry.text_entry
@@ -719,27 +719,27 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup):
PathChooserPopup.__init__(self, 0, max_visible_rows, popup_alignment_widget)
StoredValuesList.__init__(self)
- self.popup_buttonbox = self.builder.get_object("buttonbox")
+ self.popup_buttonbox = self.builder.get_object('buttonbox')
# Add signal handlers
- self.signal_handlers["on_buttonbox_key_press_event"] = self.on_buttonbox_key_press_event
- self.signal_handlers["on_stored_values_treeview_scroll_event"] = self.on_scroll_event
- self.signal_handlers["on_button_toggle_dropdown_scroll_event"] = self.on_scroll_event
- self.signal_handlers["on_entry_text_scroll_event"] = self.on_scroll_event
- self.signal_handlers["on_stored_values_popup_window_focus_out_event"] = \
+ self.signal_handlers['on_buttonbox_key_press_event'] = self.on_buttonbox_key_press_event
+ self.signal_handlers['on_stored_values_treeview_scroll_event'] = self.on_scroll_event
+ self.signal_handlers['on_button_toggle_dropdown_scroll_event'] = self.on_scroll_event
+ self.signal_handlers['on_entry_text_scroll_event'] = self.on_scroll_event
+ self.signal_handlers['on_stored_values_popup_window_focus_out_event'] = \
self.on_stored_values_popup_window_focus_out_event
# For when clicking outside the popup
- self.signal_handlers["on_stored_values_popup_window_button_press_event"] = \
+ self.signal_handlers['on_stored_values_popup_window_button_press_event'] = \
self.on_popup_window_button_press_event
# Buttons for manipulating the list
- self.signal_handlers["on_button_add_clicked"] = self.on_button_add_clicked
- self.signal_handlers["on_button_edit_clicked"] = self.on_button_edit_clicked
- self.signal_handlers["on_button_remove_clicked"] = self.on_button_remove_clicked
- self.signal_handlers["on_button_up_clicked"] = self.on_button_up_clicked
- self.signal_handlers["on_button_down_clicked"] = self.on_button_down_clicked
- self.signal_handlers["on_button_default_clicked"] = self.on_button_default_clicked
- self.signal_handlers["on_button_properties_clicked"] = self.path_entry._on_button_properties_clicked
+ self.signal_handlers['on_button_add_clicked'] = self.on_button_add_clicked
+ self.signal_handlers['on_button_edit_clicked'] = self.on_button_edit_clicked
+ self.signal_handlers['on_button_remove_clicked'] = self.on_button_remove_clicked
+ self.signal_handlers['on_button_up_clicked'] = self.on_button_up_clicked
+ self.signal_handlers['on_button_down_clicked'] = self.on_button_down_clicked
+ self.signal_handlers['on_button_default_clicked'] = self.on_button_default_clicked
+ self.signal_handlers['on_button_properties_clicked'] = self.path_entry._on_button_properties_clicked
def popup(self):
"""
@@ -844,8 +844,8 @@ class PathCompletionPopup(CompletionList, PathChooserPopup):
"""
def __init__(self, builder, path_entry, max_visible_rows):
self.builder = builder
- self.treeview = self.builder.get_object("completion_treeview")
- self.popup_window = self.builder.get_object("completion_popup_window")
+ self.treeview = self.builder.get_object('completion_treeview')
+ self.popup_window = self.builder.get_object('completion_popup_window')
self.path_entry = path_entry
self.text_entry = path_entry.text_entry
self.show_hidden_files = False
@@ -855,12 +855,12 @@ class PathCompletionPopup(CompletionList, PathChooserPopup):
CompletionList.__init__(self)
# Add signal handlers
- self.signal_handlers["on_completion_treeview_scroll_event"] = self.on_scroll_event
- self.signal_handlers["on_completion_popup_window_focus_out_event"] = \
+ self.signal_handlers['on_completion_treeview_scroll_event'] = self.on_scroll_event
+ self.signal_handlers['on_completion_popup_window_focus_out_event'] = \
self.on_completion_popup_window_focus_out_event
# For when clicking outside the popup
- self.signal_handlers["on_completion_popup_window_button_press_event"] = \
+ self.signal_handlers['on_completion_popup_window_button_press_event'] = \
self.on_popup_window_button_press_event
def popup(self):
@@ -919,10 +919,10 @@ class PathAutoCompleter(object):
self.auto_complete_enabled = True
self.signal_handlers = self.completion_popup.signal_handlers
- self.signal_handlers["on_completion_popup_window_key_press_event"] = \
+ self.signal_handlers['on_completion_popup_window_key_press_event'] = \
self.on_completion_popup_window_key_press_event
- self.signal_handlers["on_entry_text_delete_text"] = self.on_entry_text_delete_text
- self.signal_handlers["on_entry_text_insert_text"] = self.on_entry_text_insert_text
+ self.signal_handlers['on_entry_text_delete_text'] = self.on_entry_text_delete_text
+ self.signal_handlers['on_entry_text_insert_text'] = self.on_entry_text_insert_text
self.accelerator_string = gtk.accelerator_name(keysyms.Tab, 0)
def on_entry_text_insert_text(self, entry, new_text, new_text_length, position):
@@ -967,7 +967,7 @@ class PathAutoCompleter(object):
else:
self.completion_popup.handle_list_scroll(_next=True)
return True
- self.path_entry.text_entry.emit("key-press-event", event)
+ self.path_entry.text_entry.emit('key-press-event', event)
def is_auto_completion_accelerator(self, keyval, state):
return gtk.accelerator_name(keyval, state.numerator) == self.accelerator_string
@@ -977,9 +977,9 @@ class PathAutoCompleter(object):
value = self.path_entry.get_text()
self.path_entry.text_entry.set_position(len(value))
opts = {}
- opts["show_hidden_files"] = self.completion_popup.show_hidden_files
- opts["completion_text"] = value
- opts["forward_completion"] = forward_completion
+ opts['show_hidden_files'] = self.completion_popup.show_hidden_files
+ opts['completion_text'] = value
+ opts['forward_completion'] = forward_completion
self._start_completion(opts)
def _start_completion(self, args):
@@ -987,10 +987,10 @@ class PathAutoCompleter(object):
self._end_completion(args)
def _end_completion(self, args):
- value = args["completion_text"]
- paths = args["paths"]
+ value = args['completion_text']
+ paths = args['paths']
- if args["forward_completion"]:
+ if args['forward_completion']:
common_prefix = os.path.commonprefix(paths)
if len(common_prefix) > len(value):
self.path_entry.set_text(common_prefix, set_file_chooser_folder=True, trigger_event=True)
@@ -1000,25 +1000,25 @@ class PathAutoCompleter(object):
if self.use_popup and len(paths) > 1:
self.completion_popup.popup()
- elif self.completion_popup.is_popped_up() and args["forward_completion"]:
+ elif self.completion_popup.is_popped_up() and args['forward_completion']:
self.completion_popup.popdown()
class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
__gsignals__ = {
- "list-value-added": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "list-value-removed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "list-values-reordered": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "list-values-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "auto-complete-enabled-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "show-filechooser-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "show-path-entry-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "show-folder-name-on-button": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "show-hidden-files-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "accelerator-set": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "max-rows-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
- "text-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'list-value-added': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'list-value-removed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'list-values-reordered': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'list-values-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'auto-complete-enabled-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'show-filechooser-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'show-path-entry-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'show-folder-name-on-button': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'show-hidden-files-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'accelerator-set': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'max-rows-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
+ 'text-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )),
}
def __init__(self, max_visible_rows=20, auto_complete=True, use_completer_popup=True):
@@ -1032,19 +1032,19 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self.show_folder_name_on_button = False
self.setting_accelerator_key = False
self.builder = gtk.Builder()
- self.popup_buttonbox = self.builder.get_object("buttonbox")
+ 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")
- self.open_filechooser_dialog_button = self.builder.get_object("button_open_dialog")
+ self.button_toggle = self.builder.get_object('button_toggle_dropdown')
+ self.text_entry = self.builder.get_object('entry_text')
+ self.open_filechooser_dialog_button = self.builder.get_object('button_open_dialog')
self.filechooser_button = self.open_filechooser_dialog_button
- self.filechooserdialog = self.builder.get_object("filechooserdialog")
- self.folder_name_label = self.builder.get_object("folder_name_label")
+ self.filechooserdialog = self.builder.get_object('filechooserdialog')
+ self.folder_name_label = self.builder.get_object('folder_name_label')
self.default_text = None
- self.button_properties = self.builder.get_object("button_properties")
- self.combo_hbox = self.builder.get_object("entry_combobox_hbox")
+ self.button_properties = self.builder.get_object('button_properties')
+ self.combo_hbox = self.builder.get_object('entry_combobox_hbox')
# Change the parent of the hbox from the glade Window to this hbox.
self.combo_hbox.reparent(self)
StoredValuesPopup.__init__(self, self.builder, self, max_visible_rows, self.combo_hbox)
@@ -1055,14 +1055,14 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self._setup_config_dialog()
signal_handlers = {
- "on_button_toggle_dropdown_toggled": self._on_button_toggle_dropdown_toggled,
+ 'on_button_toggle_dropdown_toggled': self._on_button_toggle_dropdown_toggled,
'on_entry_text_key_press_event': self._on_entry_text_key_press_event,
'on_stored_values_popup_window_hide': self._on_stored_values_popup_window_hide,
- "on_button_toggle_dropdown_button_press_event": self._on_button_toggle_dropdown_button_press_event,
- "on_entry_combobox_hbox_realize": self._on_entry_combobox_hbox_realize,
- "on_button_open_dialog_clicked": self._on_button_open_dialog_clicked,
- "on_entry_text_focus_out_event": self._on_entry_text_focus_out_event,
- "on_entry_text_changed": self.on_entry_text_changed,
+ 'on_button_toggle_dropdown_button_press_event': self._on_button_toggle_dropdown_button_press_event,
+ 'on_entry_combobox_hbox_realize': self._on_entry_combobox_hbox_realize,
+ 'on_button_open_dialog_clicked': self._on_button_open_dialog_clicked,
+ 'on_entry_text_focus_out_event': self._on_entry_text_focus_out_event,
+ 'on_entry_text_changed': self.on_entry_text_changed,
}
signal_handlers.update(self.signal_handlers)
signal_handlers.update(self.auto_completer.signal_handlers)
@@ -1092,13 +1092,13 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self.combo_hbox.set_tooltip_text(text)
if default_text:
self.default_text = text
- self.button_default.set_tooltip_text("Restore the default value in the text entry:\n%s" % self.default_text)
+ self.button_default.set_tooltip_text('Restore the default value in the text entry:\n%s' % self.default_text)
self.button_default.set_sensitive(True)
# Set text for the filechooser dialog button
- folder_name = ""
+ folder_name = ''
if self.show_folder_name_on_button or not self.path_entry_visible:
folder_name = path_without_trailing_path_sep(text)
- if folder_name is not "/" and os.path.basename(folder_name):
+ if folder_name is not '/' and os.path.basename(folder_name):
folder_name = os.path.basename(folder_name)
self.folder_name_label.set_text(folder_name)
# Only trigger event if text has changed
@@ -1131,7 +1131,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
keyval, mask = gtk.accelerator_parse(self.auto_completer.accelerator_string)
self.auto_completer.accelerator_string = accelerator
except TypeError as ex:
- raise TypeError("TypeError when setting accelerator string: %s" % ex)
+ raise TypeError('TypeError when setting accelerator string: %s' % ex)
def get_auto_complete_enabled(self):
return self.auto_completer.auto_complete_enabled
@@ -1215,7 +1215,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
if do_completion:
self.auto_completer.do_completion()
if emit_event:
- self.emit("show-hidden-files-toggled", show)
+ self.emit('show-hidden-files-toggled', show)
def set_enable_properties(self, enable):
"""
@@ -1247,7 +1247,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
##############
def on_entry_text_changed(self, entry):
- self.emit("text-changed", self.get_text())
+ self.emit('text-changed', self.get_text())
def _on_entry_text_focus_out_event(self, widget, event):
# Update text on the button label
@@ -1376,19 +1376,19 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self.show_hidden_files_checkbutton.set_sensitive(val)
def _setup_config_dialog(self):
- self.config_dialog = self.builder.get_object("completion_config_dialog")
- self.enable_completion = self.builder.get_object("enable_auto_completion_checkbutton")
- self.show_filechooser_checkbutton = self.builder.get_object("show_filechooser_checkbutton")
- self.show_path_entry_checkbutton = self.builder.get_object("show_path_entry_checkbutton")
- set_key_button = self.builder.get_object("set_completion_accelerator_button")
+ self.config_dialog = self.builder.get_object('completion_config_dialog')
+ self.enable_completion = self.builder.get_object('enable_auto_completion_checkbutton')
+ self.show_filechooser_checkbutton = self.builder.get_object('show_filechooser_checkbutton')
+ self.show_path_entry_checkbutton = self.builder.get_object('show_path_entry_checkbutton')
+ set_key_button = self.builder.get_object('set_completion_accelerator_button')
default_set_accelerator_tooltip = set_key_button.get_tooltip_text()
- self.config_short_cuts_frame = self.builder.get_object("config_short_cuts_frame")
- self.config_general_frame = self.builder.get_object("config_general_frame")
- self.accelerator_label = self.builder.get_object("completion_accelerator_label")
- self.visible_rows = self.builder.get_object("visible_rows_spinbutton")
- self.visible_rows_label = self.builder.get_object("visible_rows_label")
- self.show_hidden_files_checkbutton = self.builder.get_object("show_hidden_files_checkbutton")
- self.show_folder_name_on_button_checkbutton = self.builder.get_object("show_folder_name_on_button_checkbutton")
+ self.config_short_cuts_frame = self.builder.get_object('config_short_cuts_frame')
+ self.config_general_frame = self.builder.get_object('config_general_frame')
+ self.accelerator_label = self.builder.get_object('completion_accelerator_label')
+ self.visible_rows = self.builder.get_object('visible_rows_spinbutton')
+ self.visible_rows_label = self.builder.get_object('visible_rows_label')
+ self.show_hidden_files_checkbutton = self.builder.get_object('show_hidden_files_checkbutton')
+ self.show_folder_name_on_button_checkbutton = self.builder.get_object('show_folder_name_on_button_checkbutton')
self.config_dialog.set_transient_for(self.popup_window)
def on_close(widget, event=None):
@@ -1400,11 +1400,11 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
def on_enable_completion_toggled(widget):
self.set_auto_complete_enabled(self.enable_completion.get_active())
- self.emit("auto-complete-enabled-toggled", self.enable_completion.get_active())
+ self.emit('auto-complete-enabled-toggled', self.enable_completion.get_active())
def on_show_filechooser_toggled(widget):
self.set_filechooser_button_visible(self.show_filechooser_checkbutton.get_active())
- self.emit("show-filechooser-toggled", self.show_filechooser_checkbutton.get_active())
+ self.emit('show-filechooser-toggled', self.show_filechooser_checkbutton.get_active())
self.show_folder_name_on_button_checkbutton.set_sensitive(self.show_path_entry_checkbutton.get_active() and
self.show_filechooser_checkbutton.get_active())
if not self.filechooser_visible and not self.path_entry_visible:
@@ -1413,7 +1413,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
def on_show_path_entry_toggled(widget):
self.set_path_entry_visible(self.show_path_entry_checkbutton.get_active())
- self.emit("show-path-entry-toggled", self.show_path_entry_checkbutton.get_active())
+ self.emit('show-path-entry-toggled', self.show_path_entry_checkbutton.get_active())
self.show_folder_name_on_button_checkbutton.set_sensitive(self.show_path_entry_checkbutton.get_active() and
self.show_filechooser_checkbutton.get_active())
if not self.filechooser_visible and not self.path_entry_visible:
@@ -1423,18 +1423,18 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
def on_show_folder_name_on_button(widget):
self.set_show_folder_name_on_button(self.show_folder_name_on_button_checkbutton.get_active())
self._set_path_entry_filechooser_widths()
- self.emit("show-folder-name-on-button", self.show_folder_name_on_button_checkbutton.get_active())
+ self.emit('show-folder-name-on-button', self.show_folder_name_on_button_checkbutton.get_active())
def on_show_hidden_files_toggled(widget):
self.set_show_hidden_files(self.show_hidden_files_checkbutton.get_active(), emit_event=True)
def on_max_rows_changed(widget):
self.set_max_popup_rows(self.visible_rows.get_value_as_int())
- self.emit("max-rows-changed", self.visible_rows.get_value_as_int())
+ self.emit('max-rows-changed', self.visible_rows.get_value_as_int())
def set_accelerator(widget):
self.setting_accelerator_key = True
- set_key_button.set_tooltip_text("Press the accelerator keys for triggering auto-completion")
+ set_key_button.set_tooltip_text('Press the accelerator keys for triggering auto-completion')
self._set_properties_widgets_sensitive(False)
return True
@@ -1455,7 +1455,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
accelerator_mask = 0
self.auto_completer.accelerator_string = gtk.accelerator_name(event.keyval, accelerator_mask)
self.accelerator_label.set_text(gtk.accelerator_get_label(event.keyval, accelerator_mask))
- self.emit("accelerator-set", self.auto_completer.accelerator_string)
+ self.emit('accelerator-set', self.auto_completer.accelerator_string)
stop_setting_accelerator()
return True
else:
@@ -1473,22 +1473,22 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
return True
self.config_dialog_signal_handlers = {
- "on_enable_auto_completion_checkbutton_toggled": on_enable_completion_toggled,
- "on_show_filechooser_checkbutton_toggled": on_show_filechooser_toggled,
- "on_show_path_entry_checkbutton_toggled": on_show_path_entry_toggled,
- "on_show_folder_name_on_button_checkbutton_toggled": on_show_folder_name_on_button,
- "on_config_dialog_button_close_clicked": on_close,
- "on_visible_rows_spinbutton_value_changed": on_max_rows_changed,
- "on_completion_config_dialog_delete_event": on_close,
- "on_set_completion_accelerator_button_pressed": set_accelerator,
- "on_completion_config_dialog_key_release_event": on_completion_config_dialog_key_release_event,
- "on_set_completion_accelerator_button_clicked": on_set_completion_accelerator_button_clicked,
- "on_show_hidden_files_checkbutton_toggled": on_show_hidden_files_toggled,
+ 'on_enable_auto_completion_checkbutton_toggled': on_enable_completion_toggled,
+ 'on_show_filechooser_checkbutton_toggled': on_show_filechooser_toggled,
+ 'on_show_path_entry_checkbutton_toggled': on_show_path_entry_toggled,
+ 'on_show_folder_name_on_button_checkbutton_toggled': on_show_folder_name_on_button,
+ 'on_config_dialog_button_close_clicked': on_close,
+ 'on_visible_rows_spinbutton_value_changed': on_max_rows_changed,
+ 'on_completion_config_dialog_delete_event': on_close,
+ 'on_set_completion_accelerator_button_pressed': set_accelerator,
+ 'on_completion_config_dialog_key_release_event': on_completion_config_dialog_key_release_event,
+ 'on_set_completion_accelerator_button_clicked': on_set_completion_accelerator_button_clicked,
+ 'on_show_hidden_files_checkbutton_toggled': on_show_hidden_files_toggled,
}
gobject.type_register(PathChooserComboBox)
-if __name__ == "__main__":
+if __name__ == '__main__':
import sys
w = gtk.Window()
w.set_position(gtk.WIN_POS_CENTER)
@@ -1499,7 +1499,7 @@ if __name__ == "__main__":
box1 = gtk.VBox(gtk.FALSE, 0)
def get_resource2(filename):
- return "%s/glade/%s" % (os.path.abspath(os.path.dirname(sys.argv[0])), filename)
+ return '%s/glade/%s' % (os.path.abspath(os.path.dirname(sys.argv[0])), filename)
# Override get_resource which fetches from deluge install
# get_resource = get_resource2
@@ -1511,21 +1511,21 @@ if __name__ == "__main__":
box1.add(entry2)
test_paths = [
- "/home/bro/Downloads",
- "/media/Movies-HD",
- "/media/torrent/in",
- "/media/Live-show/Misc",
- "/media/Live-show/Consert",
- "/media/Series/1/",
- "/media/Series/2",
- "/media/Series/17",
- "/media/Series/18",
- "/media/Series/19"
+ '/home/bro/Downloads',
+ '/media/Movies-HD',
+ '/media/torrent/in',
+ '/media/Live-show/Misc',
+ '/media/Live-show/Consert',
+ '/media/Series/1/',
+ '/media/Series/2',
+ '/media/Series/17',
+ '/media/Series/18',
+ '/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/",
+ 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_filechooser_button_visible(False)
@@ -1533,10 +1533,10 @@ if __name__ == "__main__":
entry2.set_filechooser_button_enabled(False)
def list_value_added_event(widget, values):
- print("Current list values:", widget.get_values())
+ print('Current list values:', widget.get_values())
- entry1.connect("list-value-added", list_value_added_event)
- entry2.connect("list-value-added", list_value_added_event)
+ entry1.connect('list-value-added', list_value_added_event)
+ entry2.connect('list-value-added', list_value_added_event)
w.add(box1)
w.show_all()
gtk.main()
diff --git a/deluge/ui/gtkui/peers_tab.py b/deluge/ui/gtkui/peers_tab.py
index 5202fc9d4..0614b4e81 100644
--- a/deluge/ui/gtkui/peers_tab.py
+++ b/deluge/ui/gtkui/peers_tab.py
@@ -26,33 +26,33 @@ log = logging.getLogger(__name__)
def cell_data_progress(column, cell, model, row, data):
value = model.get_value(row, data) * 100
- cell.set_property("value", value)
- cell.set_property("text", "%i%%" % value)
+ cell.set_property('value', value)
+ cell.set_property('text', '%i%%' % value)
class PeersTab(Tab):
def __init__(self):
Tab.__init__(self)
- builder = component.get("MainWindow").get_builder()
-
- self._name = "Peers"
- self._child_widget = builder.get_object("peers_tab")
- self._tab_label = builder.get_object("peers_tab_label")
- self.peer_menu = builder.get_object("menu_peer_tab")
- component.get("MainWindow").connect_signals({
- "on_menuitem_add_peer_activate": self._on_menuitem_add_peer_activate,
+ builder = component.get('MainWindow').get_builder()
+
+ self._name = 'Peers'
+ self._child_widget = builder.get_object('peers_tab')
+ self._tab_label = builder.get_object('peers_tab_label')
+ self.peer_menu = builder.get_object('menu_peer_tab')
+ component.get('MainWindow').connect_signals({
+ 'on_menuitem_add_peer_activate': self._on_menuitem_add_peer_activate,
})
- self.listview = builder.get_object("peers_listview")
+ self.listview = builder.get_object('peers_listview')
self.listview.props.has_tooltip = True
- self.listview.connect("button-press-event", self._on_button_press_event)
- self.listview.connect("query-tooltip", self._on_query_tooltip)
+ self.listview.connect('button-press-event', self._on_button_press_event)
+ self.listview.connect('query-tooltip', self._on_query_tooltip)
# country pixbuf, ip, client, downspeed, upspeed, country code, int_ip, seed/peer icon, progress
self.liststore = gtk.ListStore(gtk.gdk.Pixbuf, str, str, int, int, str, float, gtk.gdk.Pixbuf, float)
self.cached_flag_pixbufs = {}
- self.seed_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap("seeding16.png"))
- self.peer_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap("downloading16.png"))
+ self.seed_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap('seeding16.png'))
+ self.peer_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap('downloading16.png'))
# key is ip address, item is row iter
self.peers = {}
@@ -61,7 +61,7 @@ class PeersTab(Tab):
column = gtk.TreeViewColumn()
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
- column.add_attribute(render, "pixbuf", 0)
+ column.add_attribute(render, 'pixbuf', 0)
column.set_sort_column_id(5)
column.set_clickable(True)
column.set_resizable(True)
@@ -71,13 +71,13 @@ class PeersTab(Tab):
self.listview.append_column(column)
# Address column
- column = gtk.TreeViewColumn(_("Address"))
+ column = gtk.TreeViewColumn(_('Address'))
render = gtk.CellRendererPixbuf()
column.pack_start(render, False)
- column.add_attribute(render, "pixbuf", 7)
+ column.add_attribute(render, 'pixbuf', 7)
render = gtk.CellRendererText()
column.pack_start(render, False)
- column.add_attribute(render, "text", 1)
+ column.add_attribute(render, 'text', 1)
column.set_sort_column_id(6)
column.set_clickable(True)
column.set_resizable(True)
@@ -87,10 +87,10 @@ class PeersTab(Tab):
self.listview.append_column(column)
# Client column
- column = gtk.TreeViewColumn(_("Client"))
+ column = gtk.TreeViewColumn(_('Client'))
render = gtk.CellRendererText()
column.pack_start(render, False)
- column.add_attribute(render, "text", 2)
+ column.add_attribute(render, 'text', 2)
column.set_sort_column_id(2)
column.set_clickable(True)
column.set_resizable(True)
@@ -100,7 +100,7 @@ class PeersTab(Tab):
self.listview.append_column(column)
# Progress column
- column = gtk.TreeViewColumn(_("Progress"))
+ column = gtk.TreeViewColumn(_('Progress'))
render = gtk.CellRendererProgress()
column.pack_start(render, True)
column.set_cell_data_func(render, cell_data_progress, 8)
@@ -113,7 +113,7 @@ class PeersTab(Tab):
self.listview.append_column(column)
# Down Speed column
- column = gtk.TreeViewColumn(_("Down Speed"))
+ column = gtk.TreeViewColumn(_('Down Speed'))
render = gtk.CellRendererText()
column.pack_start(render, False)
column.set_cell_data_func(render, cell_data_speed_down, 3)
@@ -126,7 +126,7 @@ class PeersTab(Tab):
self.listview.append_column(column)
# Up Speed column
- column = gtk.TreeViewColumn(_("Up Speed"))
+ column = gtk.TreeViewColumn(_('Up Speed'))
render = gtk.CellRendererText()
column.pack_start(render, False)
column.set_cell_data_func(render, cell_data_speed_up, 4)
@@ -152,50 +152,50 @@ class PeersTab(Tab):
# Setup state dict
state = {
- "columns": {},
- "sort_id": column_id,
- "sort_order": int(sort_order) if sort_order else None
+ 'columns': {},
+ 'sort_id': column_id,
+ '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()
+ state['columns'][column.get_title()] = {
+ 'position': index,
+ 'width': column.get_width()
}
- save_pickled_state_file("peers_tab.state", state)
+ save_pickled_state_file('peers_tab.state', state)
def load_state(self):
- state = load_pickled_state_file("peers_tab.state")
+ state = load_pickled_state_file('peers_tab.state')
if state is None:
return
- if len(state["columns"]) != len(self.listview.get_columns()):
- log.warning("peers_tab.state is not compatible! rejecting..")
+ if len(state['columns']) != len(self.listview.get_columns()):
+ log.warning('peers_tab.state is not compatible! rejecting..')
return
- if state["sort_id"] and state["sort_order"] is not None:
- self.liststore.set_sort_column_id(state["sort_id"], state["sort_order"])
+ if state['sort_id'] and state['sort_order'] is not None:
+ self.liststore.set_sort_column_id(state['sort_id'], state['sort_order'])
for (index, column) in enumerate(self.listview.get_columns()):
cname = column.get_title()
- if cname in state["columns"]:
- cstate = state["columns"][cname]
+ if cname in state['columns']:
+ cstate = state['columns'][cname]
column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
- column.set_fixed_width(cstate["width"] if cstate["width"] > 0 else 10)
- if state["sort_id"] == index and state["sort_order"] is not None:
+ column.set_fixed_width(cstate['width'] if cstate['width'] > 0 else 10)
+ if state['sort_id'] == index and state['sort_order'] is not None:
column.set_sort_indicator(True)
- column.set_sort_order(state["sort_order"])
- if cstate["position"] != index:
+ column.set_sort_order(state['sort_order'])
+ if cstate['position'] != index:
# Column is in wrong position
- if cstate["position"] == 0:
+ if cstate['position'] == 0:
self.listview.move_column_after(column, None)
- elif self.listview.get_columns()[cstate["position"] - 1].get_title() != cname:
- self.listview.move_column_after(column, self.listview.get_columns()[cstate["position"] - 1])
+ elif self.listview.get_columns()[cstate['position'] - 1].get_title() != cname:
+ self.listview.move_column_after(column, self.listview.get_columns()[cstate['position'] - 1])
def update(self):
# Get the first selected torrent
- torrent_id = component.get("TorrentView").get_selected_torrents()
+ torrent_id = component.get('TorrentView').get_selected_torrents()
# Only use the first torrent in the list or return if None selected
if len(torrent_id) != 0:
@@ -211,7 +211,7 @@ class PeersTab(Tab):
self.peers = {}
self.torrent_id = torrent_id
- component.get("SessionProxy").get_torrent_status(torrent_id, ["peers"]).addCallback(self._on_get_torrent_status)
+ component.get('SessionProxy').get_torrent_status(torrent_id, ['peers']).addCallback(self._on_get_torrent_status)
def get_flag_pixbuf(self, country):
if not country.strip():
@@ -222,34 +222,34 @@ class PeersTab(Tab):
try:
self.cached_flag_pixbufs[country] = gtk.gdk.pixbuf_new_from_file(
deluge.common.resource_filename(
- "deluge",
- os.path.join("ui", "data", "pixmaps", "flags", country.lower() + ".png")))
+ 'deluge',
+ os.path.join('ui', 'data', 'pixmaps', 'flags', country.lower() + '.png')))
except Exception as ex:
- log.debug("Unable to load flag: %s", ex)
+ log.debug('Unable to load flag: %s', ex)
return None
return self.cached_flag_pixbufs[country]
def _on_get_torrent_status(self, status):
new_ips = set()
- for peer in status["peers"]:
- new_ips.add(peer["ip"])
- if peer["ip"] in self.peers:
+ for peer in status['peers']:
+ new_ips.add(peer['ip'])
+ if peer['ip'] in self.peers:
# We already have this peer in our list, so lets just update it
- row = self.peers[peer["ip"]]
+ row = self.peers[peer['ip']]
if not self.liststore.iter_is_valid(row):
# This iter is invalid, delete it and continue to next iteration
- del self.peers[peer["ip"]]
+ del self.peers[peer['ip']]
continue
values = self.liststore.get(row, 3, 4, 5, 7, 8)
- if peer["down_speed"] != values[0]:
- self.liststore.set_value(row, 3, peer["down_speed"])
- if peer["up_speed"] != values[1]:
- self.liststore.set_value(row, 4, peer["up_speed"])
- if peer["country"] != values[2]:
- self.liststore.set_value(row, 5, peer["country"])
- self.liststore.set_value(row, 0, self.get_flag_pixbuf(peer["country"]))
- if peer["seed"]:
+ if peer['down_speed'] != values[0]:
+ self.liststore.set_value(row, 3, peer['down_speed'])
+ if peer['up_speed'] != values[1]:
+ self.liststore.set_value(row, 4, peer['up_speed'])
+ if peer['country'] != values[2]:
+ self.liststore.set_value(row, 5, peer['country'])
+ self.liststore.set_value(row, 0, self.get_flag_pixbuf(peer['country']))
+ if peer['seed']:
icon = self.seed_pixbuf
else:
icon = self.peer_pixbuf
@@ -257,43 +257,43 @@ class PeersTab(Tab):
if icon != values[3]:
self.liststore.set_value(row, 7, icon)
- if peer["progress"] != values[4]:
- self.liststore.set_value(row, 8, peer["progress"])
+ if peer['progress'] != values[4]:
+ self.liststore.set_value(row, 8, peer['progress'])
else:
# Peer is not in list so we need to add it
# Create an int IP address for sorting purposes
- if peer["ip"].count(":") == 1:
+ 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))])
- peer_ip = peer["ip"]
+ for byte, shift in zip(peer['ip'].split(':')[0].split('.'), (24, 16, 8, 0))])
+ peer_ip = peer['ip']
else:
# This is an IPv6 address
import socket
import binascii
# Split out the :port
- ip = ":".join(peer["ip"].split(":")[:-1])
+ ip = ':'.join(peer['ip'].split(':')[:-1])
ip_int = int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)
- peer_ip = "[%s]:%s" % (ip, peer["ip"].split(":")[-1])
+ peer_ip = '[%s]:%s' % (ip, peer['ip'].split(':')[-1])
- if peer["seed"]:
+ if peer['seed']:
icon = self.seed_pixbuf
else:
icon = self.peer_pixbuf
row = self.liststore.append([
- self.get_flag_pixbuf(peer["country"]),
+ self.get_flag_pixbuf(peer['country']),
peer_ip,
- peer["client"],
- peer["down_speed"],
- peer["up_speed"],
- peer["country"],
+ peer['client'],
+ peer['down_speed'],
+ peer['up_speed'],
+ peer['country'],
float(ip_int),
icon,
- peer["progress"]])
+ peer['progress']])
- self.peers[peer["ip"]] = row
+ self.peers[peer['ip']] = row
# Now we need to remove any ips that were not in status["peers"] list
for ip in set(self.peers).difference(new_ips):
@@ -305,7 +305,7 @@ class PeersTab(Tab):
def _on_button_press_event(self, widget, event):
"""This is a callback for showing the right-click context menu."""
- log.debug("on_button_press_event")
+ log.debug('on_button_press_event')
# We only care about right-clicks
if self.torrent_id and event.button == 3:
self.peer_menu.popup(None, None, None, event.button, event.time)
@@ -318,7 +318,7 @@ class PeersTab(Tab):
model, path, _iter = widget.get_tooltip_context(x, y, keyboard_tip)
country_code = model.get(_iter, 5)[0]
- if country_code != " " and country_code in COUNTRIES:
+ if country_code != ' ' and country_code in COUNTRIES:
tooltip.set_text(COUNTRIES[country_code])
# widget here is self.listview
widget.set_tooltip_cell(tooltip, path, widget.get_column(0),
@@ -329,27 +329,27 @@ class PeersTab(Tab):
def _on_menuitem_add_peer_activate(self, menuitem):
"""This is a callback for manually adding a peer"""
- log.debug("on_menuitem_add_peer")
+ log.debug('on_menuitem_add_peer')
builder = gtk.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")
+ peer_dialog = builder.get_object('connect_peer_dialog')
+ txt_ip = builder.get_object('txt_ip')
response = peer_dialog.run()
if response:
value = txt_ip.get_text()
if value and ':' in value:
if ']' in value:
# ipv6
- ip = value.split("]")[0][1:]
- port = value.split("]")[1][1:]
+ ip = value.split(']')[0][1:]
+ port = value.split(']')[1][1:]
else:
# ipv4
- ip = value.split(":")[0]
- port = value.split(":")[1]
+ ip = value.split(':')[0]
+ port = value.split(':')[1]
if deluge.common.is_ip(ip):
- log.debug("adding peer %s to %s", value, self.torrent_id)
+ log.debug('adding peer %s to %s', value, self.torrent_id)
client.core.connect_peer(self.torrent_id, ip, port)
peer_dialog.destroy()
return True
diff --git a/deluge/ui/gtkui/piecesbar.py b/deluge/ui/gtkui/piecesbar.py
index c6e44dd79..88db3b0e5 100644
--- a/deluge/ui/gtkui/piecesbar.py
+++ b/deluge/ui/gtkui/piecesbar.py
@@ -18,12 +18,12 @@ from cairo import FORMAT_ARGB32, Context, ImageSurface
from deluge.configmanager import ConfigManager
-COLOR_STATES = ["missing", "waiting", "downloading", "completed"]
+COLOR_STATES = ['missing', 'waiting', 'downloading', 'completed']
class PiecesBar(gtk.DrawingArea):
# Draw in response to an expose-event
- __gsignals__ = {"expose-event": "override"}
+ __gsignals__ = {'expose-event': 'override'}
def __init__(self):
gtk.DrawingArea.__init__(self)
@@ -36,13 +36,13 @@ class PiecesBar(gtk.DrawingArea):
del pb, pb_style
self.set_size_request(-1, 25)
- self.gtkui_config = ConfigManager("gtkui.conf")
+ self.gtkui_config = ConfigManager('gtkui.conf')
self.width = self.prev_width = 0
self.height = self.prev_height = 0
self.pieces = self.prev_pieces = ()
self.num_pieces = None
- self.text = self.prev_text = ""
+ self.text = self.prev_text = ''
self.fraction = self.prev_fraction = 0
self.progress_overlay = self.text_overlay = self.pieces_overlay = None
self.cr = None
@@ -113,10 +113,10 @@ class PiecesBar(gtk.DrawingArea):
pieces = self.pieces
elif self.num_pieces:
# Completed torrents do not send any pieces so create list using 'completed' state.
- pieces = [COLOR_STATES.index("completed")] * self.num_pieces
+ 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]]
+ 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])
@@ -196,7 +196,7 @@ class PiecesBar(gtk.DrawingArea):
def clear(self):
self.pieces = self.prev_pieces = ()
self.num_pieces = None
- self.text = self.prev_text = ""
+ self.text = self.prev_text = ''
self.fraction = self.prev_fraction = 0
self.progress_overlay = self.text_overlay = self.pieces_overlay = None
self.cr = None
diff --git a/deluge/ui/gtkui/pluginmanager.py b/deluge/ui/gtkui/pluginmanager.py
index ab53a53b8..1530b0b7e 100644
--- a/deluge/ui/gtkui/pluginmanager.py
+++ b/deluge/ui/gtkui/pluginmanager.py
@@ -19,32 +19,32 @@ log = logging.getLogger(__name__)
class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Component):
def __init__(self):
- component.Component.__init__(self, "PluginManager")
- self.config = ConfigManager("gtkui.conf")
+ 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_apply_prefs': [],
+ 'on_show_prefs': []
}
- client.register_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event)
- client.register_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event)
+ client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event)
+ client.register_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event)
def register_hook(self, hook, function):
"""Register a hook function with the plugin manager"""
try:
self.hooks[hook].append(function)
except KeyError:
- log.warning("Plugin attempting to register invalid hook.")
+ log.warning('Plugin attempting to register invalid hook.')
def deregister_hook(self, hook, function):
"""Deregisters a hook function"""
try:
self.hooks[hook].remove(function)
except KeyError:
- log.warning("Unable to deregister hook %s", hook)
+ log.warning('Unable to deregister hook %s', hook)
def start(self):
"""Start the plugin manager"""
@@ -61,7 +61,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
pass
def _on_get_enabled_plugins(self, enabled_plugins):
- log.debug("Core has these plugins enabled: %s", enabled_plugins)
+ log.debug('Core has these plugins enabled: %s', enabled_plugins)
for plugin in enabled_plugins:
self.enable_plugin(plugin)
@@ -81,53 +81,53 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
"""This hook is run before the user is shown the preferences dialog.
It is designed so that plugins can update their preference page with
the config."""
- log.debug("run_on_show_prefs")
- for function in self.hooks["on_show_prefs"]:
+ log.debug('run_on_show_prefs')
+ for function in self.hooks['on_show_prefs']:
function()
def run_on_apply_prefs(self):
"""This hook is run after the user clicks Apply or OK in the preferences
dialog.
"""
- log.debug("run_on_apply_prefs")
- for function in self.hooks["on_apply_prefs"]:
+ log.debug('run_on_apply_prefs')
+ for function in self.hooks['on_apply_prefs']:
function()
# Plugin functions.. will likely move to own class..
def add_torrentview_text_column(self, *args, **kwargs):
- return component.get("TorrentView").add_text_column(*args, **kwargs)
+ return component.get('TorrentView').add_text_column(*args, **kwargs)
def remove_torrentview_column(self, *args):
- return component.get("TorrentView").remove_column(*args)
+ return component.get('TorrentView').remove_column(*args)
def add_toolbar_separator(self):
- return component.get("ToolBar").add_separator()
+ return component.get('ToolBar').add_separator()
def add_toolbar_button(self, *args, **kwargs):
- return component.get("ToolBar").add_toolbutton(*args, **kwargs)
+ return component.get('ToolBar').add_toolbutton(*args, **kwargs)
def remove_toolbar_button(self, *args):
- return component.get("ToolBar").remove(*args)
+ return component.get('ToolBar').remove(*args)
def add_torrentmenu_menu(self, *args):
- return component.get("MenuBar").torrentmenu.append(*args)
+ return component.get('MenuBar').torrentmenu.append(*args)
def add_torrentmenu_separator(self):
- return component.get("MenuBar").add_torrentmenu_separator()
+ return component.get('MenuBar').add_torrentmenu_separator()
def remove_torrentmenu_item(self, *args):
- return component.get("MenuBar").torrentmenu.remove(*args)
+ return component.get('MenuBar').torrentmenu.remove(*args)
def add_preferences_page(self, *args):
- return component.get("Preferences").add_page(*args)
+ return component.get('Preferences').add_page(*args)
def remove_preferences_page(self, *args):
- return component.get("Preferences").remove_page(*args)
+ return component.get('Preferences').remove_page(*args)
def update_torrent_view(self, *args):
- return component.get("TorrentView").update(*args)
+ return component.get('TorrentView').update(*args)
def get_selected_torrents(self):
"""Returns a list of the selected torrent_ids"""
- return component.get("TorrentView").get_selected_torrents()
+ return component.get('TorrentView').get_selected_torrents()
diff --git a/deluge/ui/gtkui/preferences.py b/deluge/ui/gtkui/preferences.py
index 2663b9dbd..35db664ad 100644
--- a/deluge/ui/gtkui/preferences.py
+++ b/deluge/ui/gtkui/preferences.py
@@ -34,118 +34,118 @@ ACCOUNTS_USERNAME, ACCOUNTS_LEVEL, ACCOUNTS_PASSWORD = range(3)
COLOR_MISSING, COLOR_WAITING, COLOR_DOWNLOADING, COLOR_COMPLETED = range(4)
COLOR_STATES = {
- "missing": COLOR_MISSING,
- "waiting": COLOR_WAITING,
- "downloading": COLOR_DOWNLOADING,
- "completed": COLOR_COMPLETED
+ 'missing': COLOR_MISSING,
+ 'waiting': COLOR_WAITING,
+ 'downloading': COLOR_DOWNLOADING,
+ 'completed': COLOR_COMPLETED
}
class Preferences(component.Component):
def __init__(self):
- component.Component.__init__(self, "Preferences")
+ 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")))
- self.pref_dialog = self.builder.get_object("pref_dialog")
- self.pref_dialog.set_transient_for(component.get("MainWindow").window)
+ '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())
- self.treeview = self.builder.get_object("treeview")
- self.notebook = self.builder.get_object("notebook")
- self.gtkui_config = ConfigManager("gtkui.conf")
+ self.treeview = self.builder.get_object('treeview')
+ self.notebook = self.builder.get_object('notebook')
+ self.gtkui_config = ConfigManager('gtkui.conf')
self.window_open = False
self.load_pref_dialog_state()
- self.builder.get_object("image_magnet").set_from_file(
- deluge.common.get_pixmap("magnet.png"))
+ self.builder.get_object('image_magnet').set_from_file(
+ deluge.common.get_pixmap('magnet.png'))
# Hide the unused associate magnet button on OSX see: #2420
if deluge.common.osx_check():
- self.builder.get_object("button_associate_magnet").hide()
+ self.builder.get_object('button_associate_magnet').hide()
# Setup the liststore for the categories (tab pages)
self.liststore = gtk.ListStore(int, str)
self.treeview.set_model(self.liststore)
render = gtk.CellRendererText()
- column = gtk.TreeViewColumn(_("Categories"), render, text=1)
+ column = gtk.TreeViewColumn(_('Categories'), render, text=1)
self.treeview.append_column(column)
# Add the default categories
i = 0
- for category in (_("Interface"), _("Downloads"), _("Bandwidth"), _("Queue"), _("Network"),
- _("Proxy"), _("Cache"), _("Other"), _("Daemon"), _("Plugins"), "_separator_"):
+ for category in (_('Interface'), _('Downloads'), _('Bandwidth'), _('Queue'), _('Network'),
+ _('Proxy'), _('Cache'), _('Other'), _('Daemon'), _('Plugins'), '_separator_'):
self.liststore.append([i, category])
i += 1
def set_separator(model, _iter, data=None):
- if model.get_value(_iter, 1) == "_separator_":
+ if model.get_value(_iter, 1) == '_separator_':
return True
self.treeview.set_row_separator_func(set_separator)
# Setup accounts tab lisview
self.accounts_levels_mapping = None
- self.accounts_authlevel = self.builder.get_object("accounts_authlevel")
+ self.accounts_authlevel = self.builder.get_object('accounts_authlevel')
self.accounts_liststore = gtk.ListStore(str, str, str, int)
self.accounts_liststore.set_sort_column_id(ACCOUNTS_USERNAME, gtk.SORT_ASCENDING)
- self.accounts_listview = self.builder.get_object("accounts_listview")
+ 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)
self.accounts_listview.set_model(self.accounts_liststore)
- self.accounts_listview.get_selection().connect("changed", self._on_accounts_selection_changed)
- self.accounts_frame = self.builder.get_object("AccountsFrame")
+ self.accounts_listview.get_selection().connect('changed', self._on_accounts_selection_changed)
+ self.accounts_frame = self.builder.get_object('AccountsFrame')
# Setup plugin tab listview
# The third entry is for holding translated plugin names
self.plugin_liststore = gtk.ListStore(str, bool, str)
self.plugin_liststore.set_sort_column_id(0, gtk.SORT_ASCENDING)
- self.plugin_listview = self.builder.get_object("plugin_listview")
+ self.plugin_listview = self.builder.get_object('plugin_listview')
self.plugin_listview.set_model(self.plugin_liststore)
render = gtk.CellRendererToggle()
- render.connect("toggled", self.on_plugin_toggled)
- render.set_property("activatable", True)
- self.plugin_listview.append_column(gtk.TreeViewColumn(_("Enabled"), render, active=1))
- self.plugin_listview.append_column(gtk.TreeViewColumn(_("Plugin"), gtk.CellRendererText(), text=2))
+ render.connect('toggled', self.on_plugin_toggled)
+ render.set_property('activatable', True)
+ self.plugin_listview.append_column(gtk.TreeViewColumn(_('Enabled'), render, active=1))
+ self.plugin_listview.append_column(gtk.TreeViewColumn(_('Plugin'), gtk.CellRendererText(), text=2))
# Connect to the 'changed' event of TreeViewSelection to get selection
# changes.
- self.treeview.get_selection().connect("changed", self.on_selection_changed)
+ self.treeview.get_selection().connect('changed', self.on_selection_changed)
- self.plugin_listview.get_selection().connect("changed", self.on_plugin_selection_changed)
+ self.plugin_listview.get_selection().connect('changed', self.on_plugin_selection_changed)
self.builder.connect_signals({
- "on_pref_dialog_delete_event": self.on_pref_dialog_delete_event,
- "on_button_ok_clicked": self.on_button_ok_clicked,
- "on_button_apply_clicked": self.on_button_apply_clicked,
- "on_button_cancel_clicked": self.on_button_cancel_clicked,
- "on_toggle": self.on_toggle,
- "on_test_port_clicked": self.on_test_port_clicked,
- "on_button_plugin_install_clicked": self._on_button_plugin_install_clicked,
- "on_button_rescan_plugins_clicked": self._on_button_rescan_plugins_clicked,
- "on_button_find_plugins_clicked": self._on_button_find_plugins_clicked,
- "on_button_cache_refresh_clicked": self._on_button_cache_refresh_clicked,
- "on_combo_encryption_changed": self._on_combo_encryption_changed,
- "on_combo_proxy_type_changed": self._on_combo_proxy_type_changed,
- "on_button_associate_magnet_clicked": self._on_button_associate_magnet_clicked,
- "on_accounts_add_clicked": self._on_accounts_add_clicked,
- "on_accounts_delete_clicked": self._on_accounts_delete_clicked,
- "on_accounts_edit_clicked": self._on_accounts_edit_clicked,
- "on_piecesbar_toggle_toggled": self._on_piecesbar_toggle_toggled,
- "on_completed_color_set": self._on_completed_color_set,
- "on_revert_color_completed_clicked": self._on_revert_color_completed_clicked,
- "on_downloading_color_set": self._on_downloading_color_set,
- "on_revert_color_downloading_clicked": self._on_revert_color_downloading_clicked,
- "on_waiting_color_set": self._on_waiting_color_set,
- "on_revert_color_waiting_clicked": self._on_revert_color_waiting_clicked,
- "on_missing_color_set": self._on_missing_color_set,
- "on_revert_color_missing_clicked": self._on_revert_color_missing_clicked,
- "on_pref_dialog_configure_event": self.on_pref_dialog_configure_event,
- "on_checkbutton_language_toggled": self._on_checkbutton_language_toggled,
+ 'on_pref_dialog_delete_event': self.on_pref_dialog_delete_event,
+ 'on_button_ok_clicked': self.on_button_ok_clicked,
+ 'on_button_apply_clicked': self.on_button_apply_clicked,
+ 'on_button_cancel_clicked': self.on_button_cancel_clicked,
+ 'on_toggle': self.on_toggle,
+ 'on_test_port_clicked': self.on_test_port_clicked,
+ 'on_button_plugin_install_clicked': self._on_button_plugin_install_clicked,
+ 'on_button_rescan_plugins_clicked': self._on_button_rescan_plugins_clicked,
+ 'on_button_find_plugins_clicked': self._on_button_find_plugins_clicked,
+ 'on_button_cache_refresh_clicked': self._on_button_cache_refresh_clicked,
+ 'on_combo_encryption_changed': self._on_combo_encryption_changed,
+ 'on_combo_proxy_type_changed': self._on_combo_proxy_type_changed,
+ 'on_button_associate_magnet_clicked': self._on_button_associate_magnet_clicked,
+ 'on_accounts_add_clicked': self._on_accounts_add_clicked,
+ 'on_accounts_delete_clicked': self._on_accounts_delete_clicked,
+ 'on_accounts_edit_clicked': self._on_accounts_edit_clicked,
+ 'on_piecesbar_toggle_toggled': self._on_piecesbar_toggle_toggled,
+ 'on_completed_color_set': self._on_completed_color_set,
+ 'on_revert_color_completed_clicked': self._on_revert_color_completed_clicked,
+ 'on_downloading_color_set': self._on_downloading_color_set,
+ 'on_revert_color_downloading_clicked': self._on_revert_color_downloading_clicked,
+ 'on_waiting_color_set': self._on_waiting_color_set,
+ 'on_revert_color_waiting_clicked': self._on_revert_color_waiting_clicked,
+ 'on_missing_color_set': self._on_missing_color_set,
+ 'on_revert_color_missing_clicked': self._on_revert_color_missing_clicked,
+ 'on_pref_dialog_configure_event': self.on_pref_dialog_configure_event,
+ 'on_checkbutton_language_toggled': self._on_checkbutton_language_toggled,
})
if not deluge.common.osx_check() and not deluge.common.windows_check():
@@ -154,12 +154,12 @@ class Preferences(component.Component):
except ImportError:
pass
else:
- self.builder.get_object("alignment_tray_type").set_visible(True)
+ self.builder.get_object('alignment_tray_type').set_visible(True)
from deluge.ui.gtkui.gtkui import DEFAULT_PREFS
self.COLOR_DEFAULTS = {}
- for key in ("missing", "waiting", "downloading", "completed"):
- self.COLOR_DEFAULTS[key] = DEFAULT_PREFS["pieces_color_%s" % key][:]
+ for key in ('missing', 'waiting', 'downloading', 'completed'):
+ self.COLOR_DEFAULTS[key] = DEFAULT_PREFS['pieces_color_%s' % key][:]
del DEFAULT_PREFS
# These get updated by requests done to the core
@@ -170,34 +170,34 @@ class Preferences(component.Component):
self.load_languages()
def setup_path_choosers(self):
- self.download_location_hbox = self.builder.get_object("hbox_download_to_path_chooser")
- self.download_location_path_chooser = PathChooser("download_location_paths_list")
+ self.download_location_hbox = self.builder.get_object('hbox_download_to_path_chooser')
+ self.download_location_path_chooser = PathChooser('download_location_paths_list')
self.download_location_hbox.add(self.download_location_path_chooser)
self.download_location_hbox.show_all()
- self.move_completed_hbox = self.builder.get_object("hbox_move_completed_to_path_chooser")
- self.move_completed_path_chooser = PathChooser("move_completed_paths_list")
+ self.move_completed_hbox = self.builder.get_object('hbox_move_completed_to_path_chooser')
+ self.move_completed_path_chooser = PathChooser('move_completed_paths_list')
self.move_completed_hbox.add(self.move_completed_path_chooser)
self.move_completed_hbox.show_all()
- self.copy_torrents_to_hbox = self.builder.get_object("hbox_copy_torrent_files_path_chooser")
- self.copy_torrent_files_path_chooser = PathChooser("copy_torrent_files_to_paths_list")
+ self.copy_torrents_to_hbox = self.builder.get_object('hbox_copy_torrent_files_path_chooser')
+ self.copy_torrent_files_path_chooser = PathChooser('copy_torrent_files_to_paths_list')
self.copy_torrents_to_hbox.add(self.copy_torrent_files_path_chooser)
self.copy_torrents_to_hbox.show_all()
def load_languages(self):
- self.language_combo = self.builder.get_object("combobox_language")
- self.language_checkbox = self.builder.get_object("checkbutton_language")
+ self.language_combo = self.builder.get_object('combobox_language')
+ self.language_checkbox = self.builder.get_object('checkbutton_language')
lang_model = self.language_combo.get_model()
langs = lang.get_languages()
index = -1
for i, l in enumerate(langs):
lang_code, name = l
lang_model.append([lang_code, name])
- if self.gtkui_config["language"] == lang_code:
+ if self.gtkui_config['language'] == lang_code:
index = i
- if self.gtkui_config["language"] is None:
+ if self.gtkui_config['language'] is None:
self.language_checkbox.set_active(True)
self.language_combo.set_visible(False)
else:
@@ -217,7 +217,7 @@ class Preferences(component.Component):
vbox = gtk.VBox()
label = gtk.Label()
label.set_use_markup(True)
- label.set_markup("<b><i><big>" + name + "</big></i></b>")
+ label.set_markup('<b><i><big>' + name + '</big></i></b>')
label.set_alignment(0.00, 0.50)
label.set_padding(10, 10)
vbox.pack_start(label, False, True, 0)
@@ -274,7 +274,7 @@ class Preferences(component.Component):
self.treeview.get_selection().select_path(index)
break
- component.get("PluginManager").run_on_show_prefs()
+ component.get('PluginManager').run_on_show_prefs()
# Update the preferences dialog to reflect current config settings
self.core_config = {}
@@ -318,84 +318,84 @@ class Preferences(component.Component):
def _show(self):
self.is_connected = self.core_config != {} and self.core_config is not None
core_widgets = {
- "chk_move_completed": ("active", "move_completed"),
- "chk_copy_torrent_file": ("active", "copy_torrent_file"),
- "chk_del_copy_torrent_file": ("active", "del_copy_torrent_file"),
- "chk_pre_allocation": ("active", "pre_allocate_storage"),
- "chk_prioritize_first_last_pieces": ("active", "prioritize_first_last_pieces"),
- "chk_sequential_download": ("active", "sequential_download"),
- "chk_add_paused": ("active", "add_paused"),
- "active_port_label": ("text", lambda: str(self.active_port)),
- "spin_incoming_port": ("value", lambda: self.core_config["listen_ports"][0]),
- "chk_random_incoming_port": ("active", "random_port"),
- "spin_outgoing_port_min": ("value", lambda: self.core_config["outgoing_ports"][0]),
- "spin_outgoing_port_max": ("value", lambda: self.core_config["outgoing_ports"][1]),
- "chk_random_outgoing_ports": ("active", "random_outgoing_ports"),
- "entry_interface": ("text", "listen_interface"),
- "entry_peer_tos": ("text", "peer_tos"),
- "chk_dht": ("active", "dht"),
- "chk_upnp": ("active", "upnp"),
- "chk_natpmp": ("active", "natpmp"),
- "chk_utpex": ("active", "utpex"),
- "chk_lsd": ("active", "lsd"),
- "chk_new_releases": ("active", "new_release_check"),
- "chk_send_info": ("active", "send_info"),
- "entry_geoip": ("text", "geoip_db_location"),
- "combo_encin": ("active", "enc_in_policy"),
- "combo_encout": ("active", "enc_out_policy"),
- "combo_enclevel": ("active", "enc_level"),
- "spin_max_connections_global": ("value", "max_connections_global"),
- "spin_max_download": ("value", "max_download_speed"),
- "spin_max_upload": ("value", "max_upload_speed"),
- "spin_max_upload_slots_global": ("value", "max_upload_slots_global"),
- "spin_max_half_open_connections": ("value", "max_connections_per_second"),
- "spin_max_connections_per_second": ("value", "max_connections_per_second"),
- "chk_ignore_limits_on_local_network": ("active", "ignore_limits_on_local_network"),
- "chk_rate_limit_ip_overhead": ("active", "rate_limit_ip_overhead"),
- "chk_anonymous_mode": ("active", "anonymous_mode"),
- "spin_max_connections_per_torrent": ("value", "max_connections_per_torrent"),
- "spin_max_upload_slots_per_torrent": ("value", "max_upload_slots_per_torrent"),
- "spin_max_download_per_torrent": ("value", "max_download_speed_per_torrent"),
- "spin_max_upload_per_torrent": ("value", "max_upload_speed_per_torrent"),
- "spin_daemon_port": ("value", "daemon_port"),
- "chk_allow_remote_connections": ("active", "allow_remote"),
- "spin_active": ("value", "max_active_limit"),
- "spin_seeding": ("value", "max_active_seeding"),
- "spin_downloading": ("value", "max_active_downloading"),
- "chk_dont_count_slow_torrents": ("active", "dont_count_slow_torrents"),
- "chk_auto_manage_prefer_seeds": ("active", "auto_manage_prefer_seeds"),
- "chk_queue_new_top": ("active", "queue_new_to_top"),
- "spin_share_ratio_limit": ("value", "share_ratio_limit"),
- "spin_seed_time_ratio_limit": ("value", "seed_time_ratio_limit"),
- "spin_seed_time_limit": ("value", "seed_time_limit"),
- "chk_share_ratio": ("active", "stop_seed_at_ratio"),
- "spin_share_ratio": ("value", "stop_seed_ratio"),
- "radio_pause_ratio": ("active", "stop_seed_at_ratio"),
- "radio_remove_ratio": ("active", "remove_seed_at_ratio"),
- "spin_cache_size": ("value", "cache_size"),
- "spin_cache_expiry": ("value", "cache_expiry"),
- "combo_proxy_type": ("active", lambda: self.core_config["proxy"]["type"]),
- "entry_proxy_user": ("text", lambda: self.core_config["proxy"]["username"]),
- "entry_proxy_pass": ("text", lambda: self.core_config["proxy"]["password"]),
- "entry_proxy_host": ("text", lambda: self.core_config["proxy"]["hostname"]),
- "spin_proxy_port": ("value", lambda: self.core_config["proxy"]["port"]),
- "chk_proxy_host_resolve": ("active", lambda: self.core_config["proxy"]["proxy_hostnames"]),
- "chk_proxy_peer_conn": ("active", lambda: self.core_config["proxy"]["proxy_peer_connections"]),
- "entry_i2p_host": ("text", lambda: self.core_config["i2p_proxy"]["hostname"]),
- "spin_i2p_port": ("value", lambda: self.core_config["i2p_proxy"]["port"]),
- "accounts_add": (None, None),
- "accounts_listview": (None, None),
- "button_cache_refresh": (None, None),
- "button_plugin_install": (None, None),
- "button_rescan_plugins": (None, None),
- "button_find_plugins": (None, None),
- "button_testport": (None, None),
- "plugin_listview": (None, None),
+ 'chk_move_completed': ('active', 'move_completed'),
+ 'chk_copy_torrent_file': ('active', 'copy_torrent_file'),
+ 'chk_del_copy_torrent_file': ('active', 'del_copy_torrent_file'),
+ 'chk_pre_allocation': ('active', 'pre_allocate_storage'),
+ 'chk_prioritize_first_last_pieces': ('active', 'prioritize_first_last_pieces'),
+ 'chk_sequential_download': ('active', 'sequential_download'),
+ 'chk_add_paused': ('active', 'add_paused'),
+ 'active_port_label': ('text', lambda: str(self.active_port)),
+ 'spin_incoming_port': ('value', lambda: self.core_config['listen_ports'][0]),
+ 'chk_random_incoming_port': ('active', 'random_port'),
+ 'spin_outgoing_port_min': ('value', lambda: self.core_config['outgoing_ports'][0]),
+ 'spin_outgoing_port_max': ('value', lambda: self.core_config['outgoing_ports'][1]),
+ 'chk_random_outgoing_ports': ('active', 'random_outgoing_ports'),
+ 'entry_interface': ('text', 'listen_interface'),
+ 'entry_peer_tos': ('text', 'peer_tos'),
+ 'chk_dht': ('active', 'dht'),
+ 'chk_upnp': ('active', 'upnp'),
+ 'chk_natpmp': ('active', 'natpmp'),
+ 'chk_utpex': ('active', 'utpex'),
+ 'chk_lsd': ('active', 'lsd'),
+ 'chk_new_releases': ('active', 'new_release_check'),
+ 'chk_send_info': ('active', 'send_info'),
+ 'entry_geoip': ('text', 'geoip_db_location'),
+ 'combo_encin': ('active', 'enc_in_policy'),
+ 'combo_encout': ('active', 'enc_out_policy'),
+ 'combo_enclevel': ('active', 'enc_level'),
+ 'spin_max_connections_global': ('value', 'max_connections_global'),
+ 'spin_max_download': ('value', 'max_download_speed'),
+ 'spin_max_upload': ('value', 'max_upload_speed'),
+ 'spin_max_upload_slots_global': ('value', 'max_upload_slots_global'),
+ 'spin_max_half_open_connections': ('value', 'max_connections_per_second'),
+ 'spin_max_connections_per_second': ('value', 'max_connections_per_second'),
+ 'chk_ignore_limits_on_local_network': ('active', 'ignore_limits_on_local_network'),
+ 'chk_rate_limit_ip_overhead': ('active', 'rate_limit_ip_overhead'),
+ 'chk_anonymous_mode': ('active', 'anonymous_mode'),
+ 'spin_max_connections_per_torrent': ('value', 'max_connections_per_torrent'),
+ 'spin_max_upload_slots_per_torrent': ('value', 'max_upload_slots_per_torrent'),
+ 'spin_max_download_per_torrent': ('value', 'max_download_speed_per_torrent'),
+ 'spin_max_upload_per_torrent': ('value', 'max_upload_speed_per_torrent'),
+ 'spin_daemon_port': ('value', 'daemon_port'),
+ 'chk_allow_remote_connections': ('active', 'allow_remote'),
+ 'spin_active': ('value', 'max_active_limit'),
+ 'spin_seeding': ('value', 'max_active_seeding'),
+ 'spin_downloading': ('value', 'max_active_downloading'),
+ 'chk_dont_count_slow_torrents': ('active', 'dont_count_slow_torrents'),
+ 'chk_auto_manage_prefer_seeds': ('active', 'auto_manage_prefer_seeds'),
+ 'chk_queue_new_top': ('active', 'queue_new_to_top'),
+ 'spin_share_ratio_limit': ('value', 'share_ratio_limit'),
+ 'spin_seed_time_ratio_limit': ('value', 'seed_time_ratio_limit'),
+ 'spin_seed_time_limit': ('value', 'seed_time_limit'),
+ 'chk_share_ratio': ('active', 'stop_seed_at_ratio'),
+ 'spin_share_ratio': ('value', 'stop_seed_ratio'),
+ 'radio_pause_ratio': ('active', 'stop_seed_at_ratio'),
+ 'radio_remove_ratio': ('active', 'remove_seed_at_ratio'),
+ 'spin_cache_size': ('value', 'cache_size'),
+ 'spin_cache_expiry': ('value', 'cache_expiry'),
+ 'combo_proxy_type': ('active', lambda: self.core_config['proxy']['type']),
+ 'entry_proxy_user': ('text', lambda: self.core_config['proxy']['username']),
+ 'entry_proxy_pass': ('text', lambda: self.core_config['proxy']['password']),
+ 'entry_proxy_host': ('text', lambda: self.core_config['proxy']['hostname']),
+ 'spin_proxy_port': ('value', lambda: self.core_config['proxy']['port']),
+ 'chk_proxy_host_resolve': ('active', lambda: self.core_config['proxy']['proxy_hostnames']),
+ 'chk_proxy_peer_conn': ('active', lambda: self.core_config['proxy']['proxy_peer_connections']),
+ 'entry_i2p_host': ('text', lambda: self.core_config['i2p_proxy']['hostname']),
+ 'spin_i2p_port': ('value', lambda: self.core_config['i2p_proxy']['port']),
+ 'accounts_add': (None, None),
+ 'accounts_listview': (None, None),
+ 'button_cache_refresh': (None, None),
+ 'button_plugin_install': (None, None),
+ 'button_rescan_plugins': (None, None),
+ 'button_find_plugins': (None, None),
+ 'button_testport': (None, None),
+ 'plugin_listview': (None, None),
}
- core_widgets[self.download_location_path_chooser] = ("path_chooser", "download_location")
- core_widgets[self.move_completed_path_chooser] = ("path_chooser", "move_completed_path")
- core_widgets[self.copy_torrent_files_path_chooser] = ("path_chooser", "torrentfiles_location")
+ core_widgets[self.download_location_path_chooser] = ('path_chooser', 'download_location')
+ core_widgets[self.move_completed_path_chooser] = ('path_chooser', 'move_completed_path')
+ core_widgets[self.copy_torrent_files_path_chooser] = ('path_chooser', 'torrentfiles_location')
# Update the widgets accordingly
for key in core_widgets:
@@ -415,19 +415,19 @@ class Preferences(component.Component):
elif isinstance(value, str):
value = self.core_config[value]
elif modifier:
- value = {"active": False, "not_active": False, "value": 0, "text": "", "path_chooser": ""}[modifier]
+ value = {'active': False, 'not_active': False, 'value': 0, 'text': '', 'path_chooser': ''}[modifier]
- if modifier == "active":
+ if modifier == 'active':
widget.set_active(value)
- elif modifier == "not_active":
+ elif modifier == 'not_active':
widget.set_active(not value)
- elif modifier == "value":
+ elif modifier == 'value':
widget.set_value(float(value))
- elif modifier == "text":
+ elif modifier == 'text':
if value is None:
- value = ""
+ value = ''
widget.set_text(value)
- elif modifier == "path_chooser":
+ elif modifier == 'path_chooser':
widget.set_text(value, cursor_end=False, default_text=True)
if self.is_connected:
@@ -440,28 +440,28 @@ class Preferences(component.Component):
self.on_toggle(widget)
# Downloads tab #
- self.builder.get_object("chk_show_dialog").set_active(self.gtkui_config["interactive_add"])
- self.builder.get_object("chk_focus_dialog").set_active(self.gtkui_config["focus_add_dialog"])
+ self.builder.get_object('chk_show_dialog').set_active(self.gtkui_config['interactive_add'])
+ self.builder.get_object('chk_focus_dialog').set_active(self.gtkui_config['focus_add_dialog'])
# Interface tab #
- self.builder.get_object("chk_use_tray").set_active(self.gtkui_config["enable_system_tray"])
- self.builder.get_object("chk_min_on_close").set_active(self.gtkui_config["close_to_tray"])
- self.builder.get_object("chk_start_in_tray").set_active(self.gtkui_config["start_in_tray"])
- self.builder.get_object("radio_appind").set_active(self.gtkui_config["enable_appindicator"])
- self.builder.get_object("chk_lock_tray").set_active(self.gtkui_config["lock_tray"])
- self.builder.get_object("radio_standalone").set_active(self.gtkui_config["standalone"])
- 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.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)
- self.__set_color("waiting", from_config=True)
- self.__set_color("missing", from_config=True)
+ self.builder.get_object('chk_use_tray').set_active(self.gtkui_config['enable_system_tray'])
+ self.builder.get_object('chk_min_on_close').set_active(self.gtkui_config['close_to_tray'])
+ self.builder.get_object('chk_start_in_tray').set_active(self.gtkui_config['start_in_tray'])
+ self.builder.get_object('radio_appind').set_active(self.gtkui_config['enable_appindicator'])
+ self.builder.get_object('chk_lock_tray').set_active(self.gtkui_config['lock_tray'])
+ self.builder.get_object('radio_standalone').set_active(self.gtkui_config['standalone'])
+ 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.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)
+ self.__set_color('waiting', from_config=True)
+ self.__set_color('missing', from_config=True)
# Other tab #
- self.builder.get_object("chk_show_new_releases").set_active(self.gtkui_config["show_new_releases"])
+ self.builder.get_object('chk_show_new_releases').set_active(self.gtkui_config['show_new_releases'])
# Cache tab #
if client.connected():
@@ -495,175 +495,175 @@ class Preferences(component.Component):
new_gtkui_config = {}
# Downloads tab #
- new_gtkui_config["interactive_add"] = self.builder.get_object("chk_show_dialog").get_active()
- new_gtkui_config["focus_add_dialog"] = self.builder.get_object("chk_focus_dialog").get_active()
+ new_gtkui_config['interactive_add'] = self.builder.get_object('chk_show_dialog').get_active()
+ new_gtkui_config['focus_add_dialog'] = self.builder.get_object('chk_focus_dialog').get_active()
- for state in ("missing", "waiting", "downloading", "completed"):
- color = self.builder.get_object("%s_color" % state).get_color()
- new_gtkui_config["pieces_color_%s" % state] = [
+ 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
]
- new_core_config["copy_torrent_file"] = self.builder.get_object(
- "chk_copy_torrent_file").get_active()
- new_core_config["del_copy_torrent_file"] = self.builder.get_object(
- "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()
- new_core_config["sequential_download"] = self.builder.get_object(
- "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()
+ new_core_config['copy_torrent_file'] = self.builder.get_object(
+ 'chk_copy_torrent_file').get_active()
+ new_core_config['del_copy_torrent_file'] = self.builder.get_object(
+ '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()
+ new_core_config['sequential_download'] = self.builder.get_object(
+ '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()
# Network tab #
- listen_ports = [self.builder.get_object("spin_incoming_port").get_value_as_int()] * 2
- new_core_config["listen_ports"] = listen_ports
- new_core_config["random_port"] = self.builder.get_object("chk_random_incoming_port").get_active()
+ listen_ports = [self.builder.get_object('spin_incoming_port').get_value_as_int()] * 2
+ new_core_config['listen_ports'] = listen_ports
+ 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_min').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()
- incoming_address = self.builder.get_object("entry_interface").get_text().strip()
+ new_core_config['outgoing_ports'] = outgoing_ports
+ new_core_config['random_outgoing_ports'] = self.builder.get_object(
+ 'chk_random_outgoing_ports').get_active()
+ incoming_address = self.builder.get_object('entry_interface').get_text().strip()
if deluge.common.is_ip(incoming_address) or not incoming_address:
- new_core_config["listen_interface"] = incoming_address
- new_core_config["peer_tos"] = self.builder.get_object("entry_peer_tos").get_text()
- new_core_config["dht"] = self.builder.get_object("chk_dht").get_active()
- new_core_config["upnp"] = self.builder.get_object("chk_upnp").get_active()
- new_core_config["natpmp"] = self.builder.get_object("chk_natpmp").get_active()
- new_core_config["utpex"] = self.builder.get_object("chk_utpex").get_active()
- new_core_config["lsd"] = self.builder.get_object("chk_lsd").get_active()
- new_core_config["enc_in_policy"] = self.builder.get_object("combo_encin").get_active()
- new_core_config["enc_out_policy"] = self.builder.get_object("combo_encout").get_active()
- new_core_config["enc_level"] = self.builder.get_object("combo_enclevel").get_active()
+ new_core_config['listen_interface'] = incoming_address
+ new_core_config['peer_tos'] = self.builder.get_object('entry_peer_tos').get_text()
+ new_core_config['dht'] = self.builder.get_object('chk_dht').get_active()
+ new_core_config['upnp'] = self.builder.get_object('chk_upnp').get_active()
+ new_core_config['natpmp'] = self.builder.get_object('chk_natpmp').get_active()
+ new_core_config['utpex'] = self.builder.get_object('chk_utpex').get_active()
+ new_core_config['lsd'] = self.builder.get_object('chk_lsd').get_active()
+ new_core_config['enc_in_policy'] = self.builder.get_object('combo_encin').get_active()
+ new_core_config['enc_out_policy'] = self.builder.get_object('combo_encout').get_active()
+ new_core_config['enc_level'] = self.builder.get_object('combo_enclevel').get_active()
# Bandwidth tab #
- new_core_config["max_connections_global"] = self.builder.get_object(
- "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()
- new_core_config["max_half_open_connections"] = self.builder.get_object(
- "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()
- new_core_config["max_connections_per_torrent"] = self.builder.get_object(
- "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()
- new_core_config["max_upload_speed_per_torrent"] = self.builder.get_object(
- "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()
- new_core_config["ignore_limits_on_local_network"] = self.builder.get_object(
- "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()
+ new_core_config['max_connections_global'] = self.builder.get_object(
+ '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()
+ new_core_config['max_half_open_connections'] = self.builder.get_object(
+ '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()
+ new_core_config['max_connections_per_torrent'] = self.builder.get_object(
+ '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()
+ new_core_config['max_upload_speed_per_torrent'] = self.builder.get_object(
+ '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()
+ new_core_config['ignore_limits_on_local_network'] = self.builder.get_object(
+ '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()
# Interface tab #
- new_gtkui_config["enable_system_tray"] = self.builder.get_object("chk_use_tray").get_active()
- new_gtkui_config["close_to_tray"] = self.builder.get_object("chk_min_on_close").get_active()
- new_gtkui_config["start_in_tray"] = self.builder.get_object("chk_start_in_tray").get_active()
- new_gtkui_config["enable_appindicator"] = self.builder.get_object("radio_appind").get_active()
- new_gtkui_config["lock_tray"] = self.builder.get_object("chk_lock_tray").get_active()
- passhex = sha(self.builder.get_object("txt_tray_password").get_text()).hexdigest()
- if passhex != "c07eb5a8c0dc7bb81c217b67f11c3b7a5e95ffd7":
- new_gtkui_config["tray_password"] = passhex
-
- was_standalone = self.gtkui_config["standalone"]
- new_gtkui_standalone = self.builder.get_object("radio_standalone").get_active()
- 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()
- new_gtkui_config["focus_main_window_on_add"] = self.builder.get_object(
- "chk_focus_main_window_on_add").get_active()
+ new_gtkui_config['enable_system_tray'] = self.builder.get_object('chk_use_tray').get_active()
+ new_gtkui_config['close_to_tray'] = self.builder.get_object('chk_min_on_close').get_active()
+ new_gtkui_config['start_in_tray'] = self.builder.get_object('chk_start_in_tray').get_active()
+ new_gtkui_config['enable_appindicator'] = self.builder.get_object('radio_appind').get_active()
+ new_gtkui_config['lock_tray'] = self.builder.get_object('chk_lock_tray').get_active()
+ passhex = sha(self.builder.get_object('txt_tray_password').get_text()).hexdigest()
+ if passhex != 'c07eb5a8c0dc7bb81c217b67f11c3b7a5e95ffd7':
+ new_gtkui_config['tray_password'] = passhex
+
+ was_standalone = self.gtkui_config['standalone']
+ new_gtkui_standalone = self.builder.get_object('radio_standalone').get_active()
+ 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()
+ new_gtkui_config['focus_main_window_on_add'] = self.builder.get_object(
+ '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()
- 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()
+ new_gtkui_config['show_new_releases'] = self.builder.get_object(
+ '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()
- new_core_config["new_release_check"] = self.builder.get_object("chk_new_releases").get_active()
+ 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()
+ new_core_config['new_release_check'] = self.builder.get_object('chk_new_releases').get_active()
# Proxy tab #
- new_core_config["proxy"] = {}
- new_core_config["proxy"]["type"] = self.builder.get_object("combo_proxy_type").get_active()
- new_core_config["proxy"]["username"] = self.builder.get_object("entry_proxy_user").get_text()
- new_core_config["proxy"]["password"] = self.builder.get_object("entry_proxy_pass").get_text()
- new_core_config["proxy"]["hostname"] = self.builder.get_object("entry_proxy_host").get_text()
- new_core_config["proxy"]["port"] = self.builder.get_object("spin_proxy_port").get_value_as_int()
- new_core_config["proxy"]["proxy_hostnames"] = self.builder.get_object(
- "chk_proxy_host_resolve").get_active()
- new_core_config["proxy"]["proxy_peer_connections"] = self.builder.get_object(
- "chk_proxy_peer_conn").get_active()
- new_core_config["i2p_proxy"] = {}
- new_core_config["i2p_proxy"]["hostname"] = self.builder.get_object("entry_i2p_host").get_text()
- new_core_config["i2p_proxy"]["port"] = self.builder.get_object("spin_i2p_port").get_value_as_int()
- new_core_config["anonymous_mode"] = self.builder.get_object("chk_anonymous_mode").get_active()
+ new_core_config['proxy'] = {}
+ new_core_config['proxy']['type'] = self.builder.get_object('combo_proxy_type').get_active()
+ new_core_config['proxy']['username'] = self.builder.get_object('entry_proxy_user').get_text()
+ new_core_config['proxy']['password'] = self.builder.get_object('entry_proxy_pass').get_text()
+ new_core_config['proxy']['hostname'] = self.builder.get_object('entry_proxy_host').get_text()
+ new_core_config['proxy']['port'] = self.builder.get_object('spin_proxy_port').get_value_as_int()
+ new_core_config['proxy']['proxy_hostnames'] = self.builder.get_object(
+ 'chk_proxy_host_resolve').get_active()
+ new_core_config['proxy']['proxy_peer_connections'] = self.builder.get_object(
+ 'chk_proxy_peer_conn').get_active()
+ new_core_config['i2p_proxy'] = {}
+ new_core_config['i2p_proxy']['hostname'] = self.builder.get_object('entry_i2p_host').get_text()
+ new_core_config['i2p_proxy']['port'] = self.builder.get_object('spin_i2p_port').get_value_as_int()
+ new_core_config['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()
- new_core_config["max_active_downloading"] = self.builder.get_object(
- "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()
- new_core_config["auto_manage_prefer_seeds"] = self.builder.get_object(
- "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()
- 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()
- new_core_config["seed_time_ratio_limit"] = self.builder.get_object(
- "spin_seed_time_ratio_limit").get_value()
- new_core_config["seed_time_limit"] = self.builder.get_object("spin_seed_time_limit").get_value()
+ 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()
+ new_core_config['max_active_downloading'] = self.builder.get_object(
+ '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()
+ new_core_config['auto_manage_prefer_seeds'] = self.builder.get_object(
+ '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()
+ 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()
+ new_core_config['seed_time_ratio_limit'] = self.builder.get_object(
+ '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 #
- new_core_config["cache_size"] = self.builder.get_object("spin_cache_size").get_value_as_int()
- new_core_config["cache_expiry"] = self.builder.get_object("spin_cache_expiry").get_value_as_int()
+ new_core_config['cache_size'] = self.builder.get_object('spin_cache_size').get_value_as_int()
+ new_core_config['cache_expiry'] = self.builder.get_object('spin_cache_expiry').get_value_as_int()
# Run plugin hook to apply preferences
- component.get("PluginManager").run_on_apply_prefs()
+ component.get('PluginManager').run_on_apply_prefs()
# Lanuage
if self.language_checkbox.get_active():
- new_gtkui_config["language"] = None
+ new_gtkui_config['language'] = None
else:
active = self.language_combo.get_active()
if active == -1:
dialog = InformationDialog(
- _("Attention"),
- _("You must choose a language")
+ _('Attention'),
+ _('You must choose a language')
)
dialog.run()
return
else:
model = self.language_combo.get_model()
- new_gtkui_config["language"] = model.get(model.get_iter(active), 0)[0]
+ new_gtkui_config['language'] = model.get(model.get_iter(active), 0)[0]
- if new_gtkui_config["language"] != self.gtkui_config["language"]:
+ 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.")
+ _('Attention'),
+ _('You must now restart the deluge UI for the changes to take effect.')
)
dialog.run()
@@ -701,22 +701,22 @@ class Preferences(component.Component):
shutdown_daemon = (not client.is_standalone() and
client.connected() and
client.is_localhost())
- component.get("MainWindow").quit(shutdown=shutdown_daemon)
+ component.get('MainWindow').quit(shutdown=shutdown_daemon)
else:
- self.gtkui_config["standalone"] = not new_gtkui_standalone
- self.builder.get_object("radio_standalone").set_active(
- self.gtkui_config["standalone"])
- self.builder.get_object("radio_thinclient").set_active(
- not self.gtkui_config["standalone"])
+ self.gtkui_config['standalone'] = not new_gtkui_standalone
+ self.builder.get_object('radio_standalone').set_active(
+ self.gtkui_config['standalone'])
+ self.builder.get_object('radio_thinclient').set_active(
+ not self.gtkui_config['standalone'])
dialog = YesNoDialog(
- _("Switching client mode..."),
- _("Your current session will be stopped. Do you wish to continue?")
+ _('Switching client mode...'),
+ _('Your current session will be stopped. Do you wish to continue?')
)
dialog.run().addCallback(on_response)
def hide(self):
self.window_open = False
- self.builder.get_object("port_img").hide()
+ self.builder.get_object('port_img').hide()
self.pref_dialog.hide()
def __update_cache_status(self):
@@ -725,10 +725,10 @@ class Preferences(component.Component):
'label_cache_blocks_read', 'label_cache_blocks_read_hit', 'label_cache_read_hit_ratio',
'label_cache_reads', 'label_cache_cache_size', 'label_cache_read_cache_size'):
widget = self.builder.get_object(widget_name)
- key = widget_name[len("label_cache_"):]
+ key = widget_name[len('label_cache_'):]
value = self.cache_status[key]
if isinstance(value, float):
- value = "%.2f" % value
+ value = '%.2f' % value
else:
value = str(value)
@@ -746,14 +746,14 @@ class Preferences(component.Component):
return True
def load_pref_dialog_state(self):
- w = self.gtkui_config["pref_dialog_width"]
- h = self.gtkui_config["pref_dialog_height"]
+ w = self.gtkui_config['pref_dialog_width']
+ h = self.gtkui_config['pref_dialog_height']
if w is not None and h is not None:
self.pref_dialog.resize(w, h)
def on_pref_dialog_configure_event(self, widget, event):
- self.gtkui_config["pref_dialog_width"] = event.width
- self.gtkui_config["pref_dialog_height"] = event.height
+ self.gtkui_config['pref_dialog_width'] = event.width
+ self.gtkui_config['pref_dialog_height'] = event.height
def on_toggle(self, widget):
"""Handles widget sensitivity based on radio/check button values."""
@@ -763,32 +763,32 @@ class Preferences(component.Component):
return
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
+ '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
}
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_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_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_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}
}
def update_dependent_widgets(name, value):
@@ -809,16 +809,16 @@ class Preferences(component.Component):
update_dependent_widgets(key, value)
def on_button_ok_clicked(self, data):
- log.debug("on_button_ok_clicked")
+ log.debug('on_button_ok_clicked')
self.set_config(hide=True)
return True
def on_button_apply_clicked(self, data):
- log.debug("on_button_apply_clicked")
+ log.debug('on_button_apply_clicked')
self.set_config()
def on_button_cancel_clicked(self, data):
- log.debug("on_button_cancel_clicked")
+ log.debug('on_button_cancel_clicked')
self.hide()
return True
@@ -826,7 +826,7 @@ class Preferences(component.Component):
# Show the correct notebook page based on what row is selected.
(model, row) = treeselection.get_selected()
try:
- if model.get_value(row, 1) == _("Daemon"):
+ if model.get_value(row, 1) == _('Daemon'):
# Let's see update the accounts related stuff
if client.connected():
self._get_accounts_tab_data()
@@ -835,27 +835,27 @@ class Preferences(component.Component):
pass
def on_test_port_clicked(self, data):
- log.debug("on_test_port_clicked")
+ log.debug('on_test_port_clicked')
def on_get_test(status):
if status:
- self.builder.get_object("port_img").set_from_stock(gtk.STOCK_YES, 4)
- self.builder.get_object("port_img").show()
+ self.builder.get_object('port_img').set_from_stock(gtk.STOCK_YES, 4)
+ self.builder.get_object('port_img').show()
else:
- self.builder.get_object("port_img").set_from_stock(gtk.STOCK_DIALOG_WARNING, 4)
- self.builder.get_object("port_img").show()
+ self.builder.get_object('port_img').set_from_stock(gtk.STOCK_DIALOG_WARNING, 4)
+ self.builder.get_object('port_img').show()
client.core.test_listen_port().addCallback(on_get_test)
# XXX: Consider using gtk.Spinner() instead of the loading gif
# It requires gtk.ver > 2.12
- self.builder.get_object("port_img").set_from_file(deluge.common.get_pixmap('loading.gif'))
- self.builder.get_object("port_img").show()
+ self.builder.get_object('port_img').set_from_file(deluge.common.get_pixmap('loading.gif'))
+ self.builder.get_object('port_img').show()
client.force_call()
def on_plugin_toggled(self, renderer, path):
row = self.plugin_liststore.get_iter_from_string(path)
name = self.plugin_liststore.get_value(row, 0)
value = self.plugin_liststore.get_value(row, 1)
- log.debug("on_plugin_toggled - %s: %s", name, value)
+ log.debug('on_plugin_toggled - %s: %s', name, value)
self.plugin_liststore.set_value(row, 1, not value)
if not value:
d = client.core.enable_plugin(name)
@@ -870,22 +870,22 @@ class Preferences(component.Component):
d.addBoth(on_plugin_action)
def on_plugin_selection_changed(self, treeselection):
- log.debug("on_plugin_selection_changed")
+ log.debug('on_plugin_selection_changed')
(model, itr) = treeselection.get_selected()
if not itr:
return
name = model[itr][0]
- plugin_info = component.get("PluginManager").get_plugin_info(name)
- self.builder.get_object("label_plugin_author").set_text(plugin_info["Author"])
- self.builder.get_object("label_plugin_version").set_text(plugin_info["Version"])
- self.builder.get_object("label_plugin_email").set_text(plugin_info["Author-email"])
- self.builder.get_object("label_plugin_homepage").set_text(plugin_info["Home-page"])
- self.builder.get_object("label_plugin_details").set_text(plugin_info["Description"])
+ plugin_info = component.get('PluginManager').get_plugin_info(name)
+ self.builder.get_object('label_plugin_author').set_text(plugin_info['Author'])
+ self.builder.get_object('label_plugin_version').set_text(plugin_info['Version'])
+ self.builder.get_object('label_plugin_email').set_text(plugin_info['Author-email'])
+ self.builder.get_object('label_plugin_homepage').set_text(plugin_info['Home-page'])
+ self.builder.get_object('label_plugin_details').set_text(plugin_info['Description'])
def _on_button_plugin_install_clicked(self, widget):
- log.debug("_on_button_plugin_install_clicked")
+ log.debug('_on_button_plugin_install_clicked')
chooser = gtk.FileChooserDialog(
- _("Select the Plugin"),
+ _('Select the Plugin'),
self.pref_dialog,
gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
@@ -893,11 +893,11 @@ class Preferences(component.Component):
chooser.set_transient_for(self.pref_dialog)
chooser.set_select_multiple(False)
- chooser.set_property("skip-taskbar-hint", True)
+ chooser.set_property('skip-taskbar-hint', True)
file_filter = gtk.FileFilter()
- file_filter.set_name(_("Plugin Eggs"))
- file_filter.add_pattern("*." + "egg")
+ file_filter.set_name(_('Plugin Eggs'))
+ file_filter.add_pattern('*.' + 'egg')
chooser.add_filter(file_filter)
# Run the dialog
@@ -914,13 +914,13 @@ 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()
+ component.get('PluginManager').scan_for_plugins()
if not client.is_localhost():
# We need to send this plugin to the daemon
- with open(filepath, "rb") as _file:
+ with open(filepath, 'rb') as _file:
filedump = base64.encodestring(_file.read())
client.core.upload_plugin(filename, filedump)
@@ -930,18 +930,18 @@ class Preferences(component.Component):
self.show()
def _on_button_rescan_plugins_clicked(self, widget):
- component.get("PluginManager").scan_for_plugins()
+ component.get('PluginManager').scan_for_plugins()
if client.connected():
client.core.rescan_plugins()
self.show()
def _on_button_find_plugins_clicked(self, widget):
- deluge.common.open_url_in_browser("http://dev.deluge-torrent.org/wiki/Plugins")
+ deluge.common.open_url_in_browser('http://dev.deluge-torrent.org/wiki/Plugins')
def _on_combo_encryption_changed(self, widget):
- combo_encin = self.builder.get_object("combo_encin").get_active()
- combo_encout = self.builder.get_object("combo_encout").get_active()
- combo_enclevel = self.builder.get_object("combo_enclevel")
+ combo_encin = self.builder.get_object('combo_encin').get_active()
+ combo_encout = self.builder.get_object('combo_encout').get_active()
+ combo_enclevel = self.builder.get_object('combo_enclevel')
# If incoming and outgoing both set to disabled, disable level combobox
if combo_encin == 2 and combo_encout == 2:
@@ -950,27 +950,27 @@ class Preferences(component.Component):
combo_enclevel.set_sensitive(True)
def _on_combo_proxy_type_changed(self, widget):
- proxy_type = self.builder.get_object("combo_proxy_type").get_active()
+ proxy_type = self.builder.get_object('combo_proxy_type').get_active()
hides = []
shows = []
# 0:"None"
if proxy_type == 0:
- hides.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port",
- "label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port",
- "chk_proxy_host_resolve", "chk_proxy_peer_conn"])
+ hides.extend(['entry_proxy_pass', 'entry_proxy_user', 'entry_proxy_host', 'spin_proxy_port',
+ 'label_proxy_pass', 'label_proxy_user', 'label_proxy_host', 'label_proxy_port',
+ 'chk_proxy_host_resolve', 'chk_proxy_peer_conn'])
# 1:"Socks4", 2:"Socks5", 4:"HTTP"
elif proxy_type in (1, 2, 4):
if proxy_type in (2, 4):
- shows.extend(["chk_proxy_host_resolve"])
- hides.extend(["entry_proxy_pass", "entry_proxy_user", "label_proxy_pass", "label_proxy_user"])
- shows.extend(["entry_proxy_host", "spin_proxy_port", "label_proxy_host",
- "label_proxy_port", "chk_proxy_peer_conn"])
+ shows.extend(['chk_proxy_host_resolve'])
+ hides.extend(['entry_proxy_pass', 'entry_proxy_user', 'label_proxy_pass', 'label_proxy_user'])
+ shows.extend(['entry_proxy_host', 'spin_proxy_port', 'label_proxy_host',
+ 'label_proxy_port', 'chk_proxy_peer_conn'])
# 3:"Socks5 Auth", 5:"HTTP Auth"
elif proxy_type in (3, 5):
- shows.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port",
- "label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port",
- "chk_proxy_host_resolve", "chk_proxy_peer_conn"])
+ shows.extend(['entry_proxy_pass', 'entry_proxy_user', 'entry_proxy_host', 'spin_proxy_port',
+ 'label_proxy_pass', 'label_proxy_user', 'label_proxy_host', 'label_proxy_port',
+ 'chk_proxy_host_resolve', 'chk_proxy_peer_conn'])
for hide_entry in hides:
self.builder.get_object(hide_entry).hide()
@@ -990,8 +990,8 @@ class Preferences(component.Component):
self.accounts_frame.hide()
else:
ErrorDialog(
- _("Server Side Error"),
- _("An error ocurred on the server"),
+ _('Server Side Error'),
+ _('An error ocurred on the server'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
client.core.get_known_accounts().addCallback(on_ok).addErrback(on_fail)
@@ -1005,7 +1005,7 @@ class Preferences(component.Component):
value = '*' * len(value)
account_to_log[key] = value
known_accounts_to_log.append(account_to_log)
- log.debug("_on_known_accounts: %s", known_accounts_to_log)
+ log.debug('_on_known_accounts: %s', known_accounts_to_log)
self.accounts_liststore.clear()
@@ -1016,17 +1016,17 @@ class Preferences(component.Component):
self.accounts_liststore.set_value(accounts_iter, ACCOUNTS_PASSWORD, account['password'])
def _on_accounts_selection_changed(self, treeselection):
- log.debug("_on_accounts_selection_changed")
+ log.debug('_on_accounts_selection_changed')
(model, itr) = treeselection.get_selected()
if not itr:
return
username = model[itr][0]
if username:
- self.builder.get_object("accounts_edit").set_sensitive(True)
- self.builder.get_object("accounts_delete").set_sensitive(True)
+ self.builder.get_object('accounts_edit').set_sensitive(True)
+ self.builder.get_object('accounts_delete').set_sensitive(True)
else:
- self.builder.get_object("accounts_edit").set_sensitive(False)
- self.builder.get_object("accounts_delete").set_sensitive(False)
+ self.builder.get_object('accounts_edit').set_sensitive(False)
+ self.builder.get_object('accounts_delete').set_sensitive(False)
def _on_accounts_add_clicked(self, widget):
dialog = AccountDialog(levels_mapping=client.auth_levels_mapping, parent=self.pref_dialog)
@@ -1045,14 +1045,14 @@ class Preferences(component.Component):
def add_fail(failure):
if failure.type == AuthManagerError:
ErrorDialog(
- _("Error Adding Account"),
- _("Authentication failed"),
+ _('Error Adding Account'),
+ _('Authentication failed'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
else:
ErrorDialog(
- _("Error Adding Account"),
- _("An error ocurred while adding account"),
+ _('Error Adding Account'),
+ _('An error ocurred while adding account'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
@@ -1084,8 +1084,8 @@ class Preferences(component.Component):
def update_fail(failure):
ErrorDialog(
- _("Error Updating Account"),
- _("An error ocurred while updating account"),
+ _('Error Updating Account'),
+ _('An error ocurred while updating account'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
@@ -1104,7 +1104,7 @@ class Preferences(component.Component):
return
username = model[itr][0]
- header = _("Remove Account")
+ header = _('Remove Account')
text = _("Are you sure you wan't do remove the account with the "
"username \"%(username)s\"?" % dict(username=username))
dialog = YesNoDialog(header, text, parent=self.pref_dialog)
@@ -1116,14 +1116,14 @@ class Preferences(component.Component):
def remove_fail(failure):
if failure.type == AuthManagerError:
ErrorDialog(
- _("Error Removing Account"),
- _("Auhentication failed"),
+ _('Error Removing Account'),
+ _('Auhentication failed'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
else:
ErrorDialog(
- _("Error Removing Account"),
- _("An error ocurred while removing account"),
+ _('Error Removing Account'),
+ _('An error ocurred while removing account'),
parent=self.pref_dialog, details=failure.getErrorMessage()
).run()
if response_id == gtk.RESPONSE_YES:
@@ -1134,53 +1134,53 @@ class Preferences(component.Component):
def _on_piecesbar_toggle_toggled(self, widget):
self.gtkui_config['show_piecesbar'] = widget.get_active()
- colors_widget = self.builder.get_object("piecebar_colors_expander")
+ colors_widget = self.builder.get_object('piecebar_colors_expander')
colors_widget.set_visible(widget.get_active())
def _on_checkbutton_language_toggled(self, widget):
self.language_combo.set_visible(not self.language_checkbox.get_active())
def _on_completed_color_set(self, widget):
- self.__set_color("completed")
+ self.__set_color('completed')
def _on_revert_color_completed_clicked(self, widget):
- self.__revert_color("completed")
+ self.__revert_color('completed')
def _on_downloading_color_set(self, widget):
- self.__set_color("downloading")
+ self.__set_color('downloading')
def _on_revert_color_downloading_clicked(self, widget):
- self.__revert_color("downloading")
+ self.__revert_color('downloading')
def _on_waiting_color_set(self, widget):
- self.__set_color("waiting")
+ self.__set_color('waiting')
def _on_revert_color_waiting_clicked(self, widget):
- self.__revert_color("waiting")
+ self.__revert_color('waiting')
def _on_missing_color_set(self, widget):
- self.__set_color("missing")
+ self.__set_color('missing')
def _on_revert_color_missing_clicked(self, widget):
- self.__revert_color("missing")
+ self.__revert_color('missing')
def __set_color(self, state, from_config=False):
if from_config:
- color = gtk.gdk.Color(*self.gtkui_config["pieces_color_%s" % state])
- log.debug("Setting %r color state from config to %s", state, (color.red, color.green, color.blue))
- self.builder.get_object("%s_color" % state).set_color(color)
+ color = gtk.gdk.Color(*self.gtkui_config['pieces_color_%s' % state])
+ log.debug('Setting %r color state from config to %s', state, (color.red, color.green, color.blue))
+ self.builder.get_object('%s_color' % state).set_color(color)
else:
- color = self.builder.get_object("%s_color" % state).get_color()
- log.debug("Setting %r color state to %s", state, (color.red, color.green, color.blue))
- self.gtkui_config["pieces_color_%s" % state] = [color.red, color.green, color.blue]
+ color = self.builder.get_object('%s_color' % state).get_color()
+ log.debug('Setting %r color state to %s', state, (color.red, color.green, color.blue))
+ self.gtkui_config['pieces_color_%s' % state] = [color.red, color.green, color.blue]
self.gtkui_config.save()
- self.gtkui_config.apply_set_functions("pieces_colors")
+ self.gtkui_config.apply_set_functions('pieces_colors')
- self.builder.get_object("revert_color_%s" % state).set_sensitive(
+ self.builder.get_object('revert_color_%s' % state).set_sensitive(
[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)
- self.builder.get_object("%s_color" % state).set_color(gtk.gdk.Color(*self.COLOR_DEFAULTS[state]))
- self.builder.get_object("revert_color_%s" % state).set_sensitive(False)
- self.gtkui_config.apply_set_functions("pieces_colors")
+ log.debug('Reverting %r color state', state)
+ self.builder.get_object('%s_color' % state).set_color(gtk.gdk.Color(*self.COLOR_DEFAULTS[state]))
+ self.builder.get_object('revert_color_%s' % state).set_sensitive(False)
+ self.gtkui_config.apply_set_functions('pieces_colors')
diff --git a/deluge/ui/gtkui/queuedtorrents.py b/deluge/ui/gtkui/queuedtorrents.py
index 750432bb5..be88b445a 100644
--- a/deluge/ui/gtkui/queuedtorrents.py
+++ b/deluge/ui/gtkui/queuedtorrents.py
@@ -24,36 +24,36 @@ log = logging.getLogger(__name__)
class QueuedTorrents(component.Component):
def __init__(self):
- component.Component.__init__(self, "QueuedTorrents", depend=["StatusBar", "AddTorrentDialog"])
+ component.Component.__init__(self, 'QueuedTorrents', depend=['StatusBar', 'AddTorrentDialog'])
self.queue = []
self.status_item = None
- self.config = ConfigManager("gtkui.conf")
+ self.config = ConfigManager('gtkui.conf')
self.builder = gtk.Builder()
self.builder.add_from_file(deluge.common.resource_filename(
- "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")
+ '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))
self.builder.connect_signals({
- "on_button_remove_clicked": self.on_button_remove_clicked,
- "on_button_clear_clicked": self.on_button_clear_clicked,
- "on_button_close_clicked": self.on_button_close_clicked,
- "on_button_add_clicked": self.on_button_add_clicked,
- "on_chk_autoadd_toggled": self.on_chk_autoadd_toggled
+ 'on_button_remove_clicked': self.on_button_remove_clicked,
+ 'on_button_clear_clicked': self.on_button_clear_clicked,
+ 'on_button_close_clicked': self.on_button_close_clicked,
+ 'on_button_add_clicked': self.on_button_add_clicked,
+ 'on_chk_autoadd_toggled': self.on_chk_autoadd_toggled
})
- self.treeview = self.builder.get_object("treeview")
+ self.treeview = self.builder.get_object('treeview')
self.treeview.append_column(
- gtk.TreeViewColumn(_("Torrent"), gtk.CellRendererText(), text=0))
+ gtk.TreeViewColumn(_('Torrent'), gtk.CellRendererText(), text=0))
self.liststore = gtk.ListStore(str, str)
self.treeview.set_model(self.liststore)
self.treeview.set_tooltip_column(1)
def run(self):
- self.dialog.set_transient_for(component.get("MainWindow").window)
+ self.dialog.set_transient_for(component.get('MainWindow').window)
self.dialog.show()
def start(self):
@@ -64,16 +64,16 @@ class QueuedTorrents(component.Component):
self.update_status_bar()
# We only want the add button sensitive if we're connected to a host
- self.builder.get_object("button_add").set_sensitive(True)
+ self.builder.get_object('button_add').set_sensitive(True)
- if self.config["autoadd_queued"] or self.config["standalone"]:
+ if self.config['autoadd_queued'] or self.config['standalone']:
self.on_button_add_clicked(None)
else:
self.run()
def stop(self):
# We only want the add button sensitive if we're connected to a host
- self.builder.get_object("button_add").set_sensitive(False)
+ self.builder.get_object('button_add').set_sensitive(False)
self.update_status_bar()
def add_to_queue(self, torrents):
@@ -86,7 +86,7 @@ class QueuedTorrents(component.Component):
for torrent in self.queue:
if deluge.common.is_magnet(torrent):
magnet = deluge.common.get_magnet_info(torrent)
- self.liststore.append([magnet["name"], torrent])
+ self.liststore.append([magnet['name'], torrent])
else:
self.liststore.append([os.path.split(torrent)[1], torrent])
@@ -98,12 +98,12 @@ class QueuedTorrents(component.Component):
# If there are no queued torrents.. remove statusbar widgets and return
if len(self.queue) == 0:
if self.status_item is not None:
- component.get("StatusBar").remove_item(self.status_item)
+ component.get('StatusBar').remove_item(self.status_item)
self.status_item = None
return False
try:
- component.get("StatusBar")
+ component.get('StatusBar')
except Exception:
# The statusbar hasn't been loaded yet, so we'll add a timer to
# update it later.
@@ -112,14 +112,14 @@ class QueuedTorrents(component.Component):
# Set the label text for statusbar
if len(self.queue) > 1:
- label = str(len(self.queue)) + _(" Torrents Queued")
+ label = str(len(self.queue)) + _(' Torrents Queued')
else:
- label = str(len(self.queue)) + _(" Torrent Queued")
+ label = str(len(self.queue)) + _(' Torrent Queued')
# Add the statusbar items if needed, or just modify the label if they
# have already been added.
if self.status_item is None:
- self.status_item = component.get("StatusBar").add_item(
+ self.status_item = component.get('StatusBar').add_item(
stock=gtk.STOCK_SORT_DESCENDING,
text=label,
callback=self.on_statusbar_click)
@@ -130,7 +130,7 @@ class QueuedTorrents(component.Component):
return False
def on_statusbar_click(self, widget, event):
- log.debug("on_statusbar_click")
+ log.debug('on_statusbar_click')
self.run()
def on_button_remove_clicked(self, widget):
@@ -161,4 +161,4 @@ class QueuedTorrents(component.Component):
self.update_status_bar()
def on_chk_autoadd_toggled(self, widget):
- self.config["autoadd_queued"] = widget.get_active()
+ self.config['autoadd_queued'] = widget.get_active()
diff --git a/deluge/ui/gtkui/removetorrentdialog.py b/deluge/ui/gtkui/removetorrentdialog.py
index 822f089f5..2a15f8a0b 100644
--- a/deluge/ui/gtkui/removetorrentdialog.py
+++ b/deluge/ui/gtkui/removetorrentdialog.py
@@ -32,45 +32,45 @@ class RemoveTorrentDialog(object):
"""
def __init__(self, torrent_ids, delete_files=False):
if not isinstance(torrent_ids, list) and not isinstance(torrent_ids, tuple):
- raise TypeError("requires a list of torrent_ids")
+ raise TypeError('requires a list of torrent_ids')
if not torrent_ids:
- raise ValueError("requires a list of torrent_ids")
+ raise ValueError('requires a list of torrent_ids')
self.__torrent_ids = torrent_ids
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)
+ self.__dialog = self.builder.get_object('remove_torrent_dialog')
+ self.__dialog.set_transient_for(component.get('MainWindow').window)
self.builder.connect_signals({
- "on_delete_files_toggled": self.on_delete_files_toggled
+ 'on_delete_files_toggled': self.on_delete_files_toggled
})
self.builder.get_object('delete_files').set_active(delete_files)
- label_title = self.builder.get_object("label_title")
- label_torrents = self.builder.get_object("label_torrents")
+ label_title = self.builder.get_object('label_title')
+ label_torrents = self.builder.get_object('label_torrents')
num_torrents = len(self.__torrent_ids)
if num_torrents == 1:
- label_torrents.set_markup(component.get("TorrentView").get_torrent_status(self.__torrent_ids[0])["name"])
+ label_torrents.set_markup(component.get('TorrentView').get_torrent_status(self.__torrent_ids[0])['name'])
else:
- label_title.set_markup(_("Remove the selected torrents?"))
- label_torrents.set_markup(_("Total of %s torrents selected") % num_torrents)
+ label_title.set_markup(_('Remove the selected torrents?'))
+ label_torrents.set_markup(_('Total of %s torrents selected') % num_torrents)
def on_delete_files_toggled(self, widget):
self.builder.get_object('warning_label').set_visible(widget.get_active())
def __remove_torrents(self, remove_data):
# Unselect all to avoid issues with the selection changed event
- component.get("TorrentView").treeview.get_selection().unselect_all()
+ component.get('TorrentView').treeview.get_selection().unselect_all()
def on_removed_finished(errors):
if errors:
- log.info("Error(s) occured when trying to delete torrent(s).")
+ log.info('Error(s) occured when trying to delete torrent(s).')
for t_id, e_msg in errors:
- log.warn("Error removing torrent %s : %s", t_id, e_msg)
+ log.warn('Error removing torrent %s : %s', t_id, e_msg)
d = client.core.remove_torrents(self.__torrent_ids, remove_data)
d.addCallback(on_removed_finished)
@@ -81,5 +81,5 @@ class RemoveTorrentDialog(object):
remove the torrent(s) from the session with or without their data.
"""
if self.__dialog.run() == gtk.RESPONSE_OK:
- self.__remove_torrents(self.builder.get_object("delete_files").get_active())
+ self.__remove_torrents(self.builder.get_object('delete_files').get_active())
self.__dialog.destroy()
diff --git a/deluge/ui/gtkui/sidebar.py b/deluge/ui/gtkui/sidebar.py
index 379794dbe..7fc5db6a2 100644
--- a/deluge/ui/gtkui/sidebar.py
+++ b/deluge/ui/gtkui/sidebar.py
@@ -24,40 +24,40 @@ class SideBar(component.Component):
purpose : plugins
"""
def __init__(self):
- component.Component.__init__(self, "SideBar")
- self.window = component.get("MainWindow")
+ component.Component.__init__(self, 'SideBar')
+ self.window = component.get('MainWindow')
builder = self.window.get_builder()
- self.notebook = builder.get_object("sidebar_notebook")
- self.hpaned = builder.get_object("main_window_hpaned")
- self.config = ConfigManager("gtkui.conf")
+ self.notebook = builder.get_object('sidebar_notebook')
+ self.hpaned = builder.get_object('main_window_hpaned')
+ self.config = ConfigManager('gtkui.conf')
# self.hpaned_position = self.hpaned.get_position()
# Tabs holds references to the Tab widgets by their name
self.tabs = {}
# Hide if necessary
- self.visible(self.config["show_sidebar"])
+ self.visible(self.config['show_sidebar'])
def shutdown(self):
- log.debug("hpaned.position: %s", self.hpaned.get_position())
- self.config["sidebar_position"] = self.hpaned.get_position()
+ log.debug('hpaned.position: %s', self.hpaned.get_position())
+ self.config['sidebar_position'] = self.hpaned.get_position()
def visible(self, visible):
if visible:
- if self.config["sidebar_position"]:
- self.hpaned.set_position(self.config["sidebar_position"])
+ if self.config['sidebar_position']:
+ self.hpaned.set_position(self.config['sidebar_position'])
self.notebook.show()
else:
self.notebook.hide()
# Store the position for restoring upon show()
- self.config["sidebar_position"] = self.hpaned.get_position()
+ self.config['sidebar_position'] = self.hpaned.get_position()
self.hpaned.set_position(-1)
- self.config["show_sidebar"] = visible
+ self.config['show_sidebar'] = visible
def add_tab(self, widget, tab_name, label):
"""Adds a tab object to the notebook."""
- log.debug("add tab: %s", tab_name)
+ log.debug('add tab: %s', tab_name)
self.tabs[tab_name] = widget
scrolled = gtk.ScrolledWindow()
scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
diff --git a/deluge/ui/gtkui/status_tab.py b/deluge/ui/gtkui/status_tab.py
index a54632a60..7b9d2ee61 100644
--- a/deluge/ui/gtkui/status_tab.py
+++ b/deluge/ui/gtkui/status_tab.py
@@ -27,43 +27,43 @@ class StatusTab(Tab):
Tab.__init__(self)
# Get the labels we need to update.
# widget name, modifier function, status keys
- self.builder = builder = component.get("MainWindow").get_builder()
+ self.builder = builder = component.get('MainWindow').get_builder()
- self._name = "Status"
- self._child_widget = builder.get_object("status_tab")
- self._tab_label = builder.get_object("status_tab_label")
- self.config = ConfigManager("gtkui.conf")
+ self._name = 'Status'
+ self._child_widget = builder.get_object('status_tab')
+ self._tab_label = builder.get_object('status_tab_label')
+ self.config = ConfigManager('gtkui.conf')
- self.progressbar = builder.get_object("progressbar")
+ self.progressbar = builder.get_object('progressbar')
self.piecesbar = None
self.piecesbar_label_widget = None
self.label_widgets = [
- (builder.get_object("summary_availability"), fratio, ("distributed_copies",)),
- (builder.get_object("summary_total_downloaded"), ftotal_sized, ("all_time_download",
- "total_payload_download")),
- (builder.get_object("summary_total_uploaded"), ftotal_sized, ("total_uploaded", "total_payload_upload")),
- (builder.get_object("summary_download_speed"), fspeed_max, ("download_payload_rate", "max_download_speed")),
- (builder.get_object("summary_upload_speed"), fspeed_max, ("upload_payload_rate", "max_upload_speed")),
- (builder.get_object("summary_seeds"), fpeer, ("num_seeds", "total_seeds")),
- (builder.get_object("summary_peers"), fpeer, ("num_peers", "total_peers")),
- (builder.get_object("summary_eta"), ftime_or_dash, ("eta",)),
- (builder.get_object("summary_share_ratio"), fratio, ("ratio",)),
- (builder.get_object("summary_active_time"), ftime_or_dash, ("active_time",)),
- (builder.get_object("summary_seed_time"), ftime_or_dash, ("seeding_time",)),
- (builder.get_object("summary_seed_rank"), fseed_rank_or_dash, ("seed_rank", "seeding_time")),
- (builder.get_object("progressbar"), fpcnt, ("progress", "state", "message")),
- (builder.get_object("summary_last_seen_complete"), fdate_or_never, ("last_seen_complete",)),
- (builder.get_object("summary_last_active"), flast_active, ("time_since_download",
- "time_since_upload")),
+ (builder.get_object('summary_availability'), fratio, ('distributed_copies',)),
+ (builder.get_object('summary_total_downloaded'), ftotal_sized, ('all_time_download',
+ 'total_payload_download')),
+ (builder.get_object('summary_total_uploaded'), ftotal_sized, ('total_uploaded', 'total_payload_upload')),
+ (builder.get_object('summary_download_speed'), fspeed_max, ('download_payload_rate', 'max_download_speed')),
+ (builder.get_object('summary_upload_speed'), fspeed_max, ('upload_payload_rate', 'max_upload_speed')),
+ (builder.get_object('summary_seeds'), fpeer, ('num_seeds', 'total_seeds')),
+ (builder.get_object('summary_peers'), fpeer, ('num_peers', 'total_peers')),
+ (builder.get_object('summary_eta'), ftime_or_dash, ('eta',)),
+ (builder.get_object('summary_share_ratio'), fratio, ('ratio',)),
+ (builder.get_object('summary_active_time'), ftime_or_dash, ('active_time',)),
+ (builder.get_object('summary_seed_time'), ftime_or_dash, ('seeding_time',)),
+ (builder.get_object('summary_seed_rank'), fseed_rank_or_dash, ('seed_rank', 'seeding_time')),
+ (builder.get_object('progressbar'), fpcnt, ('progress', 'state', 'message')),
+ (builder.get_object('summary_last_seen_complete'), fdate_or_never, ('last_seen_complete',)),
+ (builder.get_object('summary_last_active'), flast_active, ('time_since_download',
+ 'time_since_upload')),
]
self.status_keys = [status for widget in self.label_widgets for status in widget[2]]
- self.config.register_set_function("show_piecesbar", self.on_show_piecesbar_config_changed, apply_now=True)
+ self.config.register_set_function('show_piecesbar', self.on_show_piecesbar_config_changed, apply_now=True)
def update(self):
# Get the first selected torrent
- selected = component.get("TorrentView").get_selected_torrent()
+ selected = component.get('TorrentView').get_selected_torrent()
if not selected:
# No torrent is selected in the torrentview
@@ -73,9 +73,9 @@ class StatusTab(Tab):
# Get the torrent status
status_keys = self.status_keys
if self.config['show_piecesbar']:
- status_keys.extend(["pieces", "num_pieces"])
+ status_keys.extend(['pieces', 'num_pieces'])
- component.get("SessionProxy").get_torrent_status(
+ component.get('SessionProxy').get_torrent_status(
selected, status_keys).addCallback(self._on_get_torrent_status)
def _on_get_torrent_status(self, status):
@@ -90,12 +90,12 @@ class StatusTab(Tab):
widget[0].set_text(txt)
# Update progress bar seperately as it's a special case (not a label).
- fraction = status["progress"] / 100
+ fraction = status['progress'] / 100
if self.config['show_piecesbar']:
if self.piecesbar.get_fraction() != fraction:
self.piecesbar.set_fraction(fraction)
- if status["state"] != "Checking" and self.piecesbar.get_pieces() != status['pieces']:
+ if status['state'] != 'Checking' and self.piecesbar.get_pieces() != status['pieces']:
# Skip pieces assignment if checking torrent.
self.piecesbar.set_pieces(status['pieces'], status['num_pieces'])
self.piecesbar.update()
@@ -112,8 +112,8 @@ class StatusTab(Tab):
def show_piecesbar(self):
if self.piecesbar is None:
self.piecesbar = PiecesBar()
- self.builder.get_object("status_progress_vbox").pack_start(self.piecesbar, False, False, 0)
- self.piecesbar_label_widget = (self.piecesbar, fpcnt, ("progress", "state", "message"))
+ self.builder.get_object('status_progress_vbox').pack_start(self.piecesbar, False, False, 0)
+ self.piecesbar_label_widget = (self.piecesbar, fpcnt, ('progress', 'state', 'message'))
self.label_widgets.append(self.piecesbar_label_widget)
self.piecesbar.show()
self.progressbar.hide()
@@ -127,7 +127,7 @@ class StatusTab(Tab):
def clear(self):
for widget in self.label_widgets:
- widget[0].set_text("")
+ widget[0].set_text('')
if self.config['show_piecesbar']:
self.piecesbar.clear()
diff --git a/deluge/ui/gtkui/statusbar.py b/deluge/ui/gtkui/statusbar.py
index fb742fcf7..61b3e7836 100644
--- a/deluge/ui/gtkui/statusbar.py
+++ b/deluge/ui/gtkui/statusbar.py
@@ -57,7 +57,7 @@ class StatusBarItem(object):
self.show_all()
def set_callback(self, callback):
- self._ebox.connect("button-press-event", callback)
+ self._ebox.connect('button-press-event', callback)
def show_all(self):
self._ebox.show()
@@ -100,18 +100,18 @@ class StatusBarItem(object):
class StatusBar(component.Component):
def __init__(self):
- component.Component.__init__(self, "StatusBar", interval=3)
- self.window = component.get("MainWindow")
- self.statusbar = self.window.get_builder().get_object("statusbar")
- self.config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'StatusBar', interval=3)
+ self.window = component.get('MainWindow')
+ self.statusbar = self.window.get_builder().get_object('statusbar')
+ self.config = ConfigManager('gtkui.conf')
# Status variables that are updated via callback
self.max_connections_global = -1
self.num_connections = 0
self.max_download_speed = -1.0
- self.download_rate = ""
+ self.download_rate = ''
self.max_upload_speed = -1.0
- self.upload_rate = ""
+ self.upload_rate = ''
self.dht_nodes = 0
self.dht_status = False
self.health = False
@@ -119,10 +119,10 @@ class StatusBar(component.Component):
self.upload_protocol_rate = 0.0
self.config_value_changed_dict = {
- "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
+ '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
}
self.current_warnings = []
# Add a HBox to the statusbar after removing the initial label widget
@@ -137,15 +137,15 @@ class StatusBar(component.Component):
self.statusbar.show_all()
# Create the not connected item
self.not_connected_item = StatusBarItem(
- stock=gtk.STOCK_STOP, text=_("Not Connected"),
+ stock=gtk.STOCK_STOP, text=_('Not Connected'),
callback=self._on_notconnected_item_clicked)
# Show the not connected status bar
self.show_not_connected()
# Hide if necessary
- self.visible(self.config["show_statusbar"])
+ self.visible(self.config['show_statusbar'])
- client.register_event_handler("ConfigValueChangedEvent", self.on_configvaluechanged_event)
+ client.register_event_handler('ConfigValueChangedEvent', self.on_configvaluechanged_event)
def start(self):
# Add in images and labels
@@ -154,51 +154,51 @@ 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"),
+ 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"),
+ 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"),
+ 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>"),
+ text=_('<b><small>Port Issue</small></b>'),
markup=True,
- tooltip=_("No incoming connections, check port forwarding"),
+ tooltip=_('No incoming connections, check port forwarding'),
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
def update_config_values(configs):
- self._on_max_connections_global(configs["max_connections_global"])
- self._on_max_download_speed(configs["max_download_speed"])
- self._on_max_upload_speed(configs["max_upload_speed"])
- self._on_dht(configs["dht"])
+ self._on_max_connections_global(configs['max_connections_global'])
+ self._on_max_download_speed(configs['max_download_speed'])
+ 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
@@ -213,7 +213,7 @@ class StatusBar(component.Component):
self.remove_item(self.diskspace_item)
self.remove_item(self.external_ip_item)
except Exception as ex:
- log.debug("Unable to remove StatusBar item: %s", ex)
+ log.debug('Unable to remove StatusBar item: %s', ex)
self.show_not_connected()
def visible(self, visible):
@@ -222,7 +222,7 @@ class StatusBar(component.Component):
else:
self.statusbar.hide()
- self.config["show_statusbar"] = visible
+ self.config['show_statusbar'] = visible
def show_not_connected(self):
self.hbox.pack_start(
@@ -244,7 +244,7 @@ class StatusBar(component.Component):
try:
self.hbox.remove(item.get_eventbox())
except Exception as ex:
- log.debug("Unable to remove widget: %s", ex)
+ log.debug('Unable to remove widget: %s', ex)
def add_timeout_item(self, seconds=3, image=None, stock=None, text=None, callback=None):
"""Adds an item to the StatusBar for seconds"""
@@ -271,13 +271,13 @@ class StatusBar(component.Component):
def send_status_request(self):
# Sends an async request for data from the core
- keys = ["num_peers", "upload_rate", "download_rate", "payload_upload_rate", "payload_download_rate"]
+ keys = ['num_peers', 'upload_rate', 'download_rate', 'payload_upload_rate', 'payload_download_rate']
if self.dht_status:
- keys.append("dht_nodes")
+ keys.append('dht_nodes')
if not self.health:
- keys.append("has_incoming_connections")
+ keys.append('has_incoming_connections')
client.core.get_session_status(keys).addCallback(self._on_get_session_status)
client.core.get_free_space().addCallback(self._on_get_free_space)
@@ -305,30 +305,30 @@ class StatusBar(component.Component):
self.remove_item(self.dht_item)
def _on_get_session_status(self, status):
- self.download_rate = fspeed(status["payload_download_rate"], precision=0, shortform=True)
- self.upload_rate = fspeed(status["payload_upload_rate"], precision=0, shortform=True)
- self.download_protocol_rate = (status["download_rate"] - status["payload_download_rate"]) // 1024
- self.upload_protocol_rate = (status["upload_rate"] - status["payload_upload_rate"]) // 1024
- self.num_connections = status["num_peers"]
+ self.download_rate = fspeed(status['payload_download_rate'], precision=0, shortform=True)
+ self.upload_rate = fspeed(status['payload_upload_rate'], precision=0, shortform=True)
+ self.download_protocol_rate = (status['download_rate'] - status['payload_download_rate']) // 1024
+ self.upload_protocol_rate = (status['upload_rate'] - status['payload_upload_rate']) // 1024
+ self.num_connections = status['num_peers']
self.update_download_label()
self.update_upload_label()
self.update_traffic_label()
self.update_connections_label()
- if "dht_nodes" in status:
- self.dht_nodes = status["dht_nodes"]
+ if 'dht_nodes' in status:
+ self.dht_nodes = status['dht_nodes']
self.update_dht_label()
- if "has_incoming_connections" in status:
- self.health = status["has_incoming_connections"]
+ if 'has_incoming_connections' in status:
+ self.health = status['has_incoming_connections']
if self.health:
self.remove_item(self.health_item)
def _on_get_free_space(self, space):
if space >= 0:
- self.diskspace_item.set_markup("<small>%s</small>" % fsize(space, shortform=True))
+ self.diskspace_item.set_markup('<small>%s</small>' % fsize(space, shortform=True))
else:
- self.diskspace_item.set_markup("<span foreground=\"red\">" + _("Error") + "</span>")
+ self.diskspace_item.set_markup("<span foreground=\"red\">" + _('Error') + '</span>')
def _on_max_download_speed(self, max_download_speed):
self.max_download_speed = max_download_speed
@@ -339,29 +339,29 @@ class StatusBar(component.Component):
self.update_upload_label()
def _on_get_external_ip(self, external_ip):
- ip = external_ip if external_ip else _("n/a")
- self.external_ip_item.set_markup(_("<b>IP</b> <small>%s</small>") % ip)
+ ip = external_ip if external_ip else _('n/a')
+ self.external_ip_item.set_markup(_('<b>IP</b> <small>%s</small>') % ip)
def update_connections_label(self):
# Set the max connections label
if self.max_connections_global < 0:
- label_string = "%s" % self.num_connections
+ label_string = '%s' % self.num_connections
else:
- label_string = "%s <small>(%s)</small>" % (self.num_connections, self.max_connections_global)
+ label_string = '%s <small>(%s)</small>' % (self.num_connections, self.max_connections_global)
self.connections_item.set_markup(label_string)
def update_dht_label(self):
# Set the max connections label
- self.dht_item.set_markup("<small>%s</small>" % (self.dht_nodes))
+ self.dht_item.set_markup('<small>%s</small>' % (self.dht_nodes))
def update_download_label(self):
# Set the download speed label
if self.max_download_speed <= 0:
label_string = self.download_rate
else:
- label_string = "%s <small>(%i %s)</small>" % (
- self.download_rate, self.max_download_speed, _("K/s"))
+ label_string = '%s <small>(%i %s)</small>' % (
+ self.download_rate, self.max_download_speed, _('K/s'))
self.download_item.set_markup(label_string)
@@ -370,27 +370,27 @@ class StatusBar(component.Component):
if self.max_upload_speed <= 0:
label_string = self.upload_rate
else:
- label_string = "%s <small>(%i %s)</small>" % (
- self.upload_rate, self.max_upload_speed, _("K/s"))
+ label_string = '%s <small>(%i %s)</small>' % (
+ self.upload_rate, self.max_upload_speed, _('K/s'))
self.upload_item.set_markup(label_string)
def update_traffic_label(self):
- label_string = "<small>%i:%i %s</small>" % (self.download_protocol_rate, self.upload_protocol_rate, _("K/s"))
+ label_string = '<small>%i:%i %s</small>' % (self.download_protocol_rate, self.upload_protocol_rate, _('K/s'))
self.traffic_item.set_markup(label_string)
def update(self):
self.send_status_request()
def set_limit_value(self, widget, core_key):
- log.debug("_on_set_unlimit_other %s", 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):
@@ -403,64 +403,64 @@ class StatusBar(component.Component):
if value != getattr(self, core_key):
client.core.set_config({core_key: value})
- if widget.get_name() == "unlimited":
+ if widget.get_name() == 'unlimited':
set_value(-1)
- elif widget.get_name() == "other":
+ elif widget.get_name() == 'other':
def dialog_finished(response_id):
if response_id == gtk.RESPONSE_OK:
set_value(dialog.get_value())
dialog = dialogs.OtherDialog(*other_dialog_info[core_key])
dialog.run().addCallback(set_value)
else:
- value = widget.get_children()[0].get_text().split(" ")[0]
+ value = widget.get_children()[0].get_text().split(' ')[0]
set_value(value)
def _on_download_item_clicked(self, widget, event):
menu = common.build_menu_radio_list(
- self.config["tray_download_speed_list"],
+ 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)
def _on_set_download_speed(self, widget):
- log.debug("_on_set_download_speed")
- self.set_limit_value(widget, "max_download_speed")
+ log.debug('_on_set_download_speed')
+ self.set_limit_value(widget, 'max_download_speed')
def _on_upload_item_clicked(self, widget, event):
menu = common.build_menu_radio_list(
- self.config["tray_upload_speed_list"],
+ 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)
def _on_set_upload_speed(self, widget):
- log.debug("_on_set_upload_speed")
- self.set_limit_value(widget, "max_upload_speed")
+ log.debug('_on_set_upload_speed')
+ self.set_limit_value(widget, 'max_upload_speed')
def _on_connection_item_clicked(self, widget, event):
menu = common.build_menu_radio_list(
- self.config["connection_limit_list"],
+ self.config['connection_limit_list'],
self._on_set_connection_limit,
self.max_connections_global, show_notset=True, show_other=True)
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
def _on_set_connection_limit(self, widget):
- log.debug("_on_set_connection_limit")
- self.set_limit_value(widget, "max_connections_global")
+ log.debug('_on_set_connection_limit')
+ self.set_limit_value(widget, 'max_connections_global')
def _on_health_icon_clicked(self, widget, event):
- component.get("Preferences").show("Network")
+ component.get('Preferences').show('Network')
def _on_notconnected_item_clicked(self, widget, event):
- component.get("ConnectionManager").show()
+ component.get('ConnectionManager').show()
def _on_traffic_item_clicked(self, widget, event):
- component.get("Preferences").show("Network")
+ component.get('Preferences').show('Network')
def _on_diskspace_item_clicked(self, widget, event):
- component.get("Preferences").show("Downloads")
+ component.get('Preferences').show('Downloads')
diff --git a/deluge/ui/gtkui/systemtray.py b/deluge/ui/gtkui/systemtray.py
index 5fe1f2793..97fa53c0c 100644
--- a/deluge/ui/gtkui/systemtray.py
+++ b/deluge/ui/gtkui/systemtray.py
@@ -30,26 +30,26 @@ log = logging.getLogger(__name__)
class SystemTray(component.Component):
def __init__(self):
- component.Component.__init__(self, "SystemTray", interval=4)
- self.window = component.get("MainWindow")
- self.config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'SystemTray', interval=4)
+ self.window = component.get('MainWindow')
+ self.config = ConfigManager('gtkui.conf')
# List of widgets that need to be hidden when not connected to a host
self.hide_widget_list = [
- "menuitem_add_torrent",
- "menuitem_pause_session",
- "menuitem_resume_session",
- "menuitem_download_limit",
- "menuitem_upload_limit",
- "menuitem_quitdaemon",
- "separatormenuitem1",
- "separatormenuitem2",
- "separatormenuitem3",
- "separatormenuitem4"
+ 'menuitem_add_torrent',
+ 'menuitem_pause_session',
+ 'menuitem_resume_session',
+ 'menuitem_download_limit',
+ 'menuitem_upload_limit',
+ 'menuitem_quitdaemon',
+ 'separatormenuitem1',
+ 'separatormenuitem2',
+ 'separatormenuitem3',
+ 'separatormenuitem4'
]
- self.config.register_set_function("enable_system_tray", self.on_enable_system_tray_set)
+ 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
self.__enabled_set_once = False
- self.config.register_set_function("enable_appindicator", self.on_enable_appindicator_set)
+ self.config.register_set_function('enable_appindicator', self.on_enable_appindicator_set)
self.max_download_speed = -1.0
self.download_rate = 0.0
@@ -57,33 +57,33 @@ class SystemTray(component.Component):
self.upload_rate = 0.0
self.config_value_changed_dict = {
- "max_download_speed": self._on_max_download_speed,
- "max_upload_speed": self._on_max_upload_speed
+ 'max_download_speed': self._on_max_download_speed,
+ 'max_upload_speed': self._on_max_upload_speed
}
def enable(self):
"""Enables the system tray icon."""
self.builder = gtk.Builder()
self.builder.add_from_file(deluge.common.resource_filename(
- "deluge.ui.gtkui", os.path.join("glade", "tray_menu.ui")))
+ 'deluge.ui.gtkui', os.path.join('glade', 'tray_menu.ui')))
self.builder.connect_signals({
- "on_menuitem_show_deluge_activate": self.on_menuitem_show_deluge_activate,
- "on_menuitem_add_torrent_activate": self.on_menuitem_add_torrent_activate,
- "on_menuitem_pause_session_activate": self.on_menuitem_pause_session_activate,
- "on_menuitem_resume_session_activate": self.on_menuitem_resume_session_activate,
- "on_menuitem_quit_activate": self.on_menuitem_quit_activate,
- "on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate
+ 'on_menuitem_show_deluge_activate': self.on_menuitem_show_deluge_activate,
+ 'on_menuitem_add_torrent_activate': self.on_menuitem_add_torrent_activate,
+ 'on_menuitem_pause_session_activate': self.on_menuitem_pause_session_activate,
+ 'on_menuitem_resume_session_activate': self.on_menuitem_resume_session_activate,
+ 'on_menuitem_quit_activate': self.on_menuitem_quit_activate,
+ 'on_menuitem_quitdaemon_activate': self.on_menuitem_quitdaemon_activate
})
- self.tray_menu = self.builder.get_object("tray_menu")
+ self.tray_menu = self.builder.get_object('tray_menu')
- if appindicator and self.config["enable_appindicator"]:
- log.debug("Enabling the Application Indicator...")
- self.indicator = appindicator.Indicator("deluge", "deluge",
+ if appindicator and self.config['enable_appindicator']:
+ log.debug('Enabling the Application Indicator...')
+ self.indicator = appindicator.Indicator('deluge', 'deluge',
appindicator.CATEGORY_APPLICATION_STATUS)
try:
- self.indicator.set_property("title", _("Deluge"))
+ self.indicator.set_property('title', _('Deluge'))
except TypeError:
# Catch 'title' property error for previous appindicator versions
pass
@@ -91,32 +91,32 @@ class SystemTray(component.Component):
self.indicator.set_menu(self.tray_menu)
# Make sure the status of the Show Window MenuItem is correct
- self._sig_win_hide = self.window.window.connect("hide", self._on_window_hide)
- self._sig_win_show = self.window.window.connect("show", self._on_window_show)
+ self._sig_win_hide = self.window.window.connect('hide', self._on_window_hide)
+ self._sig_win_show = self.window.window.connect('show', self._on_window_show)
if self.window.visible():
- self.builder.get_object("menuitem_show_deluge").set_active(True)
+ self.builder.get_object('menuitem_show_deluge').set_active(True)
else:
- self.builder.get_object("menuitem_show_deluge").set_active(False)
+ self.builder.get_object('menuitem_show_deluge').set_active(False)
# Show the Application Indicator
self.indicator.set_status(appindicator.STATUS_ACTIVE)
else:
- log.debug("Enabling the system tray icon..")
+ log.debug('Enabling the system tray icon..')
if deluge.common.windows_check() or deluge.common.osx_check():
self.tray = gtk.status_icon_new_from_pixbuf(get_logo(32))
else:
- self.tray = gtk.status_icon_new_from_icon_name("deluge")
+ self.tray = gtk.status_icon_new_from_icon_name('deluge')
- self.tray.connect("activate", self.on_tray_clicked)
- self.tray.connect("popup-menu", self.on_tray_popup)
+ self.tray.connect('activate', self.on_tray_clicked)
+ self.tray.connect('popup-menu', self.on_tray_popup)
- 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"))
+ 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'))
- client.register_event_handler("ConfigValueChangedEvent", self.config_value_changed)
+ client.register_event_handler('ConfigValueChangedEvent', self.config_value_changed)
if client.connected():
# We're connected so we need to get some values from the core
self.__start()
@@ -126,16 +126,16 @@ class SystemTray(component.Component):
self.builder.get_object(widget).hide()
def __start(self):
- if self.config["enable_system_tray"]:
+ if self.config['enable_system_tray']:
- if self.config["standalone"]:
+ if self.config['standalone']:
try:
- self.hide_widget_list.remove("menuitem_quitdaemon")
- self.hide_widget_list.remove("separatormenuitem4")
+ self.hide_widget_list.remove('menuitem_quitdaemon')
+ self.hide_widget_list.remove('separatormenuitem4')
except ValueError:
pass
- self.builder.get_object("menuitem_quitdaemon").hide()
- self.builder.get_object("separatormenuitem4").hide()
+ self.builder.get_object('menuitem_quitdaemon').hide()
+ self.builder.get_object('separatormenuitem4').hide()
# Show widgets in the hide list because we've connected to a host
for widget in self.hide_widget_list:
@@ -146,35 +146,35 @@ class SystemTray(component.Component):
# Get some config values
def update_config_values(configs):
- self._on_max_download_speed(configs["max_download_speed"])
- self._on_max_upload_speed(configs["max_upload_speed"])
- client.core.get_config_values(["max_download_speed", "max_upload_speed"]).addCallback(update_config_values)
+ self._on_max_download_speed(configs['max_download_speed'])
+ self._on_max_upload_speed(configs['max_upload_speed'])
+ client.core.get_config_values(['max_download_speed', 'max_upload_speed']).addCallback(update_config_values)
def start(self):
self.__start()
def stop(self):
- if self.config["enable_system_tray"] and not self.config["enable_appindicator"]:
+ if self.config['enable_system_tray'] and not self.config['enable_appindicator']:
try:
# Hide widgets in hide list because we're not connected to a host
for widget in self.hide_widget_list:
self.builder.get_object(widget).hide()
except Exception as ex:
- log.debug("Unable to hide system tray menu widgets: %s", ex)
+ log.debug('Unable to hide system tray menu widgets: %s', ex)
- self.tray.set_tooltip(_("Deluge") + "\n" + _("Not Connected..."))
+ self.tray.set_tooltip(_('Deluge') + '\n' + _('Not Connected...'))
def shutdown(self):
- if self.config["enable_system_tray"]:
- if appindicator and self.config["enable_appindicator"]:
+ if self.config['enable_system_tray']:
+ if appindicator and self.config['enable_appindicator']:
self.indicator.set_status(appindicator.STATUS_PASSIVE)
else:
self.tray.set_visible(False)
def send_status_request(self):
client.core.get_session_status([
- "payload_upload_rate",
- "payload_download_rate"]).addCallback(self._on_get_session_status)
+ 'payload_upload_rate',
+ '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
@@ -193,19 +193,19 @@ class SystemTray(component.Component):
self.build_tray_bwsetsubmenu()
def _on_get_session_status(self, status):
- self.download_rate = fspeed(status["payload_download_rate"], shortform=True)
- self.upload_rate = fspeed(status["payload_upload_rate"], shortform=True)
+ self.download_rate = fspeed(status['payload_download_rate'], shortform=True)
+ self.upload_rate = fspeed(status['payload_upload_rate'], shortform=True)
def update(self):
- if not self.config["enable_system_tray"]:
+ if not self.config['enable_system_tray']:
return
# Tool tip text not available for appindicator
- if appindicator and self.config["enable_appindicator"]:
+ if appindicator and self.config['enable_appindicator']:
if self.window.visible():
- self.builder.get_object("menuitem_show_deluge").set_active(True)
+ self.builder.get_object('menuitem_show_deluge').set_active(True)
else:
- self.builder.get_object("menuitem_show_deluge").set_active(False)
+ self.builder.get_object('menuitem_show_deluge').set_active(False)
return
# Set the tool tip text
@@ -213,17 +213,17 @@ class SystemTray(component.Component):
max_upload_speed = self.max_upload_speed
if max_download_speed == -1:
- max_download_speed = _("Unlimited")
+ max_download_speed = _('Unlimited')
else:
- max_download_speed = "%s %s" % (max_download_speed, _("K/s"))
+ max_download_speed = '%s %s' % (max_download_speed, _('K/s'))
if max_upload_speed == -1:
- max_upload_speed = _("Unlimited")
+ max_upload_speed = _('Unlimited')
else:
- max_upload_speed = "%s %s" % (max_upload_speed, _("K/s"))
+ max_upload_speed = '%s %s' % (max_upload_speed, _('K/s'))
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
+ _('Deluge'), _('Down'), self.download_rate,
+ max_download_speed, _('Up'), self.upload_rate, max_upload_speed
)
# Set the tooltip
@@ -234,21 +234,21 @@ class SystemTray(component.Component):
def build_tray_bwsetsubmenu(self):
# Create the Download speed list sub-menu
submenu_bwdownset = build_menu_radio_list(
- self.config["tray_download_speed_list"], self.on_tray_setbwdown,
+ 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.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(
+ self.builder.get_object('menuitem_download_limit').set_submenu(
submenu_bwdownset)
- self.builder.get_object("menuitem_upload_limit").set_submenu(
+ self.builder.get_object('menuitem_upload_limit').set_submenu(
submenu_bwupset)
# Show the sub-menus for all to see
@@ -259,25 +259,25 @@ class SystemTray(component.Component):
"""Disables the system tray icon or appindicator."""
try:
if invert_app_ind_conf:
- app_ind_conf = not self.config["enable_appindicator"]
+ app_ind_conf = not self.config['enable_appindicator']
else:
- app_ind_conf = self.config["enable_appindicator"]
+ app_ind_conf = self.config['enable_appindicator']
if appindicator and app_ind_conf:
- if hasattr(self, "_sig_win_hide"):
+ if hasattr(self, '_sig_win_hide'):
self.window.window.disconnect(self._sig_win_hide)
self.window.window.disconnect(self._sig_win_show)
- log.debug("Disabling the application indicator..")
+ log.debug('Disabling the application indicator..')
self.indicator.set_status(appindicator.STATUS_PASSIVE)
del self.indicator
else:
- log.debug("Disabling the system tray icon..")
+ log.debug('Disabling the system tray icon..')
self.tray.set_visible(False)
del self.tray
del self.builder
del self.tray_menu
except Exception as ex:
- log.debug("Unable to disable system tray: %s", ex)
+ log.debug('Unable to disable system tray: %s', ex)
def blink(self, value):
try:
@@ -315,9 +315,9 @@ class SystemTray(component.Component):
self.blink(False)
if self.window.visible():
- self.builder.get_object("menuitem_show_deluge").set_active(True)
+ self.builder.get_object('menuitem_show_deluge').set_active(True)
else:
- self.builder.get_object("menuitem_show_deluge").set_active(False)
+ self.builder.get_object('menuitem_show_deluge').set_active(False)
popup_function = gtk.status_icon_position_menu
if deluge.common.windows_check() or deluge.common.osx_check():
@@ -326,30 +326,30 @@ class SystemTray(component.Component):
self.tray_menu.popup(None, None, popup_function, button, activate_time, status_icon)
def on_menuitem_show_deluge_activate(self, menuitem):
- log.debug("on_menuitem_show_deluge_activate")
+ log.debug('on_menuitem_show_deluge_activate')
if menuitem.get_active() and not self.window.visible():
self.window.present()
elif not menuitem.get_active() and self.window.visible():
self.window.hide()
def on_menuitem_add_torrent_activate(self, menuitem):
- log.debug("on_menuitem_add_torrent_activate")
- component.get("AddTorrentDialog").show()
+ log.debug('on_menuitem_add_torrent_activate')
+ component.get('AddTorrentDialog').show()
def on_menuitem_pause_session_activate(self, menuitem):
- log.debug("on_menuitem_pause_session_activate")
+ log.debug('on_menuitem_pause_session_activate')
client.core.pause_session()
def on_menuitem_resume_session_activate(self, menuitem):
- log.debug("on_menuitem_resume_session_activate")
+ log.debug('on_menuitem_resume_session_activate')
client.core.resume_session()
def on_menuitem_quit_activate(self, menuitem):
- log.debug("on_menuitem_quit_activate")
+ log.debug('on_menuitem_quit_activate')
self.window.quit()
def on_menuitem_quitdaemon_activate(self, menuitem):
- log.debug("on_menuitem_quitdaemon_activate")
+ log.debug('on_menuitem_quitdaemon_activate')
self.window.quit(shutdown=True)
def on_tray_setbwdown(self, widget, data=None):
@@ -357,28 +357,28 @@ 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, gtk.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"""
- log.debug("_on_window_hide")
- self.builder.get_object("menuitem_show_deluge").set_active(False)
+ log.debug('_on_window_hide')
+ self.builder.get_object('menuitem_show_deluge').set_active(False)
def _on_window_show(self, widget, data=None):
"""_on_window_show - update the menuitem's status"""
- log.debug("_on_window_show")
- self.builder.get_object("menuitem_show_deluge").set_active(True)
+ log.debug('_on_window_show')
+ self.builder.get_object('menuitem_show_deluge').set_active(True)
def setbwlimit(self, widget, header, text, core_key, ui_key, default, image):
"""Sets the bandwidth limit based on the user selection."""
@@ -391,10 +391,10 @@ class SystemTray(component.Component):
# Set the config in the core
client.core.set_config({core_key: value})
- if widget.get_name() == "unlimited":
+ if widget.get_name() == 'unlimited':
set_value(-1)
- elif widget.get_name() == "other":
- dialog = dialogs.OtherDialog(header, text, _("K/s"), image, default)
+ elif widget.get_name() == 'other':
+ dialog = dialogs.OtherDialog(header, text, _('K/s'), image, default)
dialog.run().addCallback(set_value)
else:
- set_value(widget.get_children()[0].get_text().split(" ")[0])
+ set_value(widget.get_children()[0].get_text().split(' ')[0])
diff --git a/deluge/ui/gtkui/tab_data_funcs.py b/deluge/ui/gtkui/tab_data_funcs.py
index ef87de4ed..fcf2249b2 100644
--- a/deluge/ui/gtkui/tab_data_funcs.py
+++ b/deluge/ui/gtkui/tab_data_funcs.py
@@ -11,30 +11,30 @@ from deluge.common import fdate, fsize, fspeed, ftime
def ftotal_sized(first, second):
- return "%s (%s)" % (fsize(first, shortform=True), fsize(second, shortform=True))
+ return '%s (%s)' % (fsize(first, shortform=True), fsize(second, shortform=True))
def fratio(value):
- return ("%.3f" % value).rstrip('0').rstrip('.') if value > 0 else "∞"
+ return ('%.3f' % value).rstrip('0').rstrip('.') if value > 0 else '∞'
def fpcnt(value, state, message):
textstr = _(state)
- if state not in ("Error", "Seeding") and value < 100:
+ if state not in ('Error', 'Seeding') and value < 100:
textstr = ('%s %.2f' % (textstr, value)).rstrip('0').rstrip('.') + '%'
- elif state == "Error":
- textstr = _("%s: %s") % (textstr, message)
+ elif state == 'Error':
+ textstr = _('%s: %s') % (textstr, message)
return textstr
def fspeed_max(value, max_value=-1):
value = fspeed(value, shortform=True)
- return "%s (%s %s)" % (value, max_value, _("K/s")) if max_value > -1 else value
+ return '%s (%s %s)' % (value, max_value, _('K/s')) if max_value > -1 else value
def fdate_or_never(value):
"""Display value as date, eg 05/05/08 or Never"""
- return fdate(value, date_only=True) if value > 0 else _("Never")
+ return fdate(value, date_only=True) if value > 0 else _('Never')
def fdate_or_dash(value):
@@ -42,12 +42,12 @@ def fdate_or_dash(value):
if value > 0.0:
return fdate(value)
else:
- return "-"
+ return '-'
def ftime_or_dash(value):
"""Display value as time, eg 2h 30m or dash"""
- return ftime(value) if value > 0 else "-"
+ return ftime(value) if value > 0 else '-'
def fseed_rank_or_dash(seed_rank, seeding_time):
@@ -55,11 +55,11 @@ def fseed_rank_or_dash(seed_rank, seeding_time):
if seeding_time > 0:
if seed_rank >= 1000:
- return "%ik" % (seed_rank // 1000)
+ return '%ik' % (seed_rank // 1000)
else:
return str(seed_rank)
else:
- return "-"
+ return '-'
def flast_active(time_since_download, time_since_upload):
@@ -68,17 +68,17 @@ def flast_active(time_since_download, time_since_upload):
try:
last_time_since = min((x for x in (time_since_download, time_since_upload) if x != -1))
except ValueError:
- return "-"
+ return '-'
else:
return ftime(last_time_since)
def fpieces_num_size(num_pieces, piece_size):
- return "%s (%s)" % (num_pieces, fsize(piece_size, precision=0))
+ return '%s (%s)' % (num_pieces, fsize(piece_size, precision=0))
def fcount(value):
- return "%s" % len(value)
+ return '%s' % len(value)
def ftranslate(text):
@@ -89,4 +89,4 @@ def ftranslate(text):
def fyes_no(value):
"""Return Yes or No to bool value"""
- return _("Yes") if value else _("No")
+ return _('Yes') if value else _('No')
diff --git a/deluge/ui/gtkui/toolbar.py b/deluge/ui/gtkui/toolbar.py
index 2a78f4b7f..ffde58ec4 100644
--- a/deluge/ui/gtkui/toolbar.py
+++ b/deluge/ui/gtkui/toolbar.py
@@ -23,39 +23,39 @@ log = logging.getLogger(__name__)
class ToolBar(component.Component):
def __init__(self):
- component.Component.__init__(self, "ToolBar")
- log.debug("ToolBar Init..")
- self.window = component.get("MainWindow")
- self.toolbar = self.window.get_builder().get_object("toolbar")
- self.config = ConfigManager("gtkui.conf")
+ component.Component.__init__(self, 'ToolBar')
+ log.debug('ToolBar Init..')
+ self.window = component.get('MainWindow')
+ self.toolbar = self.window.get_builder().get_object('toolbar')
+ self.config = ConfigManager('gtkui.conf')
# Connect main window Signals #
self.window.connect_signals({
- "on_toolbutton_add_clicked": self.on_toolbutton_add_clicked,
- "on_toolbutton_remove_clicked": self.on_toolbutton_remove_clicked,
- "on_toolbutton_pause_clicked": self.on_toolbutton_pause_clicked,
- "on_toolbutton_resume_clicked": self.on_toolbutton_resume_clicked,
- "on_toolbutton_preferences_clicked": self.on_toolbutton_preferences_clicked,
- "on_toolbutton_connectionmanager_clicked": self.on_toolbutton_connectionmanager_clicked,
- "on_toolbutton_queue_up_clicked": self.on_toolbutton_queue_up_clicked,
- "on_toolbutton_queue_down_clicked": self.on_toolbutton_queue_down_clicked
+ 'on_toolbutton_add_clicked': self.on_toolbutton_add_clicked,
+ 'on_toolbutton_remove_clicked': self.on_toolbutton_remove_clicked,
+ 'on_toolbutton_pause_clicked': self.on_toolbutton_pause_clicked,
+ 'on_toolbutton_resume_clicked': self.on_toolbutton_resume_clicked,
+ 'on_toolbutton_preferences_clicked': self.on_toolbutton_preferences_clicked,
+ 'on_toolbutton_connectionmanager_clicked': self.on_toolbutton_connectionmanager_clicked,
+ 'on_toolbutton_queue_up_clicked': self.on_toolbutton_queue_up_clicked,
+ 'on_toolbutton_queue_down_clicked': self.on_toolbutton_queue_down_clicked
})
self.change_sensitivity = [
- "toolbutton_add",
- "toolbutton_remove",
- "toolbutton_pause",
- "toolbutton_resume",
- "toolbutton_queue_up",
- "toolbutton_queue_down",
- "toolbutton_filter",
- "find_menuitem"
+ 'toolbutton_add',
+ 'toolbutton_remove',
+ 'toolbutton_pause',
+ 'toolbutton_resume',
+ 'toolbutton_queue_up',
+ 'toolbutton_queue_down',
+ 'toolbutton_filter',
+ 'find_menuitem'
]
# Hide if necessary
- self.visible(self.config["show_toolbar"])
+ self.visible(self.config['show_toolbar'])
def start(self):
- self.window.get_builder().get_object("toolbutton_connectionmanager").set_visible(
- not self.config["standalone"])
+ self.window.get_builder().get_object('toolbutton_connectionmanager').set_visible(
+ not self.config['standalone'])
for widget in self.change_sensitivity:
self.window.get_builder().get_object(widget).set_sensitive(True)
@@ -70,7 +70,7 @@ class ToolBar(component.Component):
else:
self.toolbar.hide()
- self.config["show_toolbar"] = visible
+ self.config['show_toolbar'] = visible
def add_toolbutton(self, callback, label=None, image=None, stock=None, tooltip=None):
"""Adds a toolbutton to the toolbar"""
@@ -84,7 +84,7 @@ class ToolBar(component.Component):
if tooltip is not None:
toolbutton.set_tooltip_text(tooltip)
- toolbutton.connect("clicked", callback)
+ toolbutton.connect('clicked', callback)
self.toolbar.insert(toolbutton, -1)
toolbutton.show_all()
@@ -109,33 +109,33 @@ class ToolBar(component.Component):
# Callbacks (Uses the menubar's callback) #
def on_toolbutton_add_clicked(self, data):
- log.debug("on_toolbutton_add_clicked")
- component.get("MenuBar").on_menuitem_addtorrent_activate(data)
+ log.debug('on_toolbutton_add_clicked')
+ component.get('MenuBar').on_menuitem_addtorrent_activate(data)
def on_toolbutton_remove_clicked(self, data):
- log.debug("on_toolbutton_remove_clicked")
- component.get("MenuBar").on_menuitem_remove_activate(data)
+ log.debug('on_toolbutton_remove_clicked')
+ component.get('MenuBar').on_menuitem_remove_activate(data)
def on_toolbutton_pause_clicked(self, data):
- log.debug("on_toolbutton_pause_clicked")
- component.get("MenuBar").on_menuitem_pause_activate(data)
+ log.debug('on_toolbutton_pause_clicked')
+ component.get('MenuBar').on_menuitem_pause_activate(data)
def on_toolbutton_resume_clicked(self, data):
- log.debug("on_toolbutton_resume_clicked")
- component.get("MenuBar").on_menuitem_resume_activate(data)
+ log.debug('on_toolbutton_resume_clicked')
+ component.get('MenuBar').on_menuitem_resume_activate(data)
def on_toolbutton_preferences_clicked(self, data):
- log.debug("on_toolbutton_preferences_clicked")
- component.get("MenuBar").on_menuitem_preferences_activate(data)
+ log.debug('on_toolbutton_preferences_clicked')
+ component.get('MenuBar').on_menuitem_preferences_activate(data)
def on_toolbutton_connectionmanager_clicked(self, data):
- log.debug("on_toolbutton_connectionmanager_clicked")
- component.get("MenuBar").on_menuitem_connectionmanager_activate(data)
+ log.debug('on_toolbutton_connectionmanager_clicked')
+ component.get('MenuBar').on_menuitem_connectionmanager_activate(data)
def on_toolbutton_queue_up_clicked(self, data):
- log.debug("on_toolbutton_queue_up_clicked")
- component.get("MenuBar").on_menuitem_queue_up_activate(data)
+ log.debug('on_toolbutton_queue_up_clicked')
+ component.get('MenuBar').on_menuitem_queue_up_activate(data)
def on_toolbutton_queue_down_clicked(self, data):
- log.debug("on_toolbutton_queue_down_clicked")
- component.get("MenuBar").on_menuitem_queue_down_activate(data)
+ log.debug('on_toolbutton_queue_down_clicked')
+ component.get('MenuBar').on_menuitem_queue_down_activate(data)
diff --git a/deluge/ui/gtkui/torrentdetails.py b/deluge/ui/gtkui/torrentdetails.py
index 0db1023cb..3082659e1 100644
--- a/deluge/ui/gtkui/torrentdetails.py
+++ b/deluge/ui/gtkui/torrentdetails.py
@@ -39,7 +39,7 @@ class Tab(object):
def get_tab_label(self):
parent = self._tab_label.get_parent()
- log.debug("parent: %s", parent)
+ log.debug('parent: %s', parent)
if parent is not None:
parent.remove(self._tab_label)
@@ -53,23 +53,23 @@ class Tab(object):
args = [status[key] for key in widget[2]]
txt = widget[1](*args)
except KeyError as ex:
- log.warn("Unable to get status value: %s", ex)
- txt = ""
+ log.warn('Unable to get status value: %s', ex)
+ txt = ''
return txt
class TorrentDetails(component.Component):
def __init__(self):
- component.Component.__init__(self, "TorrentDetails", interval=2)
- self.window = component.get("MainWindow")
+ component.Component.__init__(self, 'TorrentDetails', interval=2)
+ self.window = component.get('MainWindow')
builder = self.window.get_builder()
- self.notebook = builder.get_object("torrent_info")
+ self.notebook = builder.get_object('torrent_info')
# This is the menu item we'll attach the tabs checklist menu to
- self.menu_tabs = builder.get_object("menu_tabs")
+ self.menu_tabs = builder.get_object('menu_tabs')
- self.notebook.connect("switch-page", self._on_switch_page)
+ self.notebook.connect('switch-page', self._on_switch_page)
# Tabs holds references to the Tab objects by their name
self.tabs = {}
@@ -83,32 +83,32 @@ class TorrentDetails(component.Component):
from deluge.ui.gtkui.trackers_tab import TrackersTab
default_tabs = {
- "Status": StatusTab,
- "Details": DetailsTab,
- "Files": FilesTab,
- "Peers": PeersTab,
- "Options": OptionsTab,
- "Trackers": TrackersTab
+ 'Status': StatusTab,
+ 'Details': DetailsTab,
+ 'Files': FilesTab,
+ 'Peers': PeersTab,
+ 'Options': OptionsTab,
+ 'Trackers': TrackersTab
}
# tab_name, visible
default_order = [
- ("Status", True),
- ("Details", True),
- ("Options", True),
- ("Files", True),
- ("Peers", True),
- ("Trackers", True)
+ ('Status', True),
+ ('Details', True),
+ ('Options', True),
+ ('Files', True),
+ ('Peers', True),
+ ('Trackers', True)
]
self.translate_tabs = {
- "All": _("_All"),
- "Status": _("_Status"),
- "Details": _("_Details"),
- "Files": _("_Files"),
- "Peers": _("_Peers"),
- "Options": _("_Options"),
- "Trackers": _("_Trackers")
+ 'All': _('_All'),
+ 'Status': _('_Status'),
+ 'Details': _('_Details'),
+ 'Files': _('_Files'),
+ 'Peers': _('_Peers'),
+ 'Options': _('_Options'),
+ 'Trackers': _('_Trackers')
}
# Get the state from saved file
@@ -117,7 +117,7 @@ class TorrentDetails(component.Component):
if state:
for item in state:
if not isinstance(item, tuple):
- log.debug("Old tabs.state, using default..")
+ log.debug('Old tabs.state, using default..')
state = None
break
@@ -127,7 +127,7 @@ class TorrentDetails(component.Component):
state = default_order
# We need to rename the tab in the state for backwards compat
- self.state = [(tab_name.replace("Statistics", "Status"), visible) for tab_name, visible in state]
+ self.state = [(tab_name.replace('Statistics', 'Status'), visible) for tab_name, visible in state]
for tab in default_tabs.itervalues():
self.add_tab(tab(), generate_menu=False)
@@ -142,14 +142,14 @@ class TorrentDetails(component.Component):
weights = sorted([(tab.weight, name) for name, tab in self.tabs.iteritems() if tab.is_visible])
- log.debug("weights: %s", weights)
- log.debug("weight of tab: %s", weight)
+ log.debug('weights: %s', weights)
+ log.debug('weight of tab: %s', weight)
position = -1
for w, name in weights:
if w >= weight:
position = self.tabs[name].position
- log.debug("Found pos %d", position)
+ log.debug('Found pos %d', position)
break
return position
@@ -177,14 +177,14 @@ class TorrentDetails(component.Component):
tab.is_visible = True
# add the tab at position guided by the weight
insert_pos = self.tab_insert_position(weight)
- log.debug("Trying to insert tab at %d", insert_pos)
+ log.debug('Trying to insert tab at %d', insert_pos)
pos = self.notebook.insert_page(
tab.get_child_widget(),
tab.get_tab_label(),
insert_pos)
- log.debug("Tab inserted at %d", pos)
+ log.debug('Tab inserted at %d', pos)
tab.position = pos
- if not self.notebook.get_property("visible"):
+ if not self.notebook.get_property('visible'):
# If the notebook isn't visible, show it
self.visible(True)
else:
@@ -218,13 +218,13 @@ class TorrentDetails(component.Component):
def hide_all_tabs(self):
"""Hides all tabs"""
- log.debug("n_pages: %s", self.notebook.get_n_pages())
+ log.debug('n_pages: %s', self.notebook.get_n_pages())
for n in xrange(self.notebook.get_n_pages() - 1, -1, -1):
self.notebook.remove_page(n)
for tab in self.tabs:
self.tabs[tab].is_visible = False
- log.debug("n_pages: %s", self.notebook.get_n_pages())
+ log.debug('n_pages: %s', self.notebook.get_n_pages())
self.generate_menu()
self.visible(False)
@@ -249,12 +249,12 @@ 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(),
+ 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)
- log.debug("position: %s", position)
+ log.debug('position: %s', position)
self.notebook.insert_page(
self.tabs[tab_name].get_child_widget(),
self.tabs[tab_name].get_tab_label(),
@@ -269,8 +269,8 @@ class TorrentDetails(component.Component):
"""Generates the checklist menu for all the tabs and attaches it"""
menu = gtk.Menu()
# Create 'All' menuitem and a separator
- menuitem = gtk.CheckMenuItem(self.translate_tabs["All"], True)
- menuitem.set_name("All")
+ menuitem = gtk.CheckMenuItem(self.translate_tabs['All'], True)
+ menuitem.set_name('All')
all_tabs = True
for key in self.tabs:
@@ -278,7 +278,7 @@ class TorrentDetails(component.Component):
all_tabs = False
break
menuitem.set_active(all_tabs)
- menuitem.connect("toggled", self._on_menuitem_toggled)
+ menuitem.connect('toggled', self._on_menuitem_toggled)
menu.append(menuitem)
@@ -295,7 +295,7 @@ class TorrentDetails(component.Component):
menuitem = gtk.CheckMenuItem(self.translate_tabs[name], True)
menuitem.set_name(name)
menuitem.set_active(self.tabs[name].is_visible)
- menuitem.connect("toggled", self._on_menuitem_toggled)
+ menuitem.connect('toggled', self._on_menuitem_toggled)
menu.append(menuitem)
self.menu_tabs.set_submenu(menu)
@@ -310,7 +310,7 @@ class TorrentDetails(component.Component):
def set_tab_visible(self, tab_name, visible):
"""Sets the tab to visible"""
- log.debug("set_tab_visible name: %s visible: %s", tab_name, visible)
+ log.debug('set_tab_visible name: %s visible: %s', tab_name, visible)
if visible and not self.tabs[tab_name].is_visible:
self.show_tab(tab_name)
elif not visible and self.tabs[tab_name].is_visible:
@@ -343,11 +343,11 @@ class TorrentDetails(component.Component):
self.save_state()
def update(self, page_num=None):
- if len(component.get("TorrentView").get_selected_torrents()) == 0:
+ if len(component.get('TorrentView').get_selected_torrents()) == 0:
# No torrents selected, so just clear
self.clear()
- if self.notebook.get_property("visible"):
+ if self.notebook.get_property('visible'):
if page_num is None:
page_num = self.notebook.get_current_page()
try:
@@ -373,7 +373,7 @@ class TorrentDetails(component.Component):
if name:
self.tabs[name].clear()
except Exception as ex:
- log.debug("Unable to clear torrentdetails: %s", ex)
+ log.debug('Unable to clear torrentdetails: %s', ex)
def _on_switch_page(self, notebook, page, page_num):
self.update(page_num)
@@ -382,7 +382,7 @@ class TorrentDetails(component.Component):
def _on_menuitem_toggled(self, widget):
# Get the tab name
name = widget.get_name()
- if name == "All":
+ if name == 'All':
if widget.get_active():
self.show_all_tabs()
else:
@@ -397,13 +397,13 @@ class TorrentDetails(component.Component):
# Leave tabs we dont know anything about it the state as they
# might come from a plugin
for i, (name, visible) in enumerate(self.state):
- log.debug("Testing name: %s", name)
+ log.debug('Testing name: %s', name)
if name in self.tabs:
self.state[i] = (name, self.tabs[name].is_visible)
- log.debug("Set to %s", self.state[i])
+ log.debug('Set to %s', self.state[i])
state = self.state
- save_pickled_state_file("tabs.state", state)
+ save_pickled_state_file('tabs.state', state)
def load_state(self):
- return load_pickled_state_file("tabs.state")
+ return load_pickled_state_file('tabs.state')
diff --git a/deluge/ui/gtkui/torrentview.py b/deluge/ui/gtkui/torrentview.py
index e2b4def65..2b0afd6a2 100644
--- a/deluge/ui/gtkui/torrentview.py
+++ b/deluge/ui/gtkui/torrentview.py
@@ -101,10 +101,10 @@ class SearchBox(object):
self.visible = False
self.search_pending = self.prefiltered = None
- self.search_box = self.window.main_builder.get_object("search_box")
- self.search_torrents_entry = self.window.main_builder.get_object("search_torrents_entry")
- self.close_search_button = self.window.main_builder.get_object("close_search_button")
- self.match_search_button = self.window.main_builder.get_object("search_torrents_match")
+ self.search_box = self.window.main_builder.get_object('search_box')
+ self.search_torrents_entry = self.window.main_builder.get_object('search_torrents_entry')
+ self.close_search_button = self.window.main_builder.get_object('close_search_button')
+ self.match_search_button = self.window.main_builder.get_object('search_torrents_match')
self.window.connect_signals(self)
def show(self):
@@ -123,8 +123,8 @@ class SearchBox(object):
self.search_pending.cancel()
if self.prefiltered:
- filter_column = self.torrentview.columns["filter"].column_indices[0]
- torrent_id_column = self.torrentview.columns["torrent_id"].column_indices[0]
+ filter_column = self.torrentview.columns['filter'].column_indices[0]
+ torrent_id_column = self.torrentview.columns['torrent_id'].column_indices[0]
for row in self.torrentview.liststore:
torrent_id = row[torrent_id_column]
@@ -135,7 +135,7 @@ class SearchBox(object):
self.prefiltered = None
- self.search_torrents_entry.set_text("")
+ self.search_torrents_entry.set_text('')
if self.torrentview.filter and 'name' in self.torrentview.filter:
self.torrentview.filter.pop('name', None)
self.search_pending = reactor.callLater(0.5, self.torrentview.update)
@@ -160,9 +160,9 @@ class SearchBox(object):
self.prefilter_torrentview()
def prefilter_torrentview(self):
- filter_column = self.torrentview.columns["filter"].column_indices[0]
- torrent_id_column = self.torrentview.columns["torrent_id"].column_indices[0]
- torrent_name_column = self.torrentview.columns[_("Name")].column_indices[1]
+ filter_column = self.torrentview.columns['filter'].column_indices[0]
+ torrent_id_column = self.torrentview.columns['torrent_id'].column_indices[0]
+ torrent_name_column = self.torrentview.columns[_('Name')].column_indices[1]
match_case = self.match_search_button.get_active()
if match_case:
@@ -224,11 +224,11 @@ class SearchBox(object):
class TorrentView(ListView, component.Component):
"""TorrentView handles the listing of torrents."""
def __init__(self):
- component.Component.__init__(self, "TorrentView", interval=2, depend=["SessionProxy"])
- self.window = component.get("MainWindow")
+ component.Component.__init__(self, 'TorrentView', interval=2, depend=['SessionProxy'])
+ self.window = component.get('MainWindow')
# Call the ListView constructor
- ListView.__init__(self, self.window.main_builder.get_object("torrent_view"), "torrentview.state")
- log.debug("TorrentView Init..")
+ ListView.__init__(self, self.window.main_builder.get_object('torrent_view'), 'torrentview.state')
+ log.debug('TorrentView Init..')
# If we have gotten the state yet
self.got_state = False
@@ -240,68 +240,68 @@ class TorrentView(ListView, component.Component):
self.prev_status = {}
# Register the columns menu with the listview so it gets updated accordingly.
- self.register_checklist_menu(self.window.main_builder.get_object("menu_columns"))
+ self.register_checklist_menu(self.window.main_builder.get_object('menu_columns'))
# 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"],
+ 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"],
+ 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,
+ self.add_func_column(_('Size'), funcs.cell_data_size,
[gobject.TYPE_UINT64],
- status_field=["total_wanted"])
- self.add_func_column(_("Downloaded"), funcs.cell_data_size,
+ status_field=['total_wanted'])
+ self.add_func_column(_('Downloaded'), funcs.cell_data_size,
[gobject.TYPE_UINT64],
- status_field=["all_time_download"], default=False)
- self.add_func_column(_("Uploaded"), funcs.cell_data_size,
+ status_field=['all_time_download'], default=False)
+ self.add_func_column(_('Uploaded'), funcs.cell_data_size,
[gobject.TYPE_UINT64],
- status_field=["total_uploaded"], default=False)
- self.add_func_column(_("Remaining"), funcs.cell_data_size, [gobject.TYPE_UINT64],
- status_field=["total_remaining"], default=False)
- self.add_progress_column(_("Progress"),
- status_field=["progress", "state"],
+ status_field=['total_uploaded'], default=False)
+ self.add_func_column(_('Remaining'), funcs.cell_data_size, [gobject.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"],
+ 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"],
+ 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_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.restore_columns_order_from_state()
# Set filter to None for now
@@ -310,21 +310,21 @@ class TorrentView(ListView, component.Component):
# Connect Signals #
# Connect to the 'button-press-event' to know when to bring up the
# torrent menu popup.
- self.treeview.connect("button-press-event", self.on_button_press_event)
+ self.treeview.connect('button-press-event', self.on_button_press_event)
# Connect to the 'key-press-event' to know when the bring up the
# torrent menu popup via keypress.
- self.treeview.connect("key-release-event", self.on_key_press_event)
+ self.treeview.connect('key-release-event', self.on_key_press_event)
# Connect to the 'changed' event of TreeViewSelection to get selection
# changes.
- self.treeview.get_selection().connect("changed", self.on_selection_changed)
+ self.treeview.get_selection().connect('changed', self.on_selection_changed)
- self.treeview.connect("drag-drop", self.on_drag_drop)
- self.treeview.connect("drag_data_received", self.on_drag_data_received)
- self.treeview.connect("key-press-event", self.on_key_press_event)
- self.treeview.connect("columns-changed", self.on_columns_changed_event)
+ self.treeview.connect('drag-drop', self.on_drag_drop)
+ self.treeview.connect('drag_data_received', self.on_drag_data_received)
+ self.treeview.connect('key-press-event', self.on_key_press_event)
+ self.treeview.connect('columns-changed', self.on_columns_changed_event)
self.search_box = SearchBox(self)
- self.permanent_status_keys = ["owner"]
+ self.permanent_status_keys = ['owner']
self.columns_to_update = []
def start(self):
@@ -338,15 +338,15 @@ class TorrentView(ListView, component.Component):
if not listview_column.status_field:
continue
status_fields.extend(listview_column.status_field)
- component.get("SessionProxy").get_torrents_status(
+ component.get('SessionProxy').get_torrents_status(
{}, 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)
- client.register_event_handler("TorrentRemovedEvent", self.on_torrentremoved_event)
- client.register_event_handler("SessionPausedEvent", self.on_sessionpaused_event)
- client.register_event_handler("SessionResumedEvent", self.on_sessionresumed_event)
- client.register_event_handler("TorrentQueueChangedEvent", self.on_torrentqueuechanged_event)
+ client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
+ client.register_event_handler('TorrentAddedEvent', self.on_torrentadded_event)
+ client.register_event_handler('TorrentRemovedEvent', self.on_torrentremoved_event)
+ client.register_event_handler('SessionPausedEvent', self.on_sessionpaused_event)
+ client.register_event_handler('SessionResumedEvent', self.on_sessionresumed_event)
+ client.register_event_handler('TorrentQueueChangedEvent', self.on_torrentqueuechanged_event)
def _on_session_state(self, state):
self.add_rows(state)
@@ -360,12 +360,12 @@ class TorrentView(ListView, component.Component):
def stop(self):
"""Stops the torrentview"""
# We need to clear the liststore
- client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event)
- client.deregister_event_handler("TorrentAddedEvent", self.on_torrentadded_event)
- client.deregister_event_handler("TorrentRemovedEvent", self.on_torrentremoved_event)
- client.deregister_event_handler("SessionPausedEvent", self.on_sessionpaused_event)
- client.deregister_event_handler("SessionResumedEvent", self.on_sessionresumed_event)
- client.deregister_event_handler("TorrentQueueChangedEvent", self.on_torrentqueuechanged_event)
+ client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event)
+ client.deregister_event_handler('TorrentAddedEvent', self.on_torrentadded_event)
+ client.deregister_event_handler('TorrentRemovedEvent', self.on_torrentremoved_event)
+ client.deregister_event_handler('SessionPausedEvent', self.on_sessionpaused_event)
+ client.deregister_event_handler('SessionResumedEvent', self.on_sessionresumed_event)
+ client.deregister_event_handler('TorrentQueueChangedEvent', self.on_torrentqueuechanged_event)
if self.treeview.get_selection():
self.treeview.get_selection().unselect_all()
@@ -383,7 +383,7 @@ class TorrentView(ListView, component.Component):
Saves the state of the torrent view.
"""
if self.window.visible():
- ListView.save_state(self, "torrentview.state")
+ ListView.save_state(self, 'torrentview.state')
def remove_column(self, header):
"""Removes the column with the name 'header' from the torrentview"""
@@ -439,7 +439,7 @@ 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(
+ d = component.get('SessionProxy').get_torrents_status(
self.filter, status_keys).addCallback(self._on_get_torrents_status)
if select_row:
d.addCallback(self.select_first_row)
@@ -472,7 +472,7 @@ class TorrentView(ListView, component.Component):
def update_view(self, load_new_list=False):
"""Update the torrent view model with data we've received."""
- filter_column = self.columns["filter"].column_indices[0]
+ filter_column = self.columns['filter'].column_indices[0]
status = self.status
if not load_new_list:
@@ -491,7 +491,7 @@ class TorrentView(ListView, component.Component):
fields_to_update.append((column_index[i], status_field))
for row in self.liststore:
- torrent_id = row[self.columns["torrent_id"].column_indices[0]]
+ torrent_id = row[self.columns['torrent_id'].column_indices[0]]
# We expect the torrent_id to be in status and prev_status,
# as it will be as long as the list isn't changed by the user
@@ -529,7 +529,7 @@ class TorrentView(ListView, component.Component):
else:
self.treeview.thaw_child_notify()
- component.get("MenuBar").update_menu()
+ component.get('MenuBar').update_menu()
self.prev_status = status
def _on_get_torrents_status(self, status, select_row=False):
@@ -547,9 +547,9 @@ class TorrentView(ListView, component.Component):
def add_rows(self, torrent_ids):
"""Accepts a list of torrent_ids to add to self.liststore"""
- torrent_id_column = self.columns["torrent_id"].column_indices[0]
- dirty_column = self.columns["dirty"].column_indices[0]
- filter_column = self.columns["filter"].column_indices[0]
+ torrent_id_column = self.columns['torrent_id'].column_indices[0]
+ dirty_column = self.columns['dirty'].column_indices[0]
+ filter_column = self.columns['filter'].column_indices[0]
for torrent_id in torrent_ids:
# Insert a new row to the liststore
row = self.liststore.append()
@@ -558,7 +558,7 @@ class TorrentView(ListView, component.Component):
def remove_row(self, torrent_id):
"""Removes a row with torrent_id"""
for row in self.liststore:
- if row[self.columns["torrent_id"].column_indices[0]] == torrent_id:
+ if row[self.columns['torrent_id'].column_indices[0]] == torrent_id:
self.liststore.remove(row.iter)
# Force an update of the torrentview
self.update()
@@ -566,9 +566,9 @@ class TorrentView(ListView, component.Component):
def mark_dirty(self, torrent_id=None):
for row in self.liststore:
- if not torrent_id or row[self.columns["torrent_id"].column_indices[0]] == torrent_id:
+ if not torrent_id or row[self.columns['torrent_id'].column_indices[0]] == torrent_id:
# log.debug("marking %s dirty", torrent_id)
- row[self.columns["dirty"].column_indices[0]] = True
+ row[self.columns['dirty'].column_indices[0]] = True
if torrent_id:
break
@@ -594,16 +594,16 @@ class TorrentView(ListView, component.Component):
try:
row = self.treeview.get_model().get_iter(path)
except Exception as ex:
- log.debug("Unable to get iter from path: %s", ex)
+ log.debug('Unable to get iter from path: %s', ex)
continue
child_row = self.treeview.get_model().convert_iter_to_child_iter(None, row)
child_row = self.treeview.get_model().get_model().convert_iter_to_child_iter(child_row)
if self.liststore.iter_is_valid(child_row):
try:
- value = self.liststore.get_value(child_row, self.columns["torrent_id"].column_indices[0])
+ value = self.liststore.get_value(child_row, self.columns['torrent_id'].column_indices[0])
except Exception as ex:
- log.debug("Unable to get value from row: %s", ex)
+ log.debug('Unable to get value from row: %s', ex)
else:
torrent_ids.append(value)
if len(torrent_ids) == 0:
@@ -626,7 +626,7 @@ class TorrentView(ListView, component.Component):
# Callbacks #
def on_button_press_event(self, widget, event):
"""This is a callback for showing the right-click context menu."""
- log.debug("on_button_press_event")
+ log.debug('on_button_press_event')
# We only care about right-clicks
if event.button == 3:
x, y = event.get_coords()
@@ -636,30 +636,30 @@ class TorrentView(ListView, component.Component):
row = self.model_filter.get_iter(path[0])
if self.get_selected_torrents():
- if (self.model_filter.get_value(row, self.columns["torrent_id"].column_indices[0])
+ if (self.model_filter.get_value(row, self.columns['torrent_id'].column_indices[0])
not in self.get_selected_torrents()):
self.treeview.get_selection().unselect_all()
self.treeview.get_selection().select_iter(row)
else:
self.treeview.get_selection().select_iter(row)
- torrentmenu = component.get("MenuBar").torrentmenu
+ torrentmenu = component.get('MenuBar').torrentmenu
torrentmenu.popup(None, None, None, event.button, event.time)
return True
def on_selection_changed(self, treeselection):
"""This callback is know when the selection has changed."""
- log.debug("on_selection_changed")
- component.get("TorrentDetails").update()
- component.get("MenuBar").update_menu()
+ log.debug('on_selection_changed')
+ component.get('TorrentDetails').update()
+ component.get('MenuBar').update_menu()
def on_drag_drop(self, widget, drag_context, x, y, timestamp):
- widget.stop_emission("drag-drop")
+ widget.stop_emission('drag-drop')
def on_drag_data_received(self, widget, drag_context, x, y, selection_data, info, timestamp):
- widget.stop_emission("drag_data_received")
+ widget.stop_emission('drag_data_received')
def on_columns_changed_event(self, treeview):
- log.debug("Treeview Columns Changed")
+ log.debug('Treeview Columns Changed')
self.save_state()
def on_torrentadded_event(self, torrent_id, from_state):
@@ -672,7 +672,7 @@ class TorrentView(ListView, component.Component):
def on_torrentstatechanged_event(self, torrent_id, state):
# Update the torrents state
for row in self.liststore:
- if torrent_id != row[self.columns["torrent_id"].column_indices[0]]:
+ if torrent_id != row[self.columns['torrent_id'].column_indices[0]]:
continue
for name in self.columns_to_update:
@@ -688,7 +688,7 @@ class TorrentView(ListView, component.Component):
# We have a filter set, let's see if theres anything to hide
# and remove from status
if torrent_id in self.status and self.status[torrent_id]['state'] != state:
- row[self.columns["filter"].column_indices[0]] = False
+ row[self.columns['filter'].column_indices[0]] = False
del self.status[torrent_id]
self.mark_dirty(torrent_id)
@@ -714,7 +714,7 @@ class TorrentView(ListView, component.Component):
return func(event)
def keypress_delete(self, event):
- log.debug("keypress_delete")
+ log.debug('keypress_delete')
torrents = self.get_selected_torrents()
if torrents:
if event.state & gtk.gdk.SHIFT_MASK:
@@ -723,10 +723,10 @@ class TorrentView(ListView, component.Component):
RemoveTorrentDialog(torrents).run()
def keypress_menu(self, event):
- log.debug("keypress_menu")
+ log.debug('keypress_menu')
if not self.get_selected_torrent():
return
- torrentmenu = component.get("MenuBar").torrentmenu
+ torrentmenu = component.get('MenuBar').torrentmenu
torrentmenu.popup(None, None, None, 3, event.time)
return True
diff --git a/deluge/ui/gtkui/torrentview_data_funcs.py b/deluge/ui/gtkui/torrentview_data_funcs.py
index 55d36f644..1727ff392 100644
--- a/deluge/ui/gtkui/torrentview_data_funcs.py
+++ b/deluge/ui/gtkui/torrentview_data_funcs.py
@@ -20,44 +20,44 @@ import deluge.component as component
# Status icons.. Create them from file only once to avoid constantly
# re-creating them.
-icon_downloading = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("downloading16.png"))
-icon_seeding = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("seeding16.png"))
-icon_inactive = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("inactive16.png"))
-icon_alert = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("alert16.png"))
-icon_queued = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("queued16.png"))
-icon_checking = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("checking16.png"))
+icon_downloading = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('downloading16.png'))
+icon_seeding = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('seeding16.png'))
+icon_inactive = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('inactive16.png'))
+icon_alert = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('alert16.png'))
+icon_queued = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('queued16.png'))
+icon_checking = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('checking16.png'))
# Holds the info for which status icon to display based on TORRENT_STATE
ICON_STATE = {
- "Allocating": icon_checking,
- "Checking": icon_checking,
- "Downloading": icon_downloading,
- "Seeding": icon_seeding,
- "Paused": icon_inactive,
- "Error": icon_alert,
- "Queued": icon_queued,
- "Moving": icon_checking
+ 'Allocating': icon_checking,
+ 'Checking': icon_checking,
+ 'Downloading': icon_downloading,
+ 'Seeding': icon_seeding,
+ 'Paused': icon_inactive,
+ 'Error': icon_alert,
+ 'Queued': icon_queued,
+ 'Moving': icon_checking
}
# Cache the key used to calculate the current value set for the specific cell
# renderer. This is much cheaper than fetch the current value and test if
# it's equal.
func_last_value = {
- "cell_data_speed_down": None,
- "cell_data_speed_up": None,
- "cell_data_time": None,
- "cell_data_ratio_seeds_peers": None,
- "cell_data_ratio_ratio": None,
- "cell_data_ratio_avail": None,
- "cell_data_date_added": None,
- "cell_data_date_completed": None,
- "cell_data_date_or_never": None,
- "cell_data_speed_limit_down": None,
- "cell_data_speed_limit_up": None,
- "cell_data_trackericon": None,
- "cell_data_statusicon": None,
- "cell_data_queue": None,
- "cell_data_progress": [None, None],
+ 'cell_data_speed_down': None,
+ 'cell_data_speed_up': None,
+ 'cell_data_time': None,
+ 'cell_data_ratio_seeds_peers': None,
+ 'cell_data_ratio_ratio': None,
+ 'cell_data_ratio_avail': None,
+ 'cell_data_date_added': None,
+ 'cell_data_date_completed': None,
+ 'cell_data_date_or_never': None,
+ 'cell_data_speed_limit_down': None,
+ 'cell_data_speed_limit_up': None,
+ 'cell_data_trackericon': None,
+ 'cell_data_statusicon': None,
+ 'cell_data_queue': None,
+ 'cell_data_progress': [None, None],
}
@@ -66,17 +66,17 @@ def cell_data_statusicon(column, cell, model, row, data):
try:
state = model.get_value(row, data)
- if func_last_value["cell_data_statusicon"] == state:
+ if func_last_value['cell_data_statusicon'] == state:
return
- func_last_value["cell_data_statusicon"] = state
+ func_last_value['cell_data_statusicon'] = state
icon = ICON_STATE[state]
# Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
original_filters = warnings.filters[:]
- warnings.simplefilter("ignore")
+ warnings.simplefilter('ignore')
try:
- cell.set_property("pixbuf", icon)
+ cell.set_property('pixbuf', icon)
finally:
warnings.filters = original_filters
@@ -106,58 +106,58 @@ def set_icon(icon, cell):
# Suppress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- cell.set_property("pixbuf", pixbuf)
+ warnings.simplefilter('ignore')
+ cell.set_property('pixbuf', pixbuf)
def cell_data_trackericon(column, cell, model, row, data):
host = model[row][data]
- if func_last_value["cell_data_trackericon"] == host:
+ if func_last_value['cell_data_trackericon'] == host:
return
if host:
- if not component.get("TrackerIcons").has(host):
+ if not component.get('TrackerIcons').has(host):
# Set blank icon while waiting for the icon to be loaded
set_icon(None, cell)
- component.get("TrackerIcons").fetch(host)
- func_last_value["cell_data_trackericon"] = None
+ component.get('TrackerIcons').fetch(host)
+ func_last_value['cell_data_trackericon'] = None
else:
- set_icon(component.get("TrackerIcons").get(host), cell)
+ set_icon(component.get('TrackerIcons').get(host), cell)
# Only set the last value when we have found the icon
- func_last_value["cell_data_trackericon"] = host
+ func_last_value['cell_data_trackericon'] = host
else:
set_icon(None, cell)
- func_last_value["cell_data_trackericon"] = None
+ func_last_value['cell_data_trackericon'] = None
def cell_data_progress(column, cell, model, row, data):
"""Display progress bar with text"""
(value, state_str) = model.get(row, *data)
- if func_last_value["cell_data_progress"][0] != value:
- func_last_value["cell_data_progress"][0] = value
- cell.set_property("value", value)
+ if func_last_value['cell_data_progress'][0] != value:
+ func_last_value['cell_data_progress'][0] = value
+ cell.set_property('value', value)
# Marked for translate states text are in filtertreeview
textstr = _(state_str)
- if state_str not in ("Error", "Seeding") and value < 100:
- textstr = "%s %i%%" % (textstr, value)
+ if state_str not in ('Error', 'Seeding') and value < 100:
+ textstr = '%s %i%%' % (textstr, value)
- if func_last_value["cell_data_progress"][1] != textstr:
- func_last_value["cell_data_progress"][1] = textstr
- cell.set_property("text", textstr)
+ if func_last_value['cell_data_progress'][1] != textstr:
+ func_last_value['cell_data_progress'][1] = textstr
+ cell.set_property('text', textstr)
def cell_data_queue(column, cell, model, row, data):
value = model.get_value(row, data)
- if func_last_value["cell_data_queue"] == value:
+ if func_last_value['cell_data_queue'] == value:
return
- func_last_value["cell_data_queue"] = value
+ func_last_value['cell_data_queue'] = value
if value < 0:
- cell.set_property("text", "")
+ cell.set_property('text', '')
else:
- cell.set_property("text", str(value + 1))
+ cell.set_property('text', str(value + 1))
def cell_data_speed(cell, model, row, data, cache_key):
@@ -165,7 +165,7 @@ def cell_data_speed(cell, model, row, data, cache_key):
try:
speed = model.get_value(row, data)
except AttributeError:
- print("AttributeError")
+ print('AttributeError')
import traceback
traceback.print_exc()
if func_last_value[cache_key] == speed:
@@ -174,19 +174,19 @@ def cell_data_speed(cell, model, row, data, cache_key):
if speed > 0:
speed_str = common.fspeed(speed, shortform=True)
- cell.set_property("markup", "{0} <small>{1}</small>".format(*tuple(speed_str.split())))
+ cell.set_property('markup', '{0} <small>{1}</small>'.format(*tuple(speed_str.split())))
else:
- cell.set_property("text", "")
+ cell.set_property('text', '')
def cell_data_speed_down(column, cell, model, row, data):
"""Display value as a speed, eg. 2 KiB/s"""
- cell_data_speed(cell, model, row, data, "cell_data_speed_down")
+ cell_data_speed(cell, model, row, data, 'cell_data_speed_down')
def cell_data_speed_up(column, cell, model, row, data):
"""Display value as a speed, eg. 2 KiB/s"""
- cell_data_speed(cell, model, row, data, "cell_data_speed_up")
+ cell_data_speed(cell, model, row, data, 'cell_data_speed_up')
def cell_data_speed_limit(cell, model, row, data, cache_key):
@@ -199,17 +199,17 @@ def cell_data_speed_limit(cell, model, row, data, cache_key):
if speed > 0:
speed_str = common.fspeed(speed * 1024, shortform=True)
- cell.set_property("markup", "{0} <small>{1}</small>".format(*tuple(speed_str.split())))
+ cell.set_property('markup', '{0} <small>{1}</small>'.format(*tuple(speed_str.split())))
else:
- cell.set_property("text", "")
+ cell.set_property('text', '')
def cell_data_speed_limit_down(column, cell, model, row, data):
- cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_down")
+ cell_data_speed_limit(cell, model, row, data, 'cell_data_speed_limit_down')
def cell_data_speed_limit_up(column, cell, model, row, data):
- cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_up")
+ cell_data_speed_limit(cell, model, row, data, 'cell_data_speed_limit_up')
def cell_data_size(column, cell, model, row, data):
@@ -231,12 +231,12 @@ def cell_data_peer(column, cell, model, row, data):
def cell_data_time(column, cell, model, row, data):
"""Display value as time, eg 1m10s"""
time = model.get_value(row, data)
- if func_last_value["cell_data_time"] == time:
+ if func_last_value['cell_data_time'] == time:
return
- func_last_value["cell_data_time"] = time
+ func_last_value['cell_data_time'] = time
if time <= 0:
- time_str = ""
+ time_str = ''
else:
time_str = common.ftime(time)
cell.set_property('text', time_str)
@@ -249,19 +249,19 @@ def cell_data_ratio(cell, model, row, data, cache_key):
if func_last_value[cache_key] == ratio:
return
func_last_value[cache_key] = ratio
- cell.set_property("text", "∞" if ratio < 0 else ("%.1f" % ratio).rstrip("0").rstrip("."))
+ cell.set_property('text', '∞' if ratio < 0 else ('%.1f' % ratio).rstrip('0').rstrip('.'))
def cell_data_ratio_seeds_peers(column, cell, model, row, data):
- cell_data_ratio(cell, model, row, data, "cell_data_ratio_seeds_peers")
+ cell_data_ratio(cell, model, row, data, 'cell_data_ratio_seeds_peers')
def cell_data_ratio_ratio(column, cell, model, row, data):
- cell_data_ratio(cell, model, row, data, "cell_data_ratio_ratio")
+ cell_data_ratio(cell, model, row, data, 'cell_data_ratio_ratio')
def cell_data_ratio_avail(column, cell, model, row, data):
- cell_data_ratio(cell, model, row, data, "cell_data_ratio_avail")
+ cell_data_ratio(cell, model, row, data, 'cell_data_ratio_avail')
def cell_data_date(column, cell, model, row, data, key):
@@ -272,20 +272,20 @@ def cell_data_date(column, cell, model, row, data, key):
return
func_last_value[key] = date
- date_str = common.fdate(date, date_only=True) if date > 0 else ""
+ date_str = common.fdate(date, date_only=True) if date > 0 else ''
cell.set_property('text', date_str)
-cell_data_date_added = partial(cell_data_date, key="cell_data_date_added")
-cell_data_date_completed = partial(cell_data_date, key="cell_data_date_completed")
+cell_data_date_added = partial(cell_data_date, key='cell_data_date_added')
+cell_data_date_completed = partial(cell_data_date, key='cell_data_date_completed')
def cell_data_date_or_never(column, cell, model, row, data):
"""Display value as date, eg 05/05/08 or Never"""
value = model.get_value(row, data)
- if func_last_value["cell_data_date_or_never"] == value:
+ if func_last_value['cell_data_date_or_never'] == value:
return
- func_last_value["cell_data_date_or_never"] = value
+ func_last_value['cell_data_date_or_never'] = value
- date_str = common.fdate(value, date_only=True) if value > 0 else _("Never")
+ date_str = common.fdate(value, date_only=True) if value > 0 else _('Never')
cell.set_property('text', date_str)
diff --git a/deluge/ui/gtkui/trackers_tab.py b/deluge/ui/gtkui/trackers_tab.py
index 36b4b9732..1b4ecb60c 100644
--- a/deluge/ui/gtkui/trackers_tab.py
+++ b/deluge/ui/gtkui/trackers_tab.py
@@ -22,29 +22,29 @@ class TrackersTab(Tab):
Tab.__init__(self)
# Get the labels we need to update.
# widget name, modifier function, status keys
- builder = component.get("MainWindow").get_builder()
+ builder = component.get('MainWindow').get_builder()
- self._name = "Trackers"
- self._child_widget = builder.get_object("trackers_tab")
- self._tab_label = builder.get_object("trackers_tab_label")
+ self._name = 'Trackers'
+ self._child_widget = builder.get_object('trackers_tab')
+ self._tab_label = builder.get_object('trackers_tab_label')
self.label_widgets = [
- (builder.get_object("summary_next_announce"), ftime, ("next_announce",)),
- (builder.get_object("summary_tracker"), None, ("tracker_host",)),
- (builder.get_object("summary_tracker_status"), ftranslate, ("tracker_status",)),
- (builder.get_object("summary_tracker_total"), fcount, ("trackers",)),
- (builder.get_object("summary_private"), fyes_no, ("private",)),
+ (builder.get_object('summary_next_announce'), ftime, ('next_announce',)),
+ (builder.get_object('summary_tracker'), None, ('tracker_host',)),
+ (builder.get_object('summary_tracker_status'), ftranslate, ('tracker_status',)),
+ (builder.get_object('summary_tracker_total'), fcount, ('trackers',)),
+ (builder.get_object('summary_private'), fyes_no, ('private',)),
]
self.status_keys = [status for widget in self.label_widgets for status in widget[2]]
- component.get("MainWindow").connect_signals({
- "on_button_edit_trackers_clicked": self._on_button_edit_trackers_clicked,
+ component.get('MainWindow').connect_signals({
+ 'on_button_edit_trackers_clicked': self._on_button_edit_trackers_clicked,
})
def update(self):
# Get the first selected torrent
- selected = component.get("TorrentView").get_selected_torrents()
+ selected = component.get('TorrentView').get_selected_torrents()
# Only use the first torrent in the list or return if None selected
if selected:
@@ -53,7 +53,7 @@ class TrackersTab(Tab):
self.clear()
return
- session = component.get("SessionProxy")
+ session = component.get('SessionProxy')
session.get_torrent_status(selected, self.status_keys).addCallback(self._on_get_torrent_status)
def _on_get_torrent_status(self, status):
@@ -69,11 +69,11 @@ class TrackersTab(Tab):
def clear(self):
for widget in self.label_widgets:
- widget[0].set_text("")
+ widget[0].set_text('')
def _on_button_edit_trackers_clicked(self, button):
- torrent_id = component.get("TorrentView").get_selected_torrent()
+ torrent_id = component.get('TorrentView').get_selected_torrent()
if torrent_id:
from deluge.ui.gtkui.edittrackersdialog import EditTrackersDialog
- dialog = EditTrackersDialog(torrent_id, component.get("MainWindow").window)
+ dialog = EditTrackersDialog(torrent_id, component.get('MainWindow').window)
dialog.run()
diff --git a/deluge/ui/sessionproxy.py b/deluge/ui/sessionproxy.py
index 882de9c19..86606caae 100644
--- a/deluge/ui/sessionproxy.py
+++ b/deluge/ui/sessionproxy.py
@@ -27,8 +27,8 @@ class SessionProxy(component.Component):
"""
def __init__(self):
- log.debug("SessionProxy init..")
- component.Component.__init__(self, "SessionProxy", interval=5)
+ log.debug('SessionProxy init..')
+ component.Component.__init__(self, 'SessionProxy', interval=5)
# Set the cache time in seconds
# This is how long data will be valid before re-fetching from the core
@@ -41,9 +41,9 @@ class SessionProxy(component.Component):
self.cache_times = {}
def start(self):
- client.register_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed)
- client.register_event_handler("TorrentRemovedEvent", self.on_torrent_removed)
- client.register_event_handler("TorrentAddedEvent", self.on_torrent_added)
+ client.register_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed)
+ client.register_event_handler('TorrentRemovedEvent', self.on_torrent_removed)
+ client.register_event_handler('TorrentAddedEvent', self.on_torrent_added)
def on_get_session_state(torrent_ids):
for torrent_id in torrent_ids:
@@ -55,9 +55,9 @@ class SessionProxy(component.Component):
return client.core.get_session_state().addCallback(on_get_session_state)
def stop(self):
- client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed)
- client.deregister_event_handler("TorrentRemovedEvent", self.on_torrent_removed)
- client.deregister_event_handler("TorrentAddedEvent", self.on_torrent_added)
+ client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed)
+ client.deregister_event_handler('TorrentRemovedEvent', self.on_torrent_removed)
+ client.deregister_event_handler('TorrentAddedEvent', self.on_torrent_added)
self.torrents = {}
def create_status_dict(self, torrent_ids, keys):
@@ -216,21 +216,21 @@ class SessionProxy(component.Component):
# We get a list of any torrent_ids with expired status dicts
to_fetch = find_torrents_to_fetch(self.torrents.keys())
if to_fetch:
- d = client.core.get_torrents_status({"id": to_fetch}, keys, True)
+ d = client.core.get_torrents_status({'id': to_fetch}, keys, True)
return d.addCallback(on_status, self.torrents.keys(), keys)
# Don't need to fetch anything
return maybeDeferred(self.create_status_dict, self.torrents.keys(), keys)
- if len(filter_dict) == 1 and "id" in filter_dict:
+ if len(filter_dict) == 1 and 'id' in filter_dict:
# At this point we should have a filter with just "id" in it
- to_fetch = find_torrents_to_fetch(filter_dict["id"])
+ to_fetch = find_torrents_to_fetch(filter_dict['id'])
if to_fetch:
- d = client.core.get_torrents_status({"id": to_fetch}, keys, True)
- return d.addCallback(on_status, filter_dict["id"], keys)
+ d = client.core.get_torrents_status({'id': to_fetch}, keys, True)
+ return d.addCallback(on_status, filter_dict['id'], keys)
else:
# Don't need to fetch anything, so just return data from the cache
- return maybeDeferred(self.create_status_dict, filter_dict["id"], keys)
+ return maybeDeferred(self.create_status_dict, filter_dict['id'], keys)
else:
# This is a keyworded filter so lets just pass it onto the core
# XXX: Add more caching here.
@@ -239,7 +239,7 @@ class SessionProxy(component.Component):
def on_torrent_state_changed(self, torrent_id, state):
if torrent_id in self.torrents:
- self.torrents[torrent_id][1].setdefault("state", state)
+ self.torrents[torrent_id][1].setdefault('state', state)
self.cache_times.setdefault(torrent_id, {}).update(state=time())
def on_torrent_added(self, torrent_id, from_state):
diff --git a/deluge/ui/tracker_icons.py b/deluge/ui/tracker_icons.py
index a6ff56bf8..aff27f25c 100644
--- a/deluge/ui/tracker_icons.py
+++ b/deluge/ui/tracker_icons.py
@@ -45,7 +45,7 @@ class TrackerIcon(object):
:type filename: string
"""
self.filename = os.path.abspath(filename)
- self.mimetype = extension_to_mimetype(self.filename.rpartition(".")[2])
+ self.mimetype = extension_to_mimetype(self.filename.rpartition('.')[2])
self.data = None
self.icon_cache = None
@@ -79,7 +79,7 @@ class TrackerIcon(object):
:rtype: string
"""
if not self.data:
- with open(self.filename, "rb") as _file:
+ with open(self.filename, 'rb') as _file:
self.data = _file.read()
return self.data
@@ -124,9 +124,9 @@ class TrackerIcons(Component):
can be fetched
:type no_icon: string
"""
- Component.__init__(self, "TrackerIcons")
+ Component.__init__(self, 'TrackerIcons')
if not icon_dir:
- icon_dir = get_config_dir("icons")
+ icon_dir = get_config_dir('icons')
self.dir = icon_dir
if not os.path.isdir(self.dir):
os.makedirs(self.dir)
@@ -138,12 +138,12 @@ class TrackerIcons(Component):
try:
self.icons[host] = TrackerIcon(os.path.join(self.dir, icon))
except KeyError:
- log.warning("invalid icon %s", icon)
+ log.warning('invalid icon %s', icon)
if no_icon:
self.icons[None] = TrackerIcon(no_icon)
else:
self.icons[None] = None
- self.icons[""] = self.icons[None]
+ self.icons[''] = self.icons[None]
self.pending = {}
self.redirects = {}
@@ -227,7 +227,7 @@ class TrackerIcons(Component):
"""
if not url:
url = self.host_to_url(host)
- log.debug("Downloading %s %s", host, url)
+ log.debug('Downloading %s %s', host, url)
tmp_fd, tmp_file = mkstemp(prefix='deluge_ticon.')
os.close(tmp_fd)
return download_file(url, tmp_file, force_filename=True, handle_redirects=False)
@@ -241,7 +241,7 @@ class TrackerIcons(Component):
:returns: the page that finished downloading
:rtype: string
"""
- log.debug("Finished downloading %s", page)
+ log.debug('Finished downloading %s', page)
return page
def on_download_page_fail(self, f, host):
@@ -257,11 +257,11 @@ class TrackerIcons(Component):
:rtype: Deferred or Failure
"""
error_msg = f.getErrorMessage()
- log.debug("Error downloading page: %s", error_msg)
+ log.debug('Error downloading page: %s', error_msg)
d = f
if f.check(PageRedirect):
# Handle redirect errors
- location = urljoin(self.host_to_url(host), error_msg.split(" to ")[1])
+ 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,
@@ -279,7 +279,7 @@ class TrackerIcons(Component):
:returns: a Deferred which callbacks a list of available favicons (url, type)
:rtype: Deferred
"""
- with open(page, "r") as _file:
+ with open(page, 'r') as _file:
parser = FaviconParser()
for line in _file:
parser.feed(line)
@@ -304,10 +304,10 @@ class TrackerIcons(Component):
:returns: the icons that were extracted from the page
:rtype: list
"""
- log.debug("Parse Complete, got icons for %s: %s", host, icons)
+ log.debug('Parse Complete, got icons for %s: %s', host, icons)
url = self.host_to_url(host)
icons = [(urljoin(url, icon), mimetype) for icon, mimetype in icons]
- log.debug("Icon urls from %s: %s", host, icons)
+ log.debug('Icon urls from %s: %s', host, icons)
return icons
def on_parse_fail(self, f):
@@ -320,7 +320,7 @@ class TrackerIcons(Component):
else the original failure
:rtype: Deferred or Failure
"""
- log.debug("Error parsing page: %s", f.getErrorMessage())
+ log.debug('Error parsing page: %s', f.getErrorMessage())
return f
def download_icon(self, icons, host):
@@ -335,7 +335,7 @@ class TrackerIcons(Component):
:rtype: Deferred
"""
if len(icons) == 0:
- raise NoIconsError("empty icons list")
+ 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)
@@ -364,7 +364,7 @@ class TrackerIcons(Component):
raise InvalidIconError(ex)
else:
if os.stat(icon_name).st_size == 0:
- raise InvalidIconError("empty icon")
+ raise InvalidIconError('empty icon')
return icon_name
@@ -379,7 +379,7 @@ class TrackerIcons(Component):
:returns: the icon that finished downloading
:rtype: TrackerIcon
"""
- log.debug("Successfully downloaded from %s: %s", host, icon_name)
+ log.debug('Successfully downloaded from %s: %s', host, icon_name)
icon = TrackerIcon(icon_name)
return icon
@@ -400,12 +400,12 @@ class TrackerIcons(Component):
if not icons:
icons = []
error_msg = f.getErrorMessage()
- log.debug("Error downloading icon from %s: %s", host, error_msg)
+ log.debug('Error downloading icon from %s: %s', host, error_msg)
d = f
if f.check(PageRedirect):
# Handle redirect errors
- 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)
+ 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,))
@@ -413,8 +413,8 @@ class TrackerIcons(Component):
d = self.download_icon(icons, host)
elif f.check(NoIconsError, HTMLParseError):
# 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 = 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:
@@ -438,7 +438,7 @@ class TrackerIcons(Component):
filename = icon.get_filename()
with Image.open(filename) as img:
if img.size > (16, 16):
- new_filename = filename.rpartition(".")[0] + ".png"
+ new_filename = filename.rpartition('.')[0] + '.png'
img = img.resize((16, 16), Image.ANTIALIAS)
img.save(new_filename)
if new_filename != filename:
@@ -475,7 +475,7 @@ class TrackerIcons(Component):
"""
if host in self.redirects:
host = self.redirects[host]
- return "http://%s/" % host
+ return 'http://%s/' % host
# ------- HELPER CLASSES ------
@@ -490,17 +490,17 @@ class FaviconParser(HTMLParser):
HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
- if tag == "link" and ("rel", "icon") in attrs or ("rel", "shortcut icon") in attrs:
+ if tag == 'link' and ('rel', 'icon') in attrs or ('rel', 'shortcut icon') in attrs:
href = None
icon_type = None
for attr, value in attrs:
- if attr == "href":
+ if attr == 'href':
href = value
- elif attr == "type":
+ elif attr == 'type':
icon_type = value
if href:
try:
- mimetype = extension_to_mimetype(href.rpartition(".")[2])
+ mimetype = extension_to_mimetype(href.rpartition('.')[2])
except KeyError:
pass
else:
@@ -509,7 +509,7 @@ class FaviconParser(HTMLParser):
self.icons.append((href, icon_type))
def handle_endtag(self, tag):
- if tag == "head":
+ if tag == 'head':
self.left_head = True
def get_icons(self):
@@ -548,7 +548,7 @@ def host_to_icon_name(host, mimetype):
:rtype: string
"""
- return host + "." + mimetype_to_extension(mimetype)
+ return host + '.' + mimetype_to_extension(mimetype)
def icon_name_to_host(icon):
@@ -560,19 +560,19 @@ def icon_name_to_host(icon):
:returns: the host name
:rtype: string
"""
- return icon.rpartition(".")[0]
+ return icon.rpartition('.')[0]
MIME_MAP = {
- "image/gif": "gif",
- "image/jpeg": "jpg",
- "image/png": "png",
- "image/vnd.microsoft.icon": "ico",
- "image/x-icon": "ico",
- "gif": "image/gif",
- "jpg": "image/jpeg",
- "jpeg": "image/jpeg",
- "png": "image/png",
- "ico": "image/vnd.microsoft.icon",
+ 'image/gif': 'gif',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/vnd.microsoft.icon': 'ico',
+ 'image/x-icon': 'ico',
+ 'gif': 'image/gif',
+ 'jpg': 'image/jpeg',
+ 'jpeg': 'image/jpeg',
+ 'png': 'image/png',
+ 'ico': 'image/vnd.microsoft.icon',
}
diff --git a/deluge/ui/ui.py b/deluge/ui/ui.py
index 13334253e..cb7076098 100644
--- a/deluge/ui/ui.py
+++ b/deluge/ui/ui.py
@@ -33,13 +33,13 @@ class UI(object):
def __init__(self, name, **kwargs):
self.__name = name
- self.ui_args = kwargs.pop("ui_args", None)
+ self.ui_args = kwargs.pop('ui_args', None)
lang.setup_translations()
self.__parser = BaseArgParser(**kwargs)
def parse_args(self, parser, args=None):
options = parser.parse_args(args)
- if not hasattr(options, "remaining"):
+ if not hasattr(options, 'remaining'):
options.remaining = []
return options
@@ -61,8 +61,8 @@ class UI(object):
parser = self.parser
self.__options = self.parse_args(parser, args)
- setproctitle("deluge-%s" % self.__name)
+ setproctitle('deluge-%s' % self.__name)
- log.info("Deluge ui %s", deluge.common.get_version())
- log.debug("options: %s", self.__options)
- log.info("Starting %s ui..", self.__name)
+ log.info('Deluge ui %s', deluge.common.get_version())
+ log.debug('options: %s', self.__options)
+ log.info('Starting %s ui..', self.__name)
diff --git a/deluge/ui/ui_entry.py b/deluge/ui/ui_entry.py
index f99989662..6425e28b0 100644
--- a/deluge/ui/ui_entry.py
+++ b/deluge/ui/ui_entry.py
@@ -26,10 +26,10 @@ from deluge.ui.baseargparser import BaseArgParser
from deluge.ui.util import lang
DEFAULT_PREFS = {
- "default_ui": "gtk"
+ 'default_ui': 'gtk'
}
-AMBIGUOUS_CMD_ARGS = ("-h", "--help", "-v", "-V", "--version")
+AMBIGUOUS_CMD_ARGS = ('-h', '--help', '-v', '-V', '--version')
def start_ui():
@@ -38,14 +38,14 @@ def start_ui():
# Get the registered UI entry points
ui_entrypoints = dict([(entrypoint.name, entrypoint.load())
- for entrypoint in pkg_resources.iter_entry_points("deluge.ui")])
+ for entrypoint in pkg_resources.iter_entry_points('deluge.ui')])
ui_titles = sorted(ui_entrypoints.keys())
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 = _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'))
return _parser
# Setup parser with Common Options and add UI Options group.
@@ -54,17 +54,17 @@ def start_ui():
# Parse and handle common/process group options
options = parser.parse_known_ui_args(sys.argv, withhold=AMBIGUOUS_CMD_ARGS)
- config = deluge.configmanager.ConfigManager("ui.conf", DEFAULT_PREFS)
+ config = deluge.configmanager.ConfigManager('ui.conf', DEFAULT_PREFS)
log = logging.getLogger(__name__)
- log.info("Deluge ui %s", deluge.common.get_version())
+ log.info('Deluge ui %s', deluge.common.get_version())
if options.default_ui:
- config["default_ui"] = options.default_ui
+ config['default_ui'] = options.default_ui
config.save()
- log.info("The default UI has been changed to %s", options.default_ui)
+ log.info('The default UI has been changed to %s', options.default_ui)
sys.exit(0)
- default_ui = config["default_ui"]
+ default_ui = config['default_ui']
config.save() # Save in case config didn't already exist.
del config
@@ -74,16 +74,16 @@ 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.add_argument("ui_args", nargs=argparse.REMAINDER)
+ 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()
- prefix = "*" if ui == default_ui else " "
- subactions[-1].dest = "%s %s" % (prefix, ui)
+ prefix = '*' if ui == default_ui else ' '
+ subactions[-1].dest = '%s %s' % (prefix, ui)
# Insert a default UI subcommand unless one of the ambiguous_args are specified
parser.set_default_subparser(default_ui, abort_opts=AMBIGUOUS_CMD_ARGS)
@@ -97,7 +97,7 @@ def start_ui():
sys.argv.remove(selected_ui)
try:
- ui = ui_entrypoints[selected_ui](prog="%s %s" % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args)
+ 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)
@@ -111,7 +111,7 @@ def start_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)
+ log.error('Encountered an error launching the request UI: %s', selected_ui)
sys.exit(1)
else:
ui.start()
diff --git a/deluge/ui/util/lang.py b/deluge/ui/util/lang.py
index 307293c96..f37e5bf4e 100644
--- a/deluge/ui/util/lang.py
+++ b/deluge/ui/util/lang.py
@@ -26,13 +26,13 @@ def set_dummy_trans(warn_msg=None):
if warn_msg:
log.warn("'%s' has been marked for translation, but translation is unavailable.", txt[0])
return txt[0]
- __builtin__.__dict__["_"] = _func
- __builtin__.__dict__["_n"] = _func
+ __builtin__.__dict__['_'] = _func
+ __builtin__.__dict__['_n'] = _func
def get_translations_path():
"""Get the absolute path to the directory containing translation files"""
- return deluge.common.resource_filename("deluge", "i18n")
+ return deluge.common.resource_filename('deluge', 'i18n')
def get_languages():
@@ -49,7 +49,7 @@ def get_languages():
return lang
for i, lang_code in enumerate(lang_dirs):
- name = "%s (Language name missing)" % lang_code
+ name = '%s (Language name missing)' % lang_code
if lang_code in languages.LANGUAGES:
name = languages.LANGUAGES[lang_code]
lang.append([lang_code, name])
@@ -75,28 +75,28 @@ def set_language(lang):
translations_path = get_translations_path()
try:
- ro = gettext.translation("deluge", localedir=translations_path, languages=[lang])
+ ro = gettext.translation('deluge', localedir=translations_path, languages=[lang])
ro.install()
except IOError as ex:
- log.warn("IOError when loading translations: %s", ex)
+ log.warn('IOError when loading translations: %s', ex)
# Initialize gettext
def setup_translations(setup_gettext=True, setup_pygtk=False):
translations_path = get_translations_path()
- domain = "deluge"
- log.info("Setting up translations from %s", translations_path)
+ domain = 'deluge'
+ log.info('Setting up translations from %s', translations_path)
if setup_pygtk:
try:
- log.info("Setting up GTK translations from %s", translations_path)
+ log.info('Setting up GTK translations from %s', translations_path)
if deluge.common.windows_check():
import ctypes
libintl = ctypes.cdll.intl
libintl.bindtextdomain(domain, translations_path.encode(sys.getfilesystemencoding()))
libintl.textdomain(domain)
- libintl.bind_textdomain_codeset(domain, "UTF-8")
+ libintl.bind_textdomain_codeset(domain, 'UTF-8')
libintl.gettext.restype = ctypes.c_char_p
# Use glade for plugins that still uses it
@@ -105,13 +105,13 @@ def setup_translations(setup_gettext=True, setup_pygtk=False):
gtk.glade.bindtextdomain(domain, translations_path)
gtk.glade.textdomain(domain)
except Exception as ex:
- log.error("Unable to initialize glade translation!")
+ log.error('Unable to initialize glade translation!')
log.exception(ex)
if setup_gettext:
try:
- if hasattr(locale, "bindtextdomain"):
+ if hasattr(locale, 'bindtextdomain'):
locale.bindtextdomain(domain, translations_path)
- if hasattr(locale, "textdomain"):
+ if hasattr(locale, 'textdomain'):
locale.textdomain(domain)
gettext.bindtextdomain(domain, translations_path)
@@ -119,9 +119,9 @@ def setup_translations(setup_gettext=True, setup_pygtk=False):
gettext.textdomain(domain)
gettext.install(domain, translations_path, unicode=True)
import __builtin__
- __builtin__.__dict__["_n"] = gettext.ngettext
+ __builtin__.__dict__['_n'] = gettext.ngettext
except Exception as ex:
- log.error("Unable to initialize gettext/locale!")
+ log.error('Unable to initialize gettext/locale!')
log.exception(ex)
set_dummy_trans()
diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py
index 5ff450bf3..cc4350752 100644
--- a/deluge/ui/web/auth.py
+++ b/deluge/ui/web/auth.py
@@ -79,7 +79,7 @@ class Auth(JSONComponent):
"""
def __init__(self, config):
- super(Auth, self).__init__("Auth")
+ super(Auth, self).__init__('Auth')
self.worker = LoopingCall(self._clean_sessions)
self.config = config
@@ -90,18 +90,18 @@ class Auth(JSONComponent):
self.worker.stop()
def _clean_sessions(self):
- session_ids = self.config["sessions"].keys()
+ session_ids = self.config['sessions'].keys()
now = time.gmtime()
for session_id in session_ids:
- session = self.config["sessions"][session_id]
+ session = self.config['sessions'][session_id]
- if "expires" not in session:
- del self.config["sessions"][session_id]
+ if 'expires' not in session:
+ del self.config['sessions'][session_id]
continue
- if time.gmtime(session["expires"]) < now:
- del self.config["sessions"][session_id]
+ if time.gmtime(session['expires']) < now:
+ del self.config['sessions'][session_id]
continue
def _create_session(self, request, login='admin'):
@@ -116,75 +116,75 @@ class Auth(JSONComponent):
m.update(os.urandom(32))
session_id = m.hexdigest()
- expires, expires_str = make_expires(self.config["session_timeout"])
+ expires, expires_str = make_expires(self.config['session_timeout'])
checksum = str(make_checksum(session_id))
request.addCookie('_session_id', session_id + checksum,
- path=request.base + "json", expires=expires_str)
+ path=request.base + 'json', expires=expires_str)
- log.debug("Creating session for %s", login)
+ log.debug('Creating session for %s', login)
- if isinstance(self.config["sessions"], list):
- self.config["sessions"] = {}
+ if isinstance(self.config['sessions'], list):
+ self.config['sessions'] = {}
- self.config["sessions"][session_id] = {
- "login": login,
- "level": AUTH_LEVEL_ADMIN,
- "expires": expires
+ self.config['sessions'][session_id] = {
+ 'login': login,
+ 'level': AUTH_LEVEL_ADMIN,
+ 'expires': expires
}
return True
def check_password(self, password):
config = self.config
- if "pwd_md5" in config.config:
+ if 'pwd_md5' in config.config:
# We are using the 1.2-dev auth method
- log.debug("Received a password via the 1.2-dev auth method")
+ log.debug('Received a password via the 1.2-dev auth method')
m = hashlib.md5()
- m.update(config["pwd_salt"])
+ m.update(config['pwd_salt'])
m.update(utf8_encoded(password))
if m.hexdigest() == config['pwd_md5']:
# We want to move the password over to sha1 and remove
# the old passwords from the config file.
self._change_password(password)
- del config.config["pwd_md5"]
+ del config.config['pwd_md5']
# Remove the older password if there is now.
- if "old_pwd_md5" in config.config:
- del config.config["old_pwd_salt"]
- del config.config["old_pwd_md5"]
+ if 'old_pwd_md5' in config.config:
+ del config.config['old_pwd_salt']
+ del config.config['old_pwd_md5']
return True
- elif "old_pwd_md5" in config.config:
+ elif 'old_pwd_md5' in config.config:
# We are using the 1.1 webui auth method
- log.debug("Received a password via the 1.1 auth method")
+ log.debug('Received a password via the 1.1 auth method')
from base64 import decodestring
m = hashlib.md5()
- m.update(decodestring(config["old_pwd_salt"]))
+ m.update(decodestring(config['old_pwd_salt']))
m.update(utf8_encoded(password))
- if m.digest() == decodestring(config["old_pwd_md5"]):
+ if m.digest() == decodestring(config['old_pwd_md5']):
# We want to move the password over to sha1 and remove
# the old passwords from the config file.
self._change_password(password)
- del config.config["old_pwd_salt"]
- del config.config["old_pwd_md5"]
+ del config.config['old_pwd_salt']
+ del config.config['old_pwd_md5']
return True
- elif "pwd_sha1" in config.config:
+ elif 'pwd_sha1' in config.config:
# We are using the 1.2 auth method
- log.debug("Received a password via the 1.2 auth method")
+ log.debug('Received a password via the 1.2 auth method')
s = hashlib.sha1()
- s.update(config["pwd_salt"])
+ s.update(config['pwd_salt'])
s.update(utf8_encoded(password))
- if s.hexdigest() == config["pwd_sha1"]:
+ if s.hexdigest() == config['pwd_sha1']:
return True
else:
# Can't detect which method we should be using so just deny
# access.
- log.debug("Failed to detect the login method")
+ log.debug('Failed to detect the login method')
return False
def check_request(self, request, method=None, level=None):
@@ -202,39 +202,39 @@ class Auth(JSONComponent):
:raises: Exception
"""
- session_id = get_session_id(request.getCookie("_session_id"))
+ session_id = get_session_id(request.getCookie('_session_id'))
- if session_id not in self.config["sessions"]:
+ if session_id not in self.config['sessions']:
auth_level = AUTH_LEVEL_NONE
session_id = None
else:
- session = self.config["sessions"][session_id]
- auth_level = session["level"]
- expires, expires_str = make_expires(self.config["session_timeout"])
- session["expires"] = expires
+ session = self.config['sessions'][session_id]
+ auth_level = session['level']
+ expires, expires_str = make_expires(self.config['session_timeout'])
+ session['expires'] = expires
- _session_id = request.getCookie("_session_id")
+ _session_id = request.getCookie('_session_id')
request.addCookie('_session_id', _session_id,
- path=request.base + "json", expires=expires_str)
+ path=request.base + 'json', expires=expires_str)
if method:
- if not hasattr(method, "_json_export"):
- raise Exception("Not an exported method")
+ if not hasattr(method, '_json_export'):
+ raise Exception('Not an exported method')
- method_level = getattr(method, "_json_auth_level")
+ method_level = getattr(method, '_json_auth_level')
if method_level is None:
- raise Exception("Method has no auth level")
+ raise Exception('Method has no auth level')
level = method_level
if level is None:
- raise Exception("No level specified to check against")
+ raise Exception('No level specified to check against')
request.auth_level = auth_level
request.session_id = session_id
if auth_level < level:
- raise AuthError("Not authenticated")
+ raise AuthError('Not authenticated')
def _change_password(self, new_password):
"""
@@ -244,12 +244,12 @@ class Auth(JSONComponent):
:param new_password: the password to change to
:type new_password: string
"""
- log.debug("Changing password")
+ log.debug('Changing password')
salt = hashlib.sha1(os.urandom(32)).hexdigest()
s = hashlib.sha1(salt)
s.update(utf8_encoded(new_password))
- self.config["pwd_salt"] = salt
- self.config["pwd_sha1"] = s.hexdigest()
+ self.config['pwd_salt'] = salt
+ self.config['pwd_sha1'] = s.hexdigest()
return True
@export
@@ -284,7 +284,7 @@ class Auth(JSONComponent):
:param session_id: the id for the session to remove
:type session_id: string
"""
- del self.config["sessions"][__request__.session_id]
+ del self.config['sessions'][__request__.session_id]
return True
@export(AUTH_LEVEL_NONE)
diff --git a/deluge/ui/web/common.py b/deluge/ui/web/common.py
index 41ad776c8..ede22767d 100644
--- a/deluge/ui/web/common.py
+++ b/deluge/ui/web/common.py
@@ -14,7 +14,7 @@ from deluge import common
def _(text):
- return gettext.gettext(text).decode("utf-8")
+ return gettext.gettext(text).decode('utf-8')
def escape(text):
@@ -30,7 +30,7 @@ def escape(text):
def compress(contents, request):
- request.setHeader("content-encoding", "gzip")
+ request.setHeader('content-encoding', 'gzip')
compress_zlib = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0)
contents = compress_zlib.compress(contents)
contents += compress_zlib.flush()
@@ -47,9 +47,9 @@ try:
"""
builtins = {
- "_": _,
- "escape": escape,
- "version": common.get_version()
+ '_': _,
+ 'escape': escape,
+ 'version': common.get_version()
}
def render(self, *args, **data):
@@ -58,11 +58,11 @@ try:
return rendered.encode('utf-8', 'replace')
except ImportError:
import warnings
- warnings.warn("The Mako library is required to run deluge.ui.web",
+ 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 f7c370012..2599b7180 100644
--- a/deluge/ui/web/json_api.py
+++ b/deluge/ui/web/json_api.py
@@ -41,7 +41,7 @@ AuthError = None
class JSONComponent(component.Component):
def __init__(self, name, interval=1, depend=None):
super(JSONComponent, self).__init__(name, interval, depend)
- self._json = component.get("JSON")
+ self._json = component.get('JSON')
self._json.register_object(self, name)
@@ -87,7 +87,7 @@ class JSON(resource.Resource, component.Component):
def __init__(self):
resource.Resource.__init__(self)
- component.Component.__init__(self, "JSON")
+ component.Component.__init__(self, 'JSON')
self._remote_methods = []
self._local_methods = {}
if client.is_standalone():
@@ -109,7 +109,7 @@ class JSON(resource.Resource, component.Component):
"""
Handles executing all local methods.
"""
- if method == "system.listMethods":
+ if method == 'system.listMethods':
d = Deferred()
methods = list(self._remote_methods)
methods.extend(self._local_methods)
@@ -120,16 +120,16 @@ class JSON(resource.Resource, component.Component):
# and any plugins.
meth = self._local_methods[method]
meth.__globals__['__request__'] = request
- component.get("Auth").check_request(request, meth)
+ component.get('Auth').check_request(request, meth)
return meth(*params)
- raise JSONException("Unknown system method")
+ raise JSONException('Unknown system method')
def _exec_remote(self, method, params, request):
"""
Executes methods using the Deluge client.
"""
- component.get("Auth").check_request(request, level=AUTH_LEVEL_DEFAULT)
- core_component, method = method.split(".")
+ component.get('Auth').check_request(request, level=AUTH_LEVEL_DEFAULT)
+ core_component, method = method.split('.')
return getattr(getattr(client, core_component), method)(*params)
def _handle_request(self, request):
@@ -141,29 +141,29 @@ class JSON(resource.Resource, component.Component):
try:
request.json = json.loads(request.json)
except (ValueError, TypeError):
- raise JSONException("JSON not decodable")
- if "method" not in request.json or "id" not in request.json or \
- "params" not in request.json:
- raise JSONException("Invalid JSON request")
+ raise JSONException('JSON not decodable')
+ if 'method' not in request.json or 'id' not in request.json or \
+ 'params' not in request.json:
+ raise JSONException('Invalid JSON request')
- method, params = request.json["method"], request.json["params"]
- request_id = request.json["id"]
+ method, params = request.json['method'], request.json['params']
+ request_id = request.json['id']
result = None
error = None
try:
- if method.startswith("system.") or method in self._local_methods:
+ if method.startswith('system.') or method in self._local_methods:
result = self._exec_local(method, params, request)
elif method in self._remote_methods:
result = self._exec_remote(method, params, request)
else:
- error = {"message": "Unknown method", "code": 2}
+ error = {'message': 'Unknown method', 'code': 2}
except AuthError:
- error = {"message": "Not authenticated", "code": 1}
+ error = {'message': 'Not authenticated', 'code': 1}
except Exception as ex:
- log.error("Error calling method `%s`", method)
+ log.error('Error calling method `%s`', method)
log.exception(ex)
- error = {"message": "%s: %s" % (ex.__class__.__name__, str(ex)), "code": 3}
+ error = {'message': '%s: %s' % (ex.__class__.__name__, str(ex)), 'code': 3}
return request_id, result, error
@@ -171,7 +171,7 @@ class JSON(resource.Resource, component.Component):
"""
Sends the response of any rpc calls back to the json-rpc client.
"""
- response["result"] = result
+ response['result'] = result
return self._send_response(request, response)
def _on_rpc_request_failed(self, reason, response, request):
@@ -179,7 +179,7 @@ class JSON(resource.Resource, component.Component):
Handles any failures that occurred while making an rpc call.
"""
log.exception(reason)
- response["error"] = {"message": "%s: %s" % (reason.__class__.__name__, str(reason)), "code": 4}
+ response['error'] = {'message': '%s: %s' % (reason.__class__.__name__, str(reason)), 'code': 4}
return self._send_response(request, response)
def _on_json_request(self, request):
@@ -187,16 +187,16 @@ class JSON(resource.Resource, component.Component):
Handler to take the json data as a string and pass it on to the
_handle_request method for further processing.
"""
- log.debug("json-request: %s", request.json)
- response = {"result": None, "error": None, "id": None}
- response["id"], d, response["error"] = self._handle_request(request)
+ log.debug('json-request: %s', request.json)
+ response = {'result': None, 'error': None, 'id': None}
+ response['id'], d, response['error'] = self._handle_request(request)
if isinstance(d, Deferred):
d.addCallback(self._on_rpc_request_finished, response, request)
d.addErrback(self._on_rpc_request_failed, response, request)
return d
else:
- response["result"] = d
+ response['result'] = d
return self._send_response(request, response)
def _on_json_request_failed(self, reason, request):
@@ -204,16 +204,16 @@ class JSON(resource.Resource, component.Component):
Returns the error in json response.
"""
log.exception(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):
if request._disconnected:
- return ""
+ return ''
response = json.dumps(response)
- request.setHeader("content-type", "application/x-json")
+ request.setHeader('content-type', 'application/x-json')
request.write(compress(response, request))
request.finish()
return server.NOT_DONE_YET
@@ -222,7 +222,7 @@ class JSON(resource.Resource, component.Component):
"""
Handles all the POST requests made to the /json controller.
"""
- if request.method != "POST":
+ if request.method != 'POST':
request.setResponseCode(http.NOT_ALLOWED)
request.finish()
return server.NOT_DONE_YET
@@ -249,11 +249,11 @@ class JSON(resource.Resource, component.Component):
name = name.lower()
for d in dir(obj):
- if d[0] == "_":
+ if d[0] == '_':
continue
if getattr(getattr(obj, d), '_json_export', False):
- log.debug("Registering method: %s", name + "." + d)
- self._local_methods[name + "." + d] = getattr(obj, d)
+ log.debug('Registering method: %s', name + '.' + d)
+ self._local_methods[name + '.' + d] = getattr(obj, d)
HOSTLIST_ID = 0
@@ -269,7 +269,7 @@ HOSTS_USER = HOSTLIST_USER
HOSTS_STATUS = 3
HOSTS_INFO = 4
-FILES_KEYS = ["files", "file_progress", "file_priorities"]
+FILES_KEYS = ['files', 'file_progress', 'file_priorities']
class EventQueue(object):
@@ -363,45 +363,45 @@ class WebApi(JSONComponent):
"""
def __init__(self):
- super(WebApi, self).__init__("Web", depend=["SessionProxy"])
- self.host_list = ConfigManager("hostlist.conf.1.2", uicommon.DEFAULT_HOSTS)
+ super(WebApi, self).__init__('Web', depend=['SessionProxy'])
+ self.host_list = ConfigManager('hostlist.conf.1.2', uicommon.DEFAULT_HOSTS)
if not os.path.isfile(self.host_list.config_file):
self.host_list.save()
self.core_config = CoreConfig()
self.event_queue = EventQueue()
try:
- self.sessionproxy = component.get("SessionProxy")
+ self.sessionproxy = component.get('SessionProxy')
except KeyError:
self.sessionproxy = SessionProxy()
def disable(self):
- client.deregister_event_handler("PluginEnabledEvent", self._json.get_remote_methods)
- client.deregister_event_handler("PluginDisabledEvent", self._json.get_remote_methods)
+ client.deregister_event_handler('PluginEnabledEvent', self._json.get_remote_methods)
+ client.deregister_event_handler('PluginDisabledEvent', self._json.get_remote_methods)
if client.is_standalone():
- component.get("Web.PluginManager").stop()
+ component.get('Web.PluginManager').stop()
else:
client.disconnect()
client.set_disconnect_callback(None)
def enable(self):
- client.register_event_handler("PluginEnabledEvent", self._json.get_remote_methods)
- client.register_event_handler("PluginDisabledEvent", self._json.get_remote_methods)
+ client.register_event_handler('PluginEnabledEvent', self._json.get_remote_methods)
+ client.register_event_handler('PluginDisabledEvent', self._json.get_remote_methods)
if client.is_standalone():
- component.get("Web.PluginManager").start()
+ component.get('Web.PluginManager').start()
else:
client.set_disconnect_callback(self._on_client_disconnect)
- if component.get("DelugeWeb").config["default_daemon"]:
+ if component.get('DelugeWeb').config['default_daemon']:
# Sort out getting the default daemon here
- default_host_id = component.get("DelugeWeb").config["default_daemon"]
- host_info = component.get("Web")._get_host(default_host_id)
+ default_host_id = component.get('DelugeWeb').config['default_daemon']
+ host_info = component.get('Web')._get_host(default_host_id)
return self._connect_daemon(*host_info[1:])
return defer.succeed(True)
def _on_client_disconnect(self, *args):
- component.get("Web.PluginManager").stop()
+ component.get('Web.PluginManager').stop()
return self.stop()
def _get_host(self, host_id):
@@ -415,7 +415,7 @@ class WebApi(JSONComponent):
"""
host_info = []
- for host_entry in self.host_list["hosts"]:
+ for host_entry in self.host_list['hosts']:
if host_entry[0] == host_id:
host_info = host_entry
break
@@ -430,7 +430,7 @@ class WebApi(JSONComponent):
self.sessionproxy.stop()
return defer.succeed(True)
- def _connect_daemon(self, host="localhost", port=58846, username="", password=""):
+ def _connect_daemon(self, host='localhost', port=58846, username='', password=''):
"""
Connects the client to a daemon
"""
@@ -442,7 +442,7 @@ class WebApi(JSONComponent):
invokes retrieving the method names.
"""
d = self._json.get_remote_methods()
- component.get("Web.PluginManager").start()
+ component.get('Web.PluginManager').start()
self.start()
return d
@@ -461,7 +461,7 @@ class WebApi(JSONComponent):
host = self._get_host(host_id)
if host:
return self._connect_daemon(*host[1:])
- return defer.fail(Exception("Bad host id"))
+ return defer.fail(Exception('Bad host id'))
@export
def connected(self):
@@ -499,13 +499,13 @@ class WebApi(JSONComponent):
"""
d = Deferred()
ui_info = {
- "connected": client.connected(),
- "torrents": None,
- "filters": None,
- "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")
+ 'connected': client.connected(),
+ 'torrents': None,
+ 'filters': None,
+ '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')
}
}
@@ -514,47 +514,47 @@ class WebApi(JSONComponent):
return d
def got_stats(stats):
- ui_info["stats"]["num_connections"] = stats["num_peers"]
- ui_info["stats"]["upload_rate"] = stats["payload_upload_rate"]
- ui_info["stats"]["download_rate"] = stats["payload_download_rate"]
- ui_info["stats"]["download_protocol_rate"] = stats["download_rate"] - stats["payload_download_rate"]
- ui_info["stats"]["upload_protocol_rate"] = stats["upload_rate"] - stats["payload_upload_rate"]
- ui_info["stats"]["dht_nodes"] = stats["dht_nodes"]
- ui_info["stats"]["has_incoming_connections"] = stats["has_incoming_connections"]
+ ui_info['stats']['num_connections'] = stats['num_peers']
+ ui_info['stats']['upload_rate'] = stats['payload_upload_rate']
+ ui_info['stats']['download_rate'] = stats['payload_download_rate']
+ ui_info['stats']['download_protocol_rate'] = stats['download_rate'] - stats['payload_download_rate']
+ ui_info['stats']['upload_protocol_rate'] = stats['upload_rate'] - stats['payload_upload_rate']
+ ui_info['stats']['dht_nodes'] = stats['dht_nodes']
+ ui_info['stats']['has_incoming_connections'] = stats['has_incoming_connections']
def got_filters(filters):
- ui_info["filters"] = filters
+ ui_info['filters'] = filters
def got_free_space(free_space):
- ui_info["stats"]["free_space"] = free_space
+ ui_info['stats']['free_space'] = free_space
def got_external_ip(external_ip):
- ui_info["stats"]["external_ip"] = external_ip
+ ui_info['stats']['external_ip'] = external_ip
def got_torrents(torrents):
- ui_info["torrents"] = torrents
+ ui_info['torrents'] = torrents
def on_complete(result):
d.callback(ui_info)
- d1 = component.get("SessionProxy").get_torrents_status(filter_dict, keys)
+ d1 = component.get('SessionProxy').get_torrents_status(filter_dict, keys)
d1.addCallback(got_torrents)
d2 = client.core.get_filter_tree()
d2.addCallback(got_filters)
d3 = client.core.get_session_status([
- "num_peers",
- "payload_download_rate",
- "payload_upload_rate",
- "download_rate",
- "upload_rate",
- "dht_nodes",
- "has_incoming_connections"
+ 'num_peers',
+ 'payload_download_rate',
+ 'payload_upload_rate',
+ 'download_rate',
+ 'upload_rate',
+ 'dht_nodes',
+ 'has_incoming_connections'
])
d3.addCallback(got_stats)
- d4 = client.core.get_free_space(self.core_config.get("download_location"))
+ d4 = client.core.get_free_space(self.core_config.get('download_location'))
d4.addCallback(got_free_space)
d5 = client.core.get_external_ip()
@@ -565,40 +565,40 @@ class WebApi(JSONComponent):
return d
def _on_got_files(self, torrent, d):
- files = torrent.get("files")
- file_progress = torrent.get("file_progress")
- file_priorities = torrent.get("file_priorities")
+ files = torrent.get('files')
+ file_progress = torrent.get('file_progress')
+ file_priorities = torrent.get('file_priorities')
paths = []
info = {}
for index, torrent_file in enumerate(files):
- path = torrent_file["path"]
+ path = torrent_file['path']
paths.append(path)
- torrent_file["progress"] = file_progress[index]
- torrent_file["priority"] = file_priorities[index]
- torrent_file["index"] = index
- torrent_file["path"] = path
+ torrent_file['progress'] = file_progress[index]
+ torrent_file['priority'] = file_priorities[index]
+ torrent_file['index'] = index
+ torrent_file['path'] = path
info[path] = torrent_file
# update the directory info
dirname = os.path.dirname(path)
while dirname:
dirinfo = info.setdefault(dirname, {})
- dirinfo["size"] = dirinfo.get("size", 0) + torrent_file["size"]
- if "priority" not in dirinfo:
- dirinfo["priority"] = torrent_file["priority"]
+ dirinfo['size'] = dirinfo.get('size', 0) + torrent_file['size']
+ if 'priority' not in dirinfo:
+ dirinfo['priority'] = torrent_file['priority']
else:
- if dirinfo["priority"] != torrent_file["priority"]:
- dirinfo["priority"] = 9
+ if dirinfo['priority'] != torrent_file['priority']:
+ dirinfo['priority'] = 9
- progresses = dirinfo.setdefault("progresses", [])
- progresses.append(torrent_file["size"] * torrent_file["progress"] / 100)
- dirinfo["progress"] = sum(progresses) / dirinfo["size"] * 100
- dirinfo["path"] = dirname
+ progresses = dirinfo.setdefault('progresses', [])
+ progresses.append(torrent_file['size'] * torrent_file['progress'] / 100)
+ dirinfo['progress'] = sum(progresses) / dirinfo['size'] * 100
+ dirinfo['path'] = dirname
dirname = os.path.dirname(dirname)
def walk(path, item):
- if item["type"] == "dir":
+ if item['type'] == 'dir':
item.update(info[path])
return item
else:
@@ -611,7 +611,7 @@ class WebApi(JSONComponent):
@export
def get_torrent_status(self, torrent_id, keys):
- return component.get("SessionProxy").get_torrent_status(torrent_id, keys)
+ return component.get('SessionProxy').get_torrent_status(torrent_id, keys)
@export
def get_torrent_files(self, torrent_id):
@@ -624,7 +624,7 @@ class WebApi(JSONComponent):
:rtype: dictionary
"""
main_deferred = Deferred()
- d = component.get("SessionProxy").get_torrent_status(torrent_id, FILES_KEYS)
+ d = component.get('SessionProxy').get_torrent_status(torrent_id, FILES_KEYS)
d.addCallback(self._on_got_files, main_deferred)
return main_deferred
@@ -640,20 +640,20 @@ class WebApi(JSONComponent):
"""
def on_download_success(result):
- log.debug("Successfully downloaded %s to %s", url, result)
+ log.debug('Successfully downloaded %s to %s', url, result)
return result
def on_download_fail(result):
- log.error("Failed to add torrent from url %s", url)
+ log.error('Failed to add torrent from url %s', url)
return result
- tempdir = tempfile.mkdtemp(prefix="delugeweb-")
- tmp_file = os.path.join(tempdir, url.split("/")[-1])
- log.debug("filename: %s", tmp_file)
+ tempdir = tempfile.mkdtemp(prefix='delugeweb-')
+ tmp_file = os.path.join(tempdir, url.split('/')[-1])
+ log.debug('filename: %s', tmp_file)
headers = {}
if cookie:
- headers["Cookie"] = cookie
- log.debug("cookie: %s", cookie)
+ headers['Cookie'] = cookie
+ log.debug('cookie: %s', cookie)
d = httpdownloader.download_file(url, tmp_file, headers=headers)
d.addCallbacks(on_download_success, on_download_fail)
return d
@@ -680,7 +680,7 @@ class WebApi(JSONComponent):
"""
try:
torrent_info = uicommon.TorrentInfo(filename.strip(), 2)
- return torrent_info.as_dict("name", "info_hash", "files_tree")
+ return torrent_info.as_dict('name', 'info_hash', 'files_tree')
except Exception as ex:
log.exception(ex)
return False
@@ -709,18 +709,18 @@ class WebApi(JSONComponent):
deferreds = []
for torrent in torrents:
- if common.is_magnet(torrent["path"]):
- 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"])
+ if common.is_magnet(torrent['path']):
+ 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:
+ 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"])
- d = client.core.add_torrent_file(filename, fdump, torrent["options"])
+ log.info('Adding torrent from file `%s` with options `%r`',
+ filename, torrent['options'])
+ d = client.core.add_torrent_file(filename, fdump, torrent['options'])
deferreds.append(d)
return DeferredList(deferreds, consumeErrors=False)
@@ -729,8 +729,8 @@ class WebApi(JSONComponent):
"""
Return the hosts in the hostlist.
"""
- log.debug("get_hosts called")
- return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ("Offline",)) for host in self.host_list["hosts"]]
+ log.debug('get_hosts called')
+ return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ('Offline',)) for host in self.host_list['hosts']]
@export
def get_host_status(self, host_id):
@@ -748,30 +748,30 @@ class WebApi(JSONComponent):
except TypeError:
host = None
port = None
- return response("Offline")
+ return response('Offline')
def on_connect(connected, c, host_id):
def on_info(info, c):
c.disconnect()
- return response("Online", info)
+ return response('Online', info)
def on_info_fail(reason, c):
c.disconnect()
- return response("Offline")
+ return response('Offline')
if not connected:
- return response("Offline")
+ return response('Offline')
return c.daemon.info().addCallback(on_info, c).addErrback(on_info_fail, c)
def on_connect_failed(reason, host_id):
- return response("Offline")
+ return response('Offline')
- if client.connected() and (host, port, "localclient" if not
- user and host in ("127.0.0.1", "localhost") else
+ if client.connected() and (host, port, 'localclient' if not
+ user and host in ('127.0.0.1', 'localhost') else
user) == client.connection_info():
def on_info(info):
- return response("Connected", info)
+ return response('Connected', info)
return client.daemon.info().addCallback(on_info)
else:
@@ -804,7 +804,7 @@ class WebApi(JSONComponent):
try:
def on_connect(connected, c):
if not connected:
- main_deferred.callback((False, _("Daemon not running")))
+ main_deferred.callback((False, _('Daemon not running')))
return
c.daemon.shutdown()
main_deferred.callback((True, ))
@@ -818,11 +818,11 @@ class WebApi(JSONComponent):
d.addCallback(on_connect, c)
d.addErrback(on_connect_failed)
except Exception:
- main_deferred.callback((False, "An error occurred"))
+ main_deferred.callback((False, 'An error occurred'))
return main_deferred
@export
- def add_host(self, host, port, username="", password=""):
+ def add_host(self, host, port, username='', password=''):
"""
Adds a host to the list.
@@ -838,18 +838,18 @@ class WebApi(JSONComponent):
"""
# Check to see if there is already an entry for this host and return
# if thats the case
- for entry in self.host_list["hosts"]:
+ for entry in self.host_list['hosts']:
if (entry[1], entry[2], entry[3]) == (host, port, username):
- return (False, "Host already in the list")
+ return (False, 'Host already in the list')
try:
port = int(port)
except ValueError:
- return (False, "Port is invalid")
+ return (False, 'Port is invalid')
# Host isn't in the list, so lets add it
connection_id = hashlib.sha1(str(time.time())).hexdigest()
- self.host_list["hosts"].append([connection_id, host, port, username,
+ self.host_list['hosts'].append([connection_id, host, port, username,
password])
self.host_list.save()
return True, connection_id
@@ -866,7 +866,7 @@ class WebApi(JSONComponent):
if not host:
return False
- self.host_list["hosts"].remove(host)
+ self.host_list['hosts'].remove(host)
self.host_list.save()
return True
@@ -878,10 +878,10 @@ class WebApi(JSONComponent):
:rtype: dictionary
:returns: the configuration
"""
- config = component.get("DelugeWeb").config.config.copy()
- del config["sessions"]
- del config["pwd_salt"]
- del config["pwd_sha1"]
+ config = component.get('DelugeWeb').config.config.copy()
+ del config['sessions']
+ del config['pwd_salt']
+ del config['pwd_sha1']
return config
@export
@@ -892,13 +892,13 @@ class WebApi(JSONComponent):
:param config: The configuration options to update
:type config: dictionary
"""
- web_config = component.get("DelugeWeb").config
+ web_config = component.get('DelugeWeb').config
for key in config.keys():
- if key in ["sessions", "pwd_salt", "pwd_sha1"]:
+ if key in ['sessions', 'pwd_salt', 'pwd_sha1']:
log.warn("Ignored attempt to overwrite web config key '%s'", key)
continue
if isinstance(config[key], basestring):
- config[key] = config[key].encode("utf8")
+ config[key] = config[key].encode('utf8')
web_config[key] = config[key]
@export
@@ -914,34 +914,34 @@ class WebApi(JSONComponent):
"""
return {
- "enabled_plugins": component.get("Web.PluginManager").plugins.keys(),
- "available_plugins": component.get("Web.PluginManager").available_plugins
+ 'enabled_plugins': component.get('Web.PluginManager').plugins.keys(),
+ 'available_plugins': component.get('Web.PluginManager').available_plugins
}
@export
def get_plugin_info(self, name):
- return component.get("Web.PluginManager").get_plugin_info(name)
+ return component.get('Web.PluginManager').get_plugin_info(name)
@export
def get_plugin_resources(self, name):
- return component.get("Web.PluginManager").get_plugin_resources(name)
+ return component.get('Web.PluginManager').get_plugin_resources(name)
@export
def upload_plugin(self, filename, path):
main_deferred = Deferred()
- shutil.copyfile(path, os.path.join(get_config_dir(), "plugins", filename))
- component.get("Web.PluginManager").scan_for_plugins()
+ shutil.copyfile(path, os.path.join(get_config_dir(), 'plugins', filename))
+ component.get('Web.PluginManager').scan_for_plugins()
if client.is_localhost():
client.core.rescan_plugins()
return True
- with open(path, "rb") as _file:
+ with open(path, 'rb') as _file:
plugin_data = base64.encodestring(_file.read())
def on_upload_complete(*args):
client.core.rescan_plugins()
- component.get("Web.PluginManager").scan_for_plugins()
+ component.get('Web.PluginManager').scan_for_plugins()
main_deferred.callback(True)
def on_upload_error(*args):
@@ -985,7 +985,7 @@ class WebUtils(JSONComponent):
Utility functions for the webui that do not fit in the WebApi.
"""
def __init__(self):
- super(WebUtils, self).__init__("WebUtils")
+ super(WebUtils, self).__init__('WebUtils')
@export
def get_languages(self):
diff --git a/deluge/ui/web/pluginmanager.py b/deluge/ui/web/pluginmanager.py
index f5485cfea..f636db5d7 100644
--- a/deluge/ui/web/pluginmanager.py
+++ b/deluge/ui/web/pluginmanager.py
@@ -20,8 +20,8 @@ log = logging.getLogger(__name__)
def gather_info(plugin):
# Get the scripts for the plugin
- scripts = getattr(plugin, "scripts", ())
- debug_scripts = getattr(plugin, "debug_scripts") or scripts
+ scripts = getattr(plugin, 'scripts', ())
+ debug_scripts = getattr(plugin, 'debug_scripts') or scripts
directories = []
for script in scripts + debug_scripts:
@@ -29,20 +29,20 @@ def gather_info(plugin):
directories.append(os.path.dirname(script))
return {
- "scripts": scripts,
- "debug_scripts": debug_scripts,
- "script_directories": directories
+ 'scripts': scripts,
+ 'debug_scripts': debug_scripts,
+ 'script_directories': directories
}
class PluginManager(PluginManagerBase, component.Component):
def __init__(self):
- component.Component.__init__(self, "Web.PluginManager")
- self.config = ConfigManager("web.conf")
- PluginManagerBase.__init__(self, "web.conf", "deluge.plugin.web")
+ component.Component.__init__(self, 'Web.PluginManager')
+ self.config = ConfigManager('web.conf')
+ PluginManagerBase.__init__(self, 'web.conf', 'deluge.plugin.web')
- client.register_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event)
- client.register_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event)
+ client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event)
+ client.register_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event)
def _on_get_enabled_plugins(self, plugins):
for plugin in plugins:
@@ -57,20 +57,20 @@ class PluginManager(PluginManagerBase, component.Component):
def disable_plugin(self, name):
# Get the plugin instance
try:
- plugin = component.get("WebPlugin." + name)
+ plugin = component.get('WebPlugin.' + name)
except KeyError:
log.debug("'%s' plugin contains no WebUI code, ignoring WebUI disable call.", name)
return
info = gather_info(plugin)
- scripts = component.get("Scripts")
- for script in info["scripts"]:
- scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()))
+ scripts = component.get('Scripts')
+ for script in info['scripts']:
+ scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()))
- for script in info["debug_scripts"]:
- scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "debug")
- scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "dev")
+ for script in info['debug_scripts']:
+ scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'debug')
+ scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'dev')
super(PluginManager, self).disable_plugin(name)
@@ -79,22 +79,22 @@ class PluginManager(PluginManagerBase, component.Component):
# Get the plugin instance
try:
- plugin = component.get("WebPlugin." + name)
+ plugin = component.get('WebPlugin.' + name)
except KeyError:
log.info("'%s' plugin contains no WebUI code, ignoring WebUI enable call.", name)
return
info = gather_info(plugin)
- scripts = component.get("Scripts")
- for script in info["scripts"]:
- log.debug("adding script %s for %s", name, os.path.basename(script))
- scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script)
+ scripts = component.get('Scripts')
+ for script in info['scripts']:
+ log.debug('adding script %s for %s', name, os.path.basename(script))
+ scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script)
- for script in info["debug_scripts"]:
- log.debug("adding debug script %s for %s", name, os.path.basename(script))
- scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "debug")
- scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "dev")
+ for script in info['debug_scripts']:
+ log.debug('adding debug script %s for %s', name, os.path.basename(script))
+ scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'debug')
+ scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'dev')
def start(self):
"""
@@ -109,8 +109,8 @@ class PluginManager(PluginManagerBase, component.Component):
Stop the plugin manager
"""
self.disable_plugins()
- client.deregister_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event)
- client.deregister_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event)
+ client.deregister_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event)
+ client.deregister_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event)
def update(self):
pass
@@ -118,13 +118,13 @@ class PluginManager(PluginManagerBase, component.Component):
def get_plugin_resources(self, name):
# Get the plugin instance
try:
- plugin = component.get("WebPlugin." + name)
+ plugin = component.get('WebPlugin.' + name)
except KeyError:
- log.info("Plugin has no web ui")
+ log.info('Plugin has no web ui')
return
info = gather_info(plugin)
- info["name"] = name
- info["scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["scripts"]]
- info["debug_scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["debug_scripts"]]
- del info["script_directories"]
+ info['name'] = name
+ info['scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['scripts']]
+ info['debug_scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['debug_scripts']]
+ del info['script_directories']
return info
diff --git a/deluge/ui/web/server.py b/deluge/ui/web/server.py
index 3ec16f824..26a20e268 100644
--- a/deluge/ui/web/server.py
+++ b/deluge/ui/web/server.py
@@ -33,36 +33,36 @@ log = logging.getLogger(__name__)
CONFIG_DEFAULTS = {
# Misc Settings
- "enabled_plugins": [],
- "default_daemon": "",
+ 'enabled_plugins': [],
+ 'default_daemon': '',
# Auth Settings
- "pwd_salt": "c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad",
- "pwd_sha1": "2ce1a410bcdcc53064129b6d950f2e9fee4edc1e",
- "session_timeout": 3600,
- "sessions": {},
+ 'pwd_salt': 'c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad',
+ 'pwd_sha1': '2ce1a410bcdcc53064129b6d950f2e9fee4edc1e',
+ 'session_timeout': 3600,
+ 'sessions': {},
# UI Settings
- "sidebar_show_zero": False,
- "sidebar_multiple_filters": True,
- "show_session_speed": False,
- "show_sidebar": True,
- "theme": "gray",
- "first_login": True,
- "language": "",
+ 'sidebar_show_zero': False,
+ 'sidebar_multiple_filters': True,
+ 'show_session_speed': False,
+ 'show_sidebar': True,
+ 'theme': 'gray',
+ 'first_login': True,
+ 'language': '',
# Server Settings
- "base": "/",
- "interface": "0.0.0.0",
- "port": 8112,
- "https": False,
- "pkey": "ssl/daemon.pkey",
- "cert": "ssl/daemon.cert"
+ 'base': '/',
+ 'interface': '0.0.0.0',
+ 'port': 8112,
+ 'https': False,
+ 'pkey': 'ssl/daemon.pkey',
+ 'cert': 'ssl/daemon.cert'
}
UI_CONFIG_KEYS = (
- "theme", "sidebar_show_zero", "sidebar_multiple_filters",
- "show_session_speed", "base", "first_login"
+ 'theme', 'sidebar_show_zero', 'sidebar_multiple_filters',
+ 'show_session_speed', 'base', 'first_login'
)
@@ -70,13 +70,13 @@ def rpath(*paths):
"""Convert a relative path into an absolute path relative to the location
of this script.
"""
- return common.resource_filename("deluge.ui.web", os.path.join(*paths))
+ return common.resource_filename('deluge.ui.web', os.path.join(*paths))
class GetText(resource.Resource):
def render(self, request):
- request.setHeader("content-type", "text/javascript; encoding=utf-8")
- template = Template(filename=rpath("js", "gettext.js"))
+ request.setHeader('content-type', 'text/javascript; encoding=utf-8')
+ template = Template(filename=rpath('js', 'gettext.js'))
return compress(template.render(), request)
@@ -92,29 +92,29 @@ class Upload(resource.Resource):
"""
# Block all other HTTP methods.
- if request.method != "POST":
+ if request.method != 'POST':
request.setResponseCode(http.NOT_ALLOWED)
- return ""
+ return ''
- if "file" not in request.args:
+ if 'file' not in request.args:
request.setResponseCode(http.OK)
return json.dumps({
'success': True,
'files': []
})
- tempdir = tempfile.mkdtemp(prefix="delugeweb-")
- log.debug("uploading files to %s", tempdir)
+ tempdir = tempfile.mkdtemp(prefix='delugeweb-')
+ log.debug('uploading files to %s', tempdir)
filenames = []
- for upload in request.args.get("file"):
+ for upload in request.args.get('file'):
fd, fn = tempfile.mkstemp('.torrent', dir=tempdir)
os.write(fd, upload)
os.close(fd)
filenames.append(fn)
- log.debug("uploaded %d file(s)", len(filenames))
+ log.debug('uploaded %d file(s)', len(filenames))
- request.setHeader("content-type", "text/html")
+ request.setHeader('content-type', 'text/html')
request.setResponseCode(http.OK)
return compress(json.dumps({
'success': True,
@@ -129,13 +129,13 @@ class Render(resource.Resource):
return self
def render(self, request):
- if not hasattr(request, "render_file"):
+ if not hasattr(request, 'render_file'):
request.setResponseCode(http.INTERNAL_SERVER_ERROR)
- return ""
+ return ''
- filename = os.path.join("render", request.render_file)
+ filename = os.path.join('render', request.render_file)
template = Template(filename=rpath(filename))
- request.setHeader("content-type", "text/html")
+ request.setHeader('content-type', 'text/html')
request.setResponseCode(http.OK)
return compress(template.render(), request)
@@ -145,7 +145,7 @@ class Tracker(resource.Resource):
def __init__(self):
resource.Resource.__init__(self)
try:
- self.tracker_icons = component.get("TrackerIcons")
+ self.tracker_icons = component.get('TrackerIcons')
except KeyError:
self.tracker_icons = TrackerIcons()
@@ -155,9 +155,9 @@ class Tracker(resource.Resource):
def on_got_icon(self, icon, request):
if icon:
- request.setHeader("cache-control",
- "public, must-revalidate, max-age=86400")
- request.setHeader("content-type", icon.get_mimetype())
+ request.setHeader('cache-control',
+ 'public, must-revalidate, max-age=86400')
+ request.setHeader('content-type', icon.get_mimetype())
request.setResponseCode(http.OK)
request.write(icon.get_data())
request.finish()
@@ -177,19 +177,19 @@ class Flag(resource.Resource):
return self
def render(self, request):
- path = ("ui", "data", "pixmaps", "flags", request.country.lower() + ".png")
- filename = common.resource_filename("deluge", os.path.join(*path))
+ 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("content-type", "image/png")
- with open(filename, "rb") as _file:
+ 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()
request.setResponseCode(http.OK)
return data
else:
request.setResponseCode(http.NOT_FOUND)
- return ""
+ return ''
class LookupResource(resource.Resource, component.Component):
@@ -202,13 +202,13 @@ class LookupResource(resource.Resource, component.Component):
for directory in directories:
self.add_directory(directory)
- def add_directory(self, directory, path=""):
- log.debug("Adding directory `%s` with path `%s`", directory, path)
+ def add_directory(self, directory, path=''):
+ log.debug('Adding directory `%s` with path `%s`', directory, path)
paths = self.__paths.setdefault(path, [])
paths.append(directory)
- def remove_directory(self, directory, path=""):
- log.debug("Removing directory `%s`", directory)
+ def remove_directory(self, directory, path=''):
+ log.debug('Removing directory `%s`', directory)
self.__paths[path].remove(directory)
def getChild(self, path, request): # NOQA
@@ -224,7 +224,7 @@ class LookupResource(resource.Resource, component.Component):
if path not in self.__paths:
request.setResponseCode(http.NOT_FOUND)
- return "<h1>404 - Not Found</h1>"
+ return '<h1>404 - Not Found</h1>'
filename = os.path.basename(request.path)
for directory in self.__paths[path]:
@@ -232,23 +232,23 @@ class LookupResource(resource.Resource, component.Component):
path = os.path.join(directory, filename)
log.debug("Serving path: '%s'", path)
mime_type = mimetypes.guess_type(path)
- request.setHeader("content-type", mime_type[0])
- with open(path, "rb") as _file:
+ request.setHeader('content-type', mime_type[0])
+ with open(path, 'rb') as _file:
data = _file.read()
return compress(data, request)
request.setResponseCode(http.NOT_FOUND)
- return "<h1>404 - Not Found</h1>"
+ return '<h1>404 - Not Found</h1>'
class ScriptResource(resource.Resource, component.Component):
def __init__(self):
resource.Resource.__init__(self)
- component.Component.__init__(self, "Scripts")
+ component.Component.__init__(self, 'Scripts')
self.__scripts = {}
- for script_type in ["normal", "debug", "dev"]:
- self.__scripts[script_type] = {"scripts": {}, "order": [], "files_exist": True}
+ for script_type in ['normal', 'debug', 'dev']:
+ self.__scripts[script_type] = {'scripts': {}, 'order': [], 'files_exist': True}
def has_script_type_files(self, script_type):
"""Returns whether all the script files exist for this script type.
@@ -260,7 +260,7 @@ class ScriptResource(resource.Resource, component.Component):
bool: True if the files for this script type exist, otherwise False.
"""
- return self.__scripts[script_type]["files_exist"]
+ return self.__scripts[script_type]['files_exist']
def add_script(self, path, filepath, script_type=None):
"""
@@ -273,13 +273,13 @@ class ScriptResource(resource.Resource, component.Component):
:keyword script_type: The type of script to add (normal, debug, dev)
:param script_type: string
"""
- if script_type not in ("dev", "debug", "normal"):
- script_type = "normal"
+ if script_type not in ('dev', 'debug', 'normal'):
+ script_type = 'normal'
- self.__scripts[script_type]["scripts"][path] = filepath
- self.__scripts[script_type]["order"].append(path)
+ self.__scripts[script_type]['scripts'][path] = filepath
+ self.__scripts[script_type]['order'].append(path)
if not os.path.isfile(filepath):
- self.__scripts[script_type]["files_exist"] = False
+ self.__scripts[script_type]['files_exist'] = False
def add_script_folder(self, path, filepath, script_type=None, recurse=True):
"""
@@ -294,13 +294,13 @@ class ScriptResource(resource.Resource, component.Component):
:keyword recurse: Whether or not to recurse into other folders
:param recurse: bool
"""
- if script_type not in ("dev", "debug", "normal"):
- script_type = "normal"
+ if script_type not in ('dev', 'debug', 'normal'):
+ script_type = 'normal'
- self.__scripts[script_type]["scripts"][path] = (filepath, recurse)
- self.__scripts[script_type]["order"].append(path)
+ self.__scripts[script_type]['scripts'][path] = (filepath, recurse)
+ self.__scripts[script_type]['order'].append(path)
if not os.path.isdir(filepath):
- self.__scripts[script_type]["files_exist"] = False
+ self.__scripts[script_type]['files_exist'] = False
def remove_script(self, path, script_type=None):
"""
@@ -311,11 +311,11 @@ class ScriptResource(resource.Resource, component.Component):
:keyword script_type: The type of script to add (normal, debug, dev)
:param script_type: string
"""
- if script_type not in ("dev", "debug", "normal"):
- script_type = "normal"
+ if script_type not in ('dev', 'debug', 'normal'):
+ script_type = 'normal'
- del self.__scripts[script_type]["scripts"][path]
- self.__scripts[script_type]["order"].remove(path)
+ del self.__scripts[script_type]['scripts'][path]
+ self.__scripts[script_type]['order'].remove(path)
def get_scripts(self, script_type=None):
"""
@@ -325,11 +325,11 @@ class ScriptResource(resource.Resource, component.Component):
:keyword script_type: The type of scripts to get (normal, debug, dev)
:param script_type: string
"""
- if script_type not in ("dev", "debug", "normal"):
+ if script_type not in ('dev', 'debug', 'normal'):
script_type = 'normal'
- _scripts = self.__scripts[script_type]["scripts"]
- _order = self.__scripts[script_type]["order"]
+ _scripts = self.__scripts[script_type]['scripts']
+ _order = self.__scripts[script_type]['order']
scripts = []
for path in _order:
@@ -340,34 +340,34 @@ class ScriptResource(resource.Resource, component.Component):
filepath, recurse = _scripts[path]
for root, dirnames, filenames in os.walk(filepath):
dirnames.sort(reverse=True)
- files = sorted(fnmatch.filter(filenames, "*.js"))
+ files = sorted(fnmatch.filter(filenames, '*.js'))
- order_file = os.path.join(root, ".order")
+ order_file = os.path.join(root, '.order')
if os.path.isfile(order_file):
- with open(order_file, "r") as _file:
+ with open(order_file, 'r') as _file:
for line in _file:
- if line.startswith("+ "):
+ if line.startswith('+ '):
order_filename = line.split()[1]
files.pop(files.index(order_filename))
files.insert(0, order_filename)
# Ensure sub-directory scripts are top of list with root directory scripts bottom.
if dirnames:
- scripts.extend(["js/" + os.path.basename(root) + "/" + f for f in files])
+ scripts.extend(['js/' + os.path.basename(root) + '/' + f for f in files])
else:
- dirpath = os.path.basename(os.path.dirname(root)) + "/" + os.path.basename(root)
+ dirpath = os.path.basename(os.path.dirname(root)) + '/' + os.path.basename(root)
for filename in reversed(files):
- scripts.insert(script_idx, "js/" + dirpath + "/" + filename)
+ scripts.insert(script_idx, 'js/' + dirpath + '/' + filename)
if not recurse:
break
else:
- scripts.append("js/" + path)
+ scripts.append('js/' + path)
return scripts
def getChild(self, path, request): # NOQA
- if hasattr(request, "lookup_path"):
- request.lookup_path += "/" + path
+ if hasattr(request, 'lookup_path'):
+ request.lookup_path += '/' + path
else:
request.lookup_path = path
return self
@@ -375,8 +375,8 @@ class ScriptResource(resource.Resource, component.Component):
def render(self, request):
log.debug("Requested path: '%s'", request.lookup_path)
- for script_type in ("dev", "debug", "normal"):
- scripts = self.__scripts[script_type]["scripts"]
+ for script_type in ('dev', 'debug', 'normal'):
+ scripts = self.__scripts[script_type]['scripts']
for pattern in scripts:
if not request.lookup_path.startswith(pattern):
continue
@@ -392,64 +392,64 @@ class ScriptResource(resource.Resource, component.Component):
log.debug("Serving path: '%s'", path)
mime_type = mimetypes.guess_type(path)
- request.setHeader("content-type", mime_type[0])
- with open(path, "rb") as _file:
+ request.setHeader('content-type', mime_type[0])
+ with open(path, 'rb') as _file:
data = _file.read()
return compress(data, request)
request.setResponseCode(http.NOT_FOUND)
- return "<h1>404 - Not Found</h1>"
+ return '<h1>404 - Not Found</h1>'
class TopLevel(resource.Resource):
addSlash = True
__stylesheets = [
- "css/ext-all-notheme.css",
- "css/ext-extensions.css",
- "css/deluge.css"
+ 'css/ext-all-notheme.css',
+ 'css/ext-extensions.css',
+ 'css/deluge.css'
]
def __init__(self):
resource.Resource.__init__(self)
- self.putChild("css", LookupResource("Css", rpath("css")))
- self.putChild("gettext.js", GetText())
- self.putChild("flag", Flag())
- self.putChild("icons", LookupResource("Icons", rpath("icons")))
- self.putChild("images", LookupResource("Images", rpath("images")))
+ self.putChild('css', LookupResource('Css', rpath('css')))
+ self.putChild('gettext.js', GetText())
+ self.putChild('flag', Flag())
+ self.putChild('icons', LookupResource('Icons', rpath('icons')))
+ self.putChild('images', LookupResource('Images', rpath('images')))
js = ScriptResource()
# configure the dev scripts
- js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "dev")
- js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "dev")
- js.add_script_folder("ext-extensions", rpath("js", "extjs", "ext-extensions"), "dev")
- js.add_script_folder("deluge-all", rpath("js", "deluge-all"), "dev")
+ js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'dev')
+ js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'dev')
+ js.add_script_folder('ext-extensions', rpath('js', 'extjs', 'ext-extensions'), 'dev')
+ js.add_script_folder('deluge-all', rpath('js', 'deluge-all'), 'dev')
# configure the debug scripts
- js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "debug")
- js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "debug")
- js.add_script("ext-extensions-debug.js", rpath("js", "extjs", "ext-extensions-debug.js"), "debug")
- js.add_script("deluge-all-debug.js", rpath("js", "deluge-all-debug.js"), "debug")
+ js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'debug')
+ js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'debug')
+ js.add_script('ext-extensions-debug.js', rpath('js', 'extjs', 'ext-extensions-debug.js'), 'debug')
+ js.add_script('deluge-all-debug.js', rpath('js', 'deluge-all-debug.js'), 'debug')
# configure the normal scripts
- js.add_script("ext-base.js", rpath("js", "extjs", "ext-base.js"))
- js.add_script("ext-all.js", rpath("js", "extjs", "ext-all.js"))
- js.add_script("ext-extensions.js", rpath("js", "extjs", "ext-extensions.js"))
- js.add_script("deluge-all.js", rpath("js", "deluge-all.js"))
+ js.add_script('ext-base.js', rpath('js', 'extjs', 'ext-base.js'))
+ js.add_script('ext-all.js', rpath('js', 'extjs', 'ext-all.js'))
+ js.add_script('ext-extensions.js', rpath('js', 'extjs', 'ext-extensions.js'))
+ js.add_script('deluge-all.js', rpath('js', 'deluge-all.js'))
self.js = js
- self.putChild("js", js)
- self.putChild("json", JSON())
- self.putChild("upload", Upload())
- self.putChild("render", Render())
- self.putChild("themes", static.File(rpath("themes")))
- self.putChild("tracker", Tracker())
-
- theme = component.get("DelugeWeb").config["theme"]
- if not os.path.isfile(rpath("themes", "css", "xtheme-%s.css" % theme)):
- theme = CONFIG_DEFAULTS.get("theme")
- self.__stylesheets.insert(1, "themes/css/xtheme-%s.css" % theme)
+ self.putChild('js', js)
+ self.putChild('json', JSON())
+ self.putChild('upload', Upload())
+ self.putChild('render', Render())
+ self.putChild('themes', static.File(rpath('themes')))
+ self.putChild('tracker', Tracker())
+
+ theme = component.get('DelugeWeb').config['theme']
+ if not os.path.isfile(rpath('themes', 'css', 'xtheme-%s.css' % theme)):
+ theme = CONFIG_DEFAULTS.get('theme')
+ self.__stylesheets.insert(1, 'themes/css/xtheme-%s.css' % theme)
@property
def stylesheets(self):
@@ -478,7 +478,7 @@ class TopLevel(resource.Resource):
self.__debug_scripts.remove(script)
def getChild(self, path, request): # NOQA
- if path == "":
+ if path == '':
return self
else:
return resource.Resource.getChild(self, path, request)
@@ -486,7 +486,7 @@ class TopLevel(resource.Resource):
def getChildWithDefault(self, path, request): # NOQA
# Calculate the request base
header = request.getHeader('x-deluge-base')
- base = header if header else component.get("DelugeWeb").base
+ base = header if header else component.get('DelugeWeb').base
# validate the base parameter
if not base:
@@ -503,37 +503,37 @@ class TopLevel(resource.Resource):
return resource.Resource.getChildWithDefault(self, path, request)
def render(self, request):
- uri_true = ("true", "yes", "1")
- debug_arg = request.args.get("debug", [""])[-1] in uri_true
- dev_arg = request.args.get("dev", [""])[-1] in uri_true
- dev_ver = "dev" in common.get_version()
+ uri_true = ('true', 'yes', '1')
+ debug_arg = request.args.get('debug', [''])[-1] in uri_true
+ dev_arg = request.args.get('dev', [''])[-1] in uri_true
+ dev_ver = 'dev' in common.get_version()
- script_type = "normal"
+ script_type = 'normal'
if debug_arg:
- script_type = "debug"
+ script_type = 'debug'
# Override debug if dev arg or version.
if dev_arg or dev_ver:
- script_type = "dev"
+ script_type = 'dev'
if not self.js.has_script_type_files(script_type):
if not dev_ver:
log.warning("Failed to enable WebUI '%s' mode, script files are missing!", script_type)
# Fallback to checking other types in order and selecting first with files available.
- for alt_script_type in [x for x in ["normal", "debug", "dev"] if x != script_type]:
+ for alt_script_type in [x for x in ['normal', 'debug', 'dev'] if x != script_type]:
if self.js.has_script_type_files(alt_script_type):
script_type = alt_script_type
if not dev_ver:
log.warning("WebUI falling back to '%s' mode.", script_type)
break
- scripts = component.get("Scripts").get_scripts(script_type)
- scripts.insert(0, "gettext.js")
+ scripts = component.get('Scripts').get_scripts(script_type)
+ scripts.insert(0, 'gettext.js')
- template = Template(filename=rpath("index.html"))
- request.setHeader("content-type", "text/html; charset=utf-8")
+ template = Template(filename=rpath('index.html'))
+ request.setHeader('content-type', 'text/html; charset=utf-8')
- web_config = component.get("Web").get_config()
- web_config["base"] = request.base
+ web_config = component.get('Web').get_config()
+ web_config['base'] = request.base
config = dict([(key, web_config[key]) for key in UI_CONFIG_KEYS])
js_config = json.dumps(config)
# Insert the values into 'index.html' and return.
@@ -553,19 +553,19 @@ class DelugeWeb(component.Component):
reactor). If False shares the process and twisted reactor from WebUI plugin or tests.
"""
- component.Component.__init__(self, "DelugeWeb", depend=["Web"])
- self.config = configmanager.ConfigManager("web.conf", defaults=CONFIG_DEFAULTS, file_version=2)
+ component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
+ self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2)
self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
- self.config.register_set_function("language", self._on_language_changed)
+ self.config.register_set_function('language', self._on_language_changed)
self.socket = None
self.top_level = TopLevel()
- self.interface = self.config["interface"]
- self.port = self.config["port"]
- self.https = self.config["https"]
- self.pkey = self.config["pkey"]
- self.cert = self.config["cert"]
- self.base = self.config["base"]
+ self.interface = self.config['interface']
+ self.port = self.config['port']
+ self.https = self.config['https']
+ self.pkey = self.config['pkey']
+ self.cert = self.config['cert']
+ self.base = self.config['base']
if options:
self.interface = options.interface if options.interface else self.interface
@@ -576,7 +576,7 @@ class DelugeWeb(component.Component):
elif options.no_ssl:
self.https = False
- if self.base != "/":
+ if self.base != '/':
# Strip away slashes and serve on the base path as well as root path
self.top_level.putChild(self.base.strip('/'), self.top_level)
@@ -598,7 +598,7 @@ class DelugeWeb(component.Component):
def install_signal_handlers(self):
# Since twisted assigns itself all the signals may as well make
# use of it.
- reactor.addSystemEventTrigger("after", "shutdown", self.shutdown)
+ reactor.addSystemEventTrigger('after', 'shutdown', self.shutdown)
# Twisted doesn't handle windows specific signals so we still
# need to attach to those to handle the close correctly.
@@ -607,7 +607,7 @@ class DelugeWeb(component.Component):
from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT
def win_handler(ctrl_type):
- log.debug("ctrl type: %s", ctrl_type)
+ log.debug('ctrl type: %s', ctrl_type)
if ctrl_type == CTRL_CLOSE_EVENT or \
ctrl_type == CTRL_SHUTDOWN_EVENT:
self.shutdown()
@@ -619,27 +619,27 @@ class DelugeWeb(component.Component):
Start the DelugeWeb server
"""
if self.socket:
- log.warn("DelugeWeb is already running and cannot be started")
+ log.warn('DelugeWeb is already running and cannot be started')
return
- log.info("Starting webui server at PID %s", os.getpid())
+ log.info('Starting webui server at PID %s', os.getpid())
if self.https:
self.start_ssl()
else:
self.start_normal()
- component.get("Web").enable()
+ component.get('Web').enable()
if self.daemon:
reactor.run()
def start_normal(self):
self.socket = reactor.listenTCP(self.port, self.site, interface=self.interface)
- log.info("Serving at http://%s:%s%s", self.interface, self.port, self.base)
+ log.info('Serving at http://%s:%s%s', self.interface, self.port, self.base)
def start_ssl(self):
check_ssl_keys()
- log.debug("Enabling SSL with PKey: %s, Cert: %s", self.pkey, self.cert)
+ log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert)
with open(configmanager.get_config_dir(self.cert)) as cert:
certificate = Certificate.loadPEM(cert.read()).original
@@ -649,17 +649,17 @@ class DelugeWeb(component.Component):
options.getContext().set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3)
self.socket = reactor.listenSSL(self.port, self.site, options, interface=self.interface)
- log.info("Serving at https://%s:%s%s", self.interface, self.port, self.base)
+ log.info('Serving at https://%s:%s%s', self.interface, self.port, self.base)
def stop(self):
- log.info("Shutting down webserver")
+ log.info('Shutting down webserver')
try:
- component.get("Web").disable()
+ component.get('Web').disable()
except KeyError:
pass
self.plugins.disable_plugins()
- log.debug("Saving configuration file")
+ log.debug('Saving configuration file')
self.config.save()
if self.socket:
@@ -676,16 +676,16 @@ class DelugeWeb(component.Component):
reactor.stop()
def _migrate_config_1_to_2(self, config):
- config["language"] = CONFIG_DEFAULTS["language"]
+ config['language'] = CONFIG_DEFAULTS['language']
return config
-if __name__ == "__builtin__":
+if __name__ == '__builtin__':
deluge_web = DelugeWeb()
- application = service.Application("DelugeWeb")
+ application = service.Application('DelugeWeb')
sc = service.IServiceCollection(application)
i = internet.TCPServer(deluge_web.port, deluge_web.site)
i.setServiceParent(sc)
-elif __name__ == "__main__":
+elif __name__ == '__main__':
deluge_web = DelugeWeb()
deluge_web.start()
diff --git a/deluge/ui/web/web.py b/deluge/ui/web/web.py
index dd3aab5b7..38c725aed 100644
--- a/deluge/ui/web/web.py
+++ b/deluge/ui/web/web.py
@@ -24,18 +24,18 @@ class Web(UI):
cmd_description = """Web-based user interface (http://localhost:8112)"""
def __init__(self, *args, **kwargs):
- super(Web, self).__init__("web", *args, description="Starts the Deluge Web interface", **kwargs)
+ super(Web, self).__init__('web', *args, description='Starts the Deluge Web interface', **kwargs)
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("--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"))
+ 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('--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()
@property
@@ -53,7 +53,7 @@ class Web(UI):
self.server.install_signal_handlers()
self.server.start()
except CannotListenError as ex:
- log.error("%s \nCheck that deluge-web or webui plugin is not already running.", ex)
+ log.error('%s \nCheck that deluge-web or webui plugin is not already running.', ex)
except Exception as ex:
log.exception(ex)
raise
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 2b9aae06f..7b133c67a 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -23,8 +23,8 @@ except ImportError:
get_version = None
# Must add these for autodoc to import packages successully
-__builtin__.__dict__["_"] = lambda x: x
-__builtin__.__dict__["_n"] = lambda s, p, n: s if n == 1 else p
+__builtin__.__dict__['_'] = lambda x: x
+__builtin__.__dict__['_n'] = lambda s, p, n: s if n == 1 else p
# If your extensions are in another directory, add it here. If the directory
# is relative to the documentation root, use os.path.abspath to make it
@@ -55,7 +55,7 @@ class Mock(object):
MOCK_MODULES = ['deluge.ui.gtkui.gtkui', 'deluge._libtorrent',
'libtorrent', 'psyco',
- 'pygtk', "gtk", "gobject", "gtk.gdk", "pango", "cairo", "pangocairo", "chardet"]
+ 'pygtk', 'gtk', 'gobject', 'gtk.gdk', 'pango', 'cairo', 'pangocairo', 'chardet']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
@@ -89,7 +89,7 @@ copyright = '2008-%s, Deluge Team' % current_year
if get_version:
version = get_version(prefix='deluge-', suffix='.dev0')
else:
- version = pkg_resources.require("Deluge")[0].version
+ version = pkg_resources.require('Deluge')[0].version
# The full version, including alpha/beta/rc tags.
release = version
diff --git a/gen_web_gettext.py b/gen_web_gettext.py
index 69dd91d8e..44654cb4c 100755
--- a/gen_web_gettext.py
+++ b/gen_web_gettext.py
@@ -42,11 +42,11 @@ def check_missing_markup(js_dir):
except_chars = "' &#"
# A list of strings that should be skipped shuold the match contain them.
- skip = ["HTTP:"]
+ skip = ['HTTP:']
# 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 = {}
@@ -100,7 +100,7 @@ if __name__ == '__main__':
print("Created '%s'" % gettext_fname)
missed_markup = check_missing_markup(WEBUI_JS_DIR)
if missed_markup:
- print("Possible missed text for translation markup:")
+ print('Possible missed text for translation markup:')
for text, filenames in missed_markup.iteritems():
for filename_lineno in filenames:
- print("{0:<58} {1}".format(':'.join(filename_lineno), text))
+ print('{0:<58} {1}'.format(':'.join(filename_lineno), text))
diff --git a/generate_pot.py b/generate_pot.py
index b46baee77..0a871e1e1 100755
--- a/generate_pot.py
+++ b/generate_pot.py
@@ -23,46 +23,46 @@ from version import get_version
# Paths to exclude
EXCLUSIONS = [
- "deluge/scripts",
- "deluge/i18n",
- "deluge/tests",
+ 'deluge/scripts',
+ 'deluge/i18n',
+ 'deluge/tests',
]
-WEBUI_JS_DIR = "deluge/ui/web/js/deluge-all"
-WEBUI_RENDER_DIR = "deluge/ui/web/render"
-INFILES_LIST = "infiles.list"
-POT_FILEPATH = os.path.join("deluge", "i18n", "deluge.pot")
+WEBUI_JS_DIR = 'deluge/ui/web/js/deluge-all'
+WEBUI_RENDER_DIR = 'deluge/ui/web/render'
+INFILES_LIST = 'infiles.list'
+POT_FILEPATH = os.path.join('deluge', 'i18n', 'deluge.pot')
-RE_EXC_PLUGIN_BUILD = re.compile("deluge\\/plugins\\/.*\\/build")
+RE_EXC_PLUGIN_BUILD = re.compile('deluge\\/plugins\\/.*\\/build')
xgettext_cmd = [
- "xgettext",
- "--from-code=UTF-8",
- "-kN_:1",
- "-f%s" % INFILES_LIST,
- "-o%s" % POT_FILEPATH,
- "--package-name=%s" % "Deluge",
- "--copyright-holder=%s" % "Deluge Team",
- "--package-version=%s" % get_version(prefix='deluge-', suffix='.dev0'),
- "--msgid-bugs-address=%s" % "http://deluge-torrent.org",
+ 'xgettext',
+ '--from-code=UTF-8',
+ '-kN_:1',
+ '-f%s' % INFILES_LIST,
+ '-o%s' % POT_FILEPATH,
+ '--package-name=%s' % 'Deluge',
+ '--copyright-holder=%s' % 'Deluge Team',
+ '--package-version=%s' % get_version(prefix='deluge-', suffix='.dev0'),
+ '--msgid-bugs-address=%s' % 'http://deluge-torrent.org',
]
to_translate = []
-for (dirpath, dirnames, filenames) in os.walk("deluge"):
+for (dirpath, dirnames, filenames) in os.walk('deluge'):
for filename in filenames:
if dirpath not in EXCLUSIONS and not RE_EXC_PLUGIN_BUILD.match(dirpath):
filepath = os.path.join(dirpath, filename)
- if os.path.splitext(filepath)[1] in (".py", ".glade"):
+ if os.path.splitext(filepath)[1] in ('.py', '.glade'):
to_translate.append(filepath)
- elif filename.endswith(".in"):
- call(["intltool-extract", "--quiet", "--type=gettext/ini", filepath])
- to_translate.append(filepath + ".h")
- elif filename.endswith(".ui"):
- call(["intltool-extract", "--quiet", "--type=gettext/glade", filepath])
- to_translate.append(filepath + ".h")
-
-with open(INFILES_LIST, "w") as f:
+ elif filename.endswith('.in'):
+ call(['intltool-extract', '--quiet', '--type=gettext/ini', filepath])
+ to_translate.append(filepath + '.h')
+ elif filename.endswith('.ui'):
+ call(['intltool-extract', '--quiet', '--type=gettext/glade', filepath])
+ to_translate.append(filepath + '.h')
+
+with open(INFILES_LIST, 'w') as f:
for line in to_translate:
- f.write(line + "\n")
+ f.write(line + '\n')
# Create pot file from file list
call(xgettext_cmd)
@@ -71,42 +71,42 @@ call(xgettext_cmd)
js_to_translate = []
for (dirpath, dirnames, filenames) in os.walk(WEBUI_JS_DIR):
for filename in filenames:
- if os.path.splitext(filename)[1] == ".js":
+ if os.path.splitext(filename)[1] == '.js':
js_to_translate.append(os.path.join(dirpath, filename))
# find render html files
for (dirpath, dirnames, filenames) in os.walk(WEBUI_RENDER_DIR):
for filename in filenames:
- if os.path.splitext(filename)[1] == ".html":
+ if os.path.splitext(filename)[1] == '.html':
js_to_translate.append(os.path.join(dirpath, filename))
-with open(INFILES_LIST, "w") as f:
+with open(INFILES_LIST, 'w') as f:
for line in js_to_translate:
- f.write(line + "\n")
+ f.write(line + '\n')
# Force xgettext language to parse javascript and update pot file
# Note: For javascript files xgettext will parse comments, so single apostrophes or quotes are
# flagged as a 'warning: untermined string'. Either ignore warning or edit javascript comment.
-call(xgettext_cmd + ["--language=Python", "-j"])
+call(xgettext_cmd + ['--language=Python', '-j'])
# Replace YEAR and PACKAGE in the copyright message
-with open(POT_FILEPATH, "r") as f:
+with open(POT_FILEPATH, 'r') as f:
lines = f.readlines()
-with open(POT_FILEPATH, "w") as f:
+with open(POT_FILEPATH, 'w') as f:
for line in lines:
- if "YEAR" in line:
- line = line.replace("YEAR", str(datetime.now().year))
- elif "PACKAGE" in line:
- line = line.replace("PACKAGE", "Deluge")
+ if 'YEAR' in line:
+ line = line.replace('YEAR', str(datetime.now().year))
+ elif 'PACKAGE' in line:
+ line = line.replace('PACKAGE', 'Deluge')
f.write(line)
# Clean up temp files
os.remove(INFILES_LIST)
for filepath in to_translate:
- if filepath.endswith(".h"):
+ if filepath.endswith('.h'):
os.remove(filepath)
# Update web js gettext
create_gettext_js(WEBUI_JS_DIR)
-print("Created %s and updated gettext.js" % POT_FILEPATH)
+print('Created %s and updated gettext.js' % POT_FILEPATH)
diff --git a/msgfmt.py b/msgfmt.py
index 2e4a11553..057b253e8 100755
--- a/msgfmt.py
+++ b/msgfmt.py
@@ -34,7 +34,7 @@ import os
import struct
import sys
-__version__ = "1.1"
+__version__ = '1.1'
MESSAGES = {}
@@ -87,14 +87,14 @@ def generate():
koffsets += [l1, o1 + keystart]
voffsets += [l2, o2 + valuestart]
offsets = koffsets + voffsets
- output = struct.pack("Iiiiiii",
+ output = struct.pack('Iiiiiii',
0x950412de, # Magic
0, # Version
len(keys), # # of entries
7 * 4, # start of key index
7 * 4 + len(keys) * 8, # start of value index
0, 0) # size and offset of hash table
- output += array.array("i", offsets).tostring()
+ output += array.array('i', offsets).tostring()
output += ids
output += strs
return output
@@ -183,7 +183,7 @@ def make(filename, outfile):
output = generate()
try:
- with open(outfile, "wb") as _file:
+ with open(outfile, 'wb') as _file:
_file.write(output)
except IOError as msg:
print(msg, file=sys.stderr)
@@ -202,7 +202,7 @@ def main():
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-V', '--version'):
- print("msgfmt.py", __version__, file=sys.stderr)
+ print('msgfmt.py', __version__, file=sys.stderr)
sys.exit(0)
elif opt in ('-o', '--output-file'):
outfile = arg
diff --git a/packaging/win32/deluge-bbfreeze.py b/packaging/win32/deluge-bbfreeze.py
index 4807e5269..e67399f50 100644
--- a/packaging/win32/deluge-bbfreeze.py
+++ b/packaging/win32/deluge-bbfreeze.py
@@ -31,10 +31,10 @@ class VersionInfo(object):
comments=None, company=None, description=None,
_copyright=None, trademarks=None, product=None, dll=False,
debug=False, verbose=True):
- parts = version.split(".")
+ parts = version.split('.')
while len(parts) < 4:
- parts.append("0")
- self.version = ".".join(parts)
+ parts.append('0')
+ self.version = '.'.join(parts)
self.internal_name = internalname
self.original_filename = originalfilename
self.comments = comments
@@ -48,31 +48,31 @@ class VersionInfo(object):
self.verbose = verbose
DEBUG = False
-if len(sys.argv) == 2 and sys.argv[1].lower() == "debug":
+if len(sys.argv) == 2 and sys.argv[1].lower() == 'debug':
DEBUG = True
# Get build_version from installed deluge.
build_version = deluge.common.get_version()
python_path = os.path.dirname(sys.executable)
-if python_path.endswith("Scripts"):
+if python_path.endswith('Scripts'):
python_path = python_path[:-8]
-gtk_root = os.path.join(gtk.__path__[0], "..", "runtime")
-build_dir = os.path.join("build-win32", "deluge-bbfreeze-" + build_version)
+gtk_root = os.path.join(gtk.__path__[0], '..', 'runtime')
+build_dir = os.path.join('build-win32', 'deluge-bbfreeze-' + build_version)
if DEBUG:
- print("Python Path: %s" % python_path)
- print("Gtk Path: %s" % gtk_root)
- print("bbfreeze Output Path: %s" % build_dir)
+ print('Python Path: %s' % python_path)
+ print('Gtk Path: %s' % gtk_root)
+ print('bbfreeze Output Path: %s' % build_dir)
-print("Freezing Deluge %s..." % build_version)
+print('Freezing Deluge %s...' % build_version)
# Disable printing to console for bbfreezing.
if not DEBUG:
- sys.stdout = open(os.devnull, "w")
+ sys.stdout = open(os.devnull, 'w')
# Include python modules not picked up automatically by bbfreeze.
-includes = ("libtorrent", "cairo", "pangocairo", "atk", "pango", "twisted.internet.utils",
- "gio", "gzip", "email.mime.multipart", "email.mime.text", "_cffi_backend")
-excludes = ("numpy", "OpenGL", "psyco", "win32ui", "unittest")
+includes = ('libtorrent', 'cairo', 'pangocairo', 'atk', 'pango', 'twisted.internet.utils',
+ 'gio', 'gzip', 'email.mime.multipart', 'email.mime.text', '_cffi_backend')
+excludes = ('numpy', 'OpenGL', 'psyco', 'win32ui', 'unittest')
def recipe_gtk_override(mf):
@@ -83,30 +83,30 @@ bbfreeze.recipes.recipe_gtk_and_friends = recipe_gtk_override
# Workaround for "ImportError: The 'packaging' package is required" with setuptools > 18.8.
# (https://github.com/pypa/setuptools/issues/517)
-bbfreeze.recipes.recipe_pkg_resources = bbfreeze.recipes.include_whole_package("pkg_resources")
+bbfreeze.recipes.recipe_pkg_resources = bbfreeze.recipes.include_whole_package('pkg_resources')
fzr = bbfreeze.Freezer(build_dir, includes=includes, excludes=excludes)
fzr.include_py = False
-fzr.setIcon(os.path.join(os.path.dirname(deluge.common.__file__), "ui", "data", "pixmaps", "deluge.ico"))
+fzr.setIcon(os.path.join(os.path.dirname(deluge.common.__file__), 'ui', 'data', 'pixmaps', 'deluge.ico'))
# TODO: Can/should we grab the script list from setup.py entry_points somehow.
# Hide cmd console popup for these console entries force gui_script True.
-force_gui = ["deluge-web", "deluged"]
+force_gui = ['deluge-web', 'deluged']
for force_script in force_gui:
- script_path = os.path.join(python_path, "Scripts", force_script + "-script.py")
- shutil.copy(script_path, script_path.replace("script", "debug-script"))
+ script_path = os.path.join(python_path, 'Scripts', force_script + '-script.py')
+ shutil.copy(script_path, script_path.replace('script', 'debug-script'))
script_list = []
-for script in glob.glob(os.path.join(python_path, "Scripts\\deluge*-script.py*")):
+for script in glob.glob(os.path.join(python_path, 'Scripts\\deluge*-script.py*')):
# Copy the scripts to remove the '-script' suffix before adding to freezer.
- new_script = script.replace("-script", "")
+ new_script = script.replace('-script', '')
shutil.copy(script, new_script)
gui_script = False
script_splitext = os.path.splitext(os.path.basename(new_script))
- if script_splitext[1] == ".pyw" or script_splitext[0] in force_gui:
+ if script_splitext[1] == '.pyw' or script_splitext[0] in force_gui:
gui_script = True
try:
fzr.addScript(new_script, gui_only=gui_script)
@@ -122,10 +122,10 @@ for script in script_list:
os.remove(script)
# Exclude files which are already included in GTK or Windows. Also exclude unneeded pygame dlls.
-excludeDlls = ("MSIMG32.dll", "MSVCR90.dll", "MSVCP90.dll", "MSVCR120.dll",
- "POWRPROF.dll", "DNSAPI.dll", "USP10.dll", "MPR.dll",
- "jpeg.dll", "libfreetype-6.dll", "libpng12-0.dll", "libtiff.dll",
- "SDL_image.dll", "SDL_ttf.dll")
+excludeDlls = ('MSIMG32.dll', 'MSVCR90.dll', 'MSVCP90.dll', 'MSVCR120.dll',
+ 'POWRPROF.dll', 'DNSAPI.dll', 'USP10.dll', 'MPR.dll',
+ 'jpeg.dll', 'libfreetype-6.dll', 'libpng12-0.dll', 'libtiff.dll',
+ 'SDL_image.dll', 'SDL_ttf.dll')
for exclude_dll in excludeDlls:
try:
os.remove(os.path.join(build_dir, exclude_dll))
@@ -151,12 +151,12 @@ shutil.copytree(gtk_locale, os.path.join(build_dir, 'share/locale'), ignore=igno
# Copy gtk theme files.
theme_include_list = [
- [gtk_root, "share/icons/hicolor/index.theme"],
- [gtk_root, "lib/gtk-2.0/2.10.0/engines"],
- [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"]
+ [gtk_root, 'share/icons/hicolor/index.theme'],
+ [gtk_root, 'lib/gtk-2.0/2.10.0/engines'],
+ [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']
]
for path_root, path in theme_include_list:
full_path = os.path.join(path_root, path)
@@ -172,14 +172,14 @@ for path_root, path in theme_include_list:
# Add version information to exe files.
for script in script_list:
- script_exe = os.path.splitext(os.path.basename(script))[0] + ".exe"
+ script_exe = os.path.splitext(os.path.basename(script))[0] + '.exe'
# Don't add to dev build versions.
if not re.search('[a-zA-Z_-]', build_version):
versionInfo = VersionInfo(build_version,
- description="Deluge Bittorrent Client",
- company="Deluge Team",
- product="Deluge",
- _copyright="Deluge Team")
+ description='Deluge Bittorrent Client',
+ company='Deluge Team',
+ product='Deluge',
+ _copyright='Deluge Team')
stamp(os.path.join(build_dir, script_exe), versionInfo)
# Copy version info to file for nsis script.
diff --git a/setup.py b/setup.py
index 9bc06e39a..bee641b13 100755
--- a/setup.py
+++ b/setup.py
@@ -38,7 +38,7 @@ def windows_check():
def osx_check():
- return platform.system() == "Darwin"
+ return platform.system() == 'Darwin'
desktop_data = 'deluge/ui/data/share/applications/deluge.desktop'
@@ -64,7 +64,7 @@ class BuildDocs(BuildDoc):
description = 'Build the documentation'
def run(self):
- print("Generating module documentation...")
+ print('Generating module documentation...')
os.system('sphinx-apidoc --force -o docs/source/modules/ deluge deluge/plugins')
BuildDoc.run(self)
@@ -409,7 +409,7 @@ _version = get_version(prefix='deluge-', suffix='.dev0')
if 'dev' in _version:
_exclude_package_data = {}
else:
- _exclude_package_data = {"deluge.ui.web": ["*-debug.js", '*-debug.css']}
+ _exclude_package_data = {'deluge.ui.web': ['*-debug.js', '*-debug.css']}
# Main setup
setup(
diff --git a/version.py b/version.py
index bdda61653..7881ab224 100755
--- a/version.py
+++ b/version.py
@@ -36,26 +36,26 @@ from __future__ import print_function
import os
from subprocess import PIPE, Popen
-__all__ = ("get_version")
+__all__ = ('get_version')
-VERSION_FILE = os.path.join(os.path.dirname(__file__), "RELEASE-VERSION")
+VERSION_FILE = os.path.join(os.path.dirname(__file__), 'RELEASE-VERSION')
-def call_git_describe(prefix="", suffix=""):
- cmd = "git describe --tags --match %s[0-9]*" % prefix
+def call_git_describe(prefix='', suffix=''):
+ cmd = 'git describe --tags --match %s[0-9]*' % prefix
try:
output = Popen(cmd.split(), stdout=PIPE, stderr=PIPE).communicate()
- version = output[0].decode("utf-8").strip().replace(prefix, "")
- if "-" in version:
- version = ".dev".join(version.replace(suffix, "").split("-")[:2])
+ version = output[0].decode('utf-8').strip().replace(prefix, '')
+ if '-' in version:
+ version = '.dev'.join(version.replace(suffix, '').split('-')[:2])
return version
except OSError:
return None
-def get_version(prefix="", suffix=""):
+def get_version(prefix='', suffix=''):
try:
- with open(VERSION_FILE, "r") as f:
+ with open(VERSION_FILE, 'r') as f:
release_version = f.readline().strip()
except IOError:
release_version = None
@@ -65,13 +65,13 @@ def get_version(prefix="", suffix=""):
if not version:
version = release_version
if not version:
- raise ValueError("Cannot find the version number!")
+ raise ValueError('Cannot find the version number!')
if version != release_version:
- with open(VERSION_FILE, "w") as f:
- f.write("%s\n" % version)
+ with open(VERSION_FILE, 'w') as f:
+ f.write('%s\n' % version)
return version
-if __name__ == "__main__":
- print(get_version(prefix="deluge-", suffix=".dev0"))
+if __name__ == '__main__':
+ print(get_version(prefix='deluge-', suffix='.dev0'))