mirror of
https://git.deluge-torrent.org/deluge
synced 2025-08-03 06:58:42 +00:00
[Lint] [Plugins] Fix all pylint issues
This commit is contained in:
parent
9237c931b2
commit
42c3580bf2
20 changed files with 148 additions and 154 deletions
|
@ -170,34 +170,35 @@ class Core(CorePluginBase):
|
||||||
|
|
||||||
def split_magnets(self, filename):
|
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:
|
try:
|
||||||
_file = open(filename, "r")
|
with open(filename, "r") as _file:
|
||||||
|
for line in _file:
|
||||||
|
line = line.strip()
|
||||||
|
if line:
|
||||||
|
magnets.append(line)
|
||||||
except IOError as ex:
|
except IOError as ex:
|
||||||
log.warning("Unable to open %s: %s", filename, ex)
|
log.warning("Unable to open %s: %s", filename, ex)
|
||||||
raise ex
|
|
||||||
else:
|
if len(magnets) < 2:
|
||||||
magnets = list(filter(len, _file.readlines()))
|
return []
|
||||||
_file.close()
|
|
||||||
if len(magnets) < 2:
|
n = 0
|
||||||
return
|
path = filename.rsplit(os.sep, 1)[0]
|
||||||
n = 0
|
for magnet in magnets:
|
||||||
path = filename.rsplit(os.sep, 1)[0]
|
for part in magnet.split("&"):
|
||||||
for magnet in magnets:
|
if part.startswith("dn="):
|
||||||
for part in magnet.split("&"):
|
mname = os.sep.join([path, part[3:] + ".magnet"])
|
||||||
if part.startswith("dn="):
|
break
|
||||||
mname = os.sep.join([path, part[3:] + ".magnet"])
|
else:
|
||||||
break
|
mname = ".".join([filename, str(n), "magnet"])
|
||||||
else:
|
n += 1
|
||||||
mname = ".".join([filename, str(n), "magnet"])
|
try:
|
||||||
n += 1
|
with open(mname, "w") as _mfile:
|
||||||
try:
|
|
||||||
_mfile = open(mname, "w")
|
|
||||||
except IOError as ex:
|
|
||||||
log.warning("Unable to open %s: %s", mname, ex)
|
|
||||||
else:
|
|
||||||
_mfile.write(magnet)
|
_mfile.write(magnet)
|
||||||
_mfile.close()
|
except IOError as ex:
|
||||||
return magnets
|
log.warning("Unable to open %s: %s", mname, ex)
|
||||||
|
return magnets
|
||||||
|
|
||||||
def update_watchdir(self, watchdir_id):
|
def update_watchdir(self, watchdir_id):
|
||||||
"""Check the watch folder for new torrents to add."""
|
"""Check the watch folder for new torrents to add."""
|
||||||
|
@ -238,8 +239,7 @@ class Core(CorePluginBase):
|
||||||
if os.path.isdir(filepath):
|
if os.path.isdir(filepath):
|
||||||
# Skip directories
|
# Skip directories
|
||||||
continue
|
continue
|
||||||
elif os.path.splitext(filename)[1] == ".magnet" and \
|
elif os.path.splitext(filename)[1] == ".magnet" and self.split_magnets(filepath):
|
||||||
self.split_magnets(filepath):
|
|
||||||
os.remove(filepath)
|
os.remove(filepath)
|
||||||
|
|
||||||
for filename in os.listdir(watchdir["abspath"]):
|
for filename in os.listdir(watchdir["abspath"]):
|
||||||
|
@ -397,8 +397,10 @@ class Core(CorePluginBase):
|
||||||
return opts
|
return opts
|
||||||
|
|
||||||
@export
|
@export
|
||||||
def add(self, options={}):
|
def add(self, options=None):
|
||||||
"""Add a watch folder."""
|
"""Add a watch folder."""
|
||||||
|
if options is None:
|
||||||
|
options = {}
|
||||||
options = self._make_unicode(options)
|
options = self._make_unicode(options)
|
||||||
abswatchdir = os.path.abspath(options["path"])
|
abswatchdir = os.path.abspath(options["path"])
|
||||||
check_input(os.path.isdir(abswatchdir), _("Path does not exist."))
|
check_input(os.path.isdir(abswatchdir), _("Path does not exist."))
|
||||||
|
|
|
@ -33,7 +33,7 @@ class IncompatibleOption(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class OptionsDialog():
|
class OptionsDialog(object):
|
||||||
spin_ids = ["max_download_speed", "max_upload_speed", "stop_ratio"]
|
spin_ids = ["max_download_speed", "max_upload_speed", "stop_ratio"]
|
||||||
spin_int_ids = ["max_upload_slots", "max_connections"]
|
spin_int_ids = ["max_upload_slots", "max_connections"]
|
||||||
chk_ids = ["stop_at_ratio", "remove_at_ratio", "move_completed",
|
chk_ids = ["stop_at_ratio", "remove_at_ratio", "move_completed",
|
||||||
|
@ -44,7 +44,9 @@ class OptionsDialog():
|
||||||
self.labels = gtk.ListStore(str)
|
self.labels = gtk.ListStore(str)
|
||||||
self.core_config = {}
|
self.core_config = {}
|
||||||
|
|
||||||
def show(self, options={}, watchdir_id=None):
|
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({
|
self.glade.signal_autoconnect({
|
||||||
"on_opts_add": self.on_add,
|
"on_opts_add": self.on_add,
|
||||||
|
@ -104,12 +106,12 @@ class OptionsDialog():
|
||||||
label_widget.set_text_column(0)
|
label_widget.set_text_column(0)
|
||||||
self.glade.get_widget('label_toggle').set_active(options.get('label_toggle', False))
|
self.glade.get_widget('label_toggle').set_active(options.get('label_toggle', False))
|
||||||
|
|
||||||
for id in self.spin_ids + self.spin_int_ids:
|
for spin_id in self.spin_ids + self.spin_int_ids:
|
||||||
self.glade.get_widget(id).set_value(options.get(id, 0))
|
self.glade.get_widget(spin_id).set_value(options.get(spin_id, 0))
|
||||||
self.glade.get_widget(id + "_toggle").set_active(options.get(id + "_toggle", False))
|
self.glade.get_widget(spin_id + "_toggle").set_active(options.get(spin_id + "_toggle", False))
|
||||||
for id in self.chk_ids:
|
for chk_id in self.chk_ids:
|
||||||
self.glade.get_widget(id).set_active(bool(options.get(id, True)))
|
self.glade.get_widget(chk_id).set_active(bool(options.get(chk_id, True)))
|
||||||
self.glade.get_widget(id + "_toggle").set_active(options.get(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):
|
if not options.get('add_paused', True):
|
||||||
self.glade.get_widget('isnt_add_paused').set_active(True)
|
self.glade.get_widget('isnt_add_paused').set_active(True)
|
||||||
if not options.get('queue_to_top', True):
|
if not options.get('queue_to_top', True):
|
||||||
|
@ -174,18 +176,18 @@ class OptionsDialog():
|
||||||
log.debug("Got Accounts")
|
log.debug("Got Accounts")
|
||||||
selected_iter = None
|
selected_iter = None
|
||||||
for account in accounts:
|
for account in accounts:
|
||||||
iter = self.accounts.append()
|
acc_iter = self.accounts.append()
|
||||||
self.accounts.set_value(
|
self.accounts.set_value(
|
||||||
iter, 0, account['username']
|
acc_iter, 0, account['username']
|
||||||
)
|
)
|
||||||
if account['username'] == owner:
|
if account['username'] == owner:
|
||||||
selected_iter = iter
|
selected_iter = acc_iter
|
||||||
self.glade.get_widget('OwnerCombobox').set_active_iter(selected_iter)
|
self.glade.get_widget('OwnerCombobox').set_active_iter(selected_iter)
|
||||||
|
|
||||||
def on_accounts_failure(failure):
|
def on_accounts_failure(failure):
|
||||||
log.debug("Failed to get accounts!!! %s", failure)
|
log.debug("Failed to get accounts!!! %s", failure)
|
||||||
iter = self.accounts.append()
|
acc_iter = self.accounts.append()
|
||||||
self.accounts.set_value(iter, 0, client.get_auth_user())
|
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_active(0)
|
||||||
self.glade.get_widget('OwnerCombobox').set_sensitive(False)
|
self.glade.get_widget('OwnerCombobox').set_sensitive(False)
|
||||||
|
|
||||||
|
@ -214,8 +216,8 @@ class OptionsDialog():
|
||||||
on_accounts, options.get('owner', client.get_auth_user())
|
on_accounts, options.get('owner', client.get_auth_user())
|
||||||
).addErrback(on_accounts_failure)
|
).addErrback(on_accounts_failure)
|
||||||
else:
|
else:
|
||||||
iter = self.accounts.append()
|
acc_iter = self.accounts.append()
|
||||||
self.accounts.set_value(iter, 0, client.get_auth_user())
|
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_active(0)
|
||||||
self.glade.get_widget('OwnerCombobox').set_sensitive(False)
|
self.glade.get_widget('OwnerCombobox').set_sensitive(False)
|
||||||
|
|
||||||
|
@ -225,7 +227,8 @@ class OptionsDialog():
|
||||||
'max_upload_speed', 'max_connections',
|
'max_upload_speed', 'max_connections',
|
||||||
'max_upload_slots', 'add_paused', 'auto_managed',
|
'max_upload_slots', 'add_paused', 'auto_managed',
|
||||||
'stop_at_ratio', 'queue_to_top', 'copy_torrent']
|
'stop_at_ratio', 'queue_to_top', 'copy_torrent']
|
||||||
[self.on_toggle_toggled(self.glade.get_widget(x + "_toggle")) for x in maintoggles]
|
for maintoggle in maintoggles:
|
||||||
|
self.on_toggle_toggled(self.glade.get_widget(maintoggle + "_toggle"))
|
||||||
|
|
||||||
def on_toggle_toggled(self, tb):
|
def on_toggle_toggled(self, tb):
|
||||||
toggle = str(tb.name).replace("_toggle", "")
|
toggle = str(tb.name).replace("_toggle", "")
|
||||||
|
@ -327,15 +330,15 @@ class OptionsDialog():
|
||||||
'delete_copy_torrent_toggle', 'seed_mode']:
|
'delete_copy_torrent_toggle', 'seed_mode']:
|
||||||
options[key] = self.glade.get_widget(key).get_active()
|
options[key] = self.glade.get_widget(key).get_active()
|
||||||
|
|
||||||
for id in self.spin_ids:
|
for spin_id in self.spin_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_value()
|
options[spin_id] = self.glade.get_widget(spin_id).get_value()
|
||||||
options[id + "_toggle"] = self.glade.get_widget(id + "_toggle").get_active()
|
options[spin_id + "_toggle"] = self.glade.get_widget(spin_id + "_toggle").get_active()
|
||||||
for id in self.spin_int_ids:
|
for spin_int_id in self.spin_int_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_value_as_int()
|
options[spin_int_id] = self.glade.get_widget(spin_int_id).get_value_as_int()
|
||||||
options[id + "_toggle"] = self.glade.get_widget(id + "_toggle").get_active()
|
options[spin_int_id + "_toggle"] = self.glade.get_widget(spin_int_id + "_toggle").get_active()
|
||||||
for id in self.chk_ids:
|
for chk_id in self.chk_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_active()
|
options[chk_id] = self.glade.get_widget(chk_id).get_active()
|
||||||
options[id + "_toggle"] = self.glade.get_widget(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']:
|
if options['copy_torrent_toggle'] and options['path'] == options['copy_torrent']:
|
||||||
raise IncompatibleOption(_("\"Watch Folder\" directory and \"Copy of .torrent"
|
raise IncompatibleOption(_("\"Watch Folder\" directory and \"Copy of .torrent"
|
||||||
|
|
|
@ -212,7 +212,8 @@ class Core(CorePluginBase):
|
||||||
check_period = timedelta(days=self.config["check_after_days"])
|
check_period = timedelta(days=self.config["check_after_days"])
|
||||||
if not self.config["last_update"] or last_update + check_period < datetime.now():
|
if not self.config["last_update"] or last_update + check_period < datetime.now():
|
||||||
update_now = True
|
update_now = True
|
||||||
self.update_timer.running and self.update_timer.stop()
|
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.update_timer.start(
|
||||||
self.config["check_after_days"] * 24 * 60 * 60, update_now
|
self.config["check_after_days"] * 24 * 60 * 60, update_now
|
||||||
|
|
|
@ -6,6 +6,7 @@
|
||||||
# the additional special exception to link portions of this program with the OpenSSL library.
|
# the additional special exception to link portions of this program with the OpenSSL library.
|
||||||
# See LICENSE for more details.
|
# See LICENSE for more details.
|
||||||
#
|
#
|
||||||
|
# pylint: disable=redefined-builtin
|
||||||
|
|
||||||
import bz2
|
import bz2
|
||||||
import gzip
|
import gzip
|
||||||
|
|
|
@ -41,16 +41,16 @@ def detect_compression(filename):
|
||||||
|
|
||||||
|
|
||||||
def detect_format(filename, compression=""):
|
def detect_format(filename, compression=""):
|
||||||
format = ""
|
file_format = ""
|
||||||
for reader in READERS:
|
for reader in READERS:
|
||||||
if create_reader(reader, compression)(filename).is_valid():
|
if create_reader(reader, compression)(filename).is_valid():
|
||||||
format = reader
|
file_format = reader
|
||||||
break
|
break
|
||||||
return format
|
return file_format
|
||||||
|
|
||||||
|
|
||||||
def create_reader(format, compression=""):
|
def create_reader(file_format, compression=""):
|
||||||
reader = READERS.get(format)
|
reader = READERS.get(file_format)
|
||||||
if reader and compression:
|
if reader and compression:
|
||||||
decompressor = DECOMPRESSERS.get(compression)
|
decompressor = DECOMPRESSERS.get(compression)
|
||||||
if decompressor:
|
if decompressor:
|
||||||
|
|
|
@ -217,10 +217,10 @@ class GtkUI(GtkPluginBase):
|
||||||
|
|
||||||
def on_delete_button_clicked(self, widget, treeview):
|
def on_delete_button_clicked(self, widget, treeview):
|
||||||
selection = treeview.get_selection()
|
selection = treeview.get_selection()
|
||||||
model, iter = selection.get_selected()
|
model, selected_iter = selection.get_selected()
|
||||||
if iter:
|
if selected_iter:
|
||||||
# path = model.get_path(iter)[0]
|
# path = model.get_path(iter)[0]
|
||||||
model.remove(iter)
|
model.remove(selected_iter)
|
||||||
|
|
||||||
def populate_whitelist(self, whitelist):
|
def populate_whitelist(self, whitelist):
|
||||||
self.whitelist_model.clear()
|
self.whitelist_model.clear()
|
||||||
|
|
|
@ -10,7 +10,6 @@
|
||||||
import gzip
|
import gzip
|
||||||
import logging
|
import logging
|
||||||
import socket
|
import socket
|
||||||
from exceptions import Exception
|
|
||||||
from struct import unpack
|
from struct import unpack
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
@ -22,7 +21,7 @@ class PGException(Exception):
|
||||||
|
|
||||||
# Incrementally reads PeerGuardian blocklists v1 and v2.
|
# Incrementally reads PeerGuardian blocklists v1 and v2.
|
||||||
# See http://wiki.phoenixlabs.org/wiki/P2B_Format
|
# See http://wiki.phoenixlabs.org/wiki/P2B_Format
|
||||||
class PGReader:
|
class PGReader(object):
|
||||||
|
|
||||||
def __init__(self, filename):
|
def __init__(self, filename):
|
||||||
log.debug("PGReader loading: %s", filename)
|
log.debug("PGReader loading: %s", filename)
|
||||||
|
|
|
@ -21,9 +21,9 @@ class ReaderParseError(Exception):
|
||||||
|
|
||||||
class BaseReader(object):
|
class BaseReader(object):
|
||||||
"""Base reader for blocklist files"""
|
"""Base reader for blocklist files"""
|
||||||
def __init__(self, file):
|
def __init__(self, _file):
|
||||||
"""Creates a new BaseReader given a file"""
|
"""Creates a new BaseReader given a file"""
|
||||||
self.file = file
|
self.file = _file
|
||||||
|
|
||||||
def open(self):
|
def open(self):
|
||||||
"""Opens the associated file for reading"""
|
"""Opens the associated file for reading"""
|
||||||
|
@ -55,13 +55,12 @@ class BaseReader(object):
|
||||||
if not self.is_ignored(line):
|
if not self.is_ignored(line):
|
||||||
try:
|
try:
|
||||||
(start, end) = self.parse(line)
|
(start, end) = self.parse(line)
|
||||||
if not re.match("^(\d{1,3}\.){4}$", start + ".") or \
|
if not re.match(r"^(\d{1,3}\.){4}$", start + ".") or \
|
||||||
not re.match("^(\d{1,3}\.){4}$", end + "."):
|
not re.match(r"^(\d{1,3}\.){4}$", end + "."):
|
||||||
valid = False
|
valid = False
|
||||||
except:
|
except Exception:
|
||||||
valid = False
|
valid = False
|
||||||
finally:
|
break
|
||||||
break
|
|
||||||
blocklist.close()
|
blocklist.close()
|
||||||
return valid
|
return valid
|
||||||
|
|
||||||
|
|
|
@ -40,7 +40,7 @@ if windows_check():
|
||||||
import _winreg
|
import _winreg
|
||||||
try:
|
try:
|
||||||
hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
|
hkey = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
|
||||||
except WindowsError:
|
except WindowsError: # pylint: disable=undefined-variable
|
||||||
pass
|
pass
|
||||||
else:
|
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")
|
||||||
|
@ -82,11 +82,11 @@ else:
|
||||||
".7z": ["7zr", "x"],
|
".7z": ["7zr", "x"],
|
||||||
}
|
}
|
||||||
# Test command exists and if not, remove.
|
# Test command exists and if not, remove.
|
||||||
for cmd in required_cmds:
|
for command in required_cmds:
|
||||||
if not which(cmd):
|
if not which(command):
|
||||||
for k, v in EXTRACT_COMMANDS.items():
|
for k, v in EXTRACT_COMMANDS.items():
|
||||||
if cmd in v[0]:
|
if command in v[0]:
|
||||||
log.warning("%s not found, disabling support for %s", cmd, k)
|
log.warning("%s not found, disabling support for %s", command, k)
|
||||||
del EXTRACT_COMMANDS[k]
|
del EXTRACT_COMMANDS[k]
|
||||||
|
|
||||||
if not EXTRACT_COMMANDS:
|
if not EXTRACT_COMMANDS:
|
||||||
|
@ -120,7 +120,7 @@ class Core(CorePluginBase):
|
||||||
if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS:
|
if file_ext_sec and file_ext_sec + file_ext in EXTRACT_COMMANDS:
|
||||||
file_ext = file_ext_sec + file_ext
|
file_ext = file_ext_sec + file_ext
|
||||||
elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == '.tar':
|
elif file_ext not in EXTRACT_COMMANDS or file_ext_sec == '.tar':
|
||||||
log.warning("Can't extract file with unknown file type: %s" % f["path"])
|
log.warning("Can't extract file with unknown file type: %s", f["path"])
|
||||||
continue
|
continue
|
||||||
cmd = EXTRACT_COMMANDS[file_ext]
|
cmd = EXTRACT_COMMANDS[file_ext]
|
||||||
|
|
||||||
|
|
|
@ -26,7 +26,7 @@ from deluge.plugins.pluginbase import CorePluginBase
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
RE_VALID = re.compile("[a-z0-9_\-\.]*\Z")
|
RE_VALID = re.compile(r"[a-z0-9_\-\.]*\Z")
|
||||||
|
|
||||||
KNOWN_STATES = ['Downloading', 'Seeding', 'Paused', 'Checking', 'Queued', 'Error']
|
KNOWN_STATES = ['Downloading', 'Seeding', 'Paused', 'Checking', 'Queued', 'Error']
|
||||||
STATE = "state"
|
STATE = "state"
|
||||||
|
@ -134,7 +134,7 @@ class Core(CorePluginBase):
|
||||||
"""remove invalid data from config-file"""
|
"""remove invalid data from config-file"""
|
||||||
for torrent_id, label_id in list(self.torrent_labels.iteritems()):
|
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):
|
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]
|
del self.torrent_labels[torrent_id]
|
||||||
|
|
||||||
def clean_initial_config(self):
|
def clean_initial_config(self):
|
||||||
|
|
|
@ -51,11 +51,10 @@ class LabelConfig(object):
|
||||||
client.label.get_config().addCallback(self.cb_global_options)
|
client.label.get_config().addCallback(self.cb_global_options)
|
||||||
|
|
||||||
def cb_global_options(self, options):
|
def cb_global_options(self, options):
|
||||||
log.debug("options=%s" % options)
|
log.debug("options=%s", options)
|
||||||
"""
|
|
||||||
for id in self.chk_ids:
|
# for id in self.chk_ids:
|
||||||
self.glade.get_widget(id).set_active(bool(options[id]))
|
# self.glade.get_widget(id).set_active(bool(options[id]))
|
||||||
"""
|
|
||||||
|
|
||||||
def on_apply_prefs(self):
|
def on_apply_prefs(self):
|
||||||
options = {}
|
options = {}
|
||||||
|
|
|
@ -53,16 +53,16 @@ class LabelSidebarMenu(object):
|
||||||
# hooks:
|
# hooks:
|
||||||
self.menu.connect("show", self.on_show, None)
|
self.menu.connect("show", self.on_show, None)
|
||||||
|
|
||||||
def _add_item(self, id, label, stock):
|
def _add_item(self, item_id, label, stock):
|
||||||
"""I hate glade.
|
"""I hate glade.
|
||||||
id is automatically-added as self.item_<id>
|
id is automatically-added as self.item_<id>
|
||||||
"""
|
"""
|
||||||
func = getattr(self, "on_%s" % id)
|
func = getattr(self, "on_%s" % item_id)
|
||||||
item = gtk.ImageMenuItem(stock)
|
item = gtk.ImageMenuItem(stock)
|
||||||
item.get_children()[0].set_label(label)
|
item.get_children()[0].set_label(label)
|
||||||
item.connect("activate", func)
|
item.connect("activate", func)
|
||||||
self.menu.prepend(item)
|
self.menu.prepend(item)
|
||||||
setattr(self, "item_%s" % id, item)
|
setattr(self, "item_%s" % item_id, item)
|
||||||
self.items.append(item)
|
self.items.append(item)
|
||||||
return item
|
return item
|
||||||
|
|
||||||
|
@ -174,10 +174,10 @@ class OptionsDialog(object):
|
||||||
def load_options(self, options):
|
def load_options(self, options):
|
||||||
log.debug(options.keys())
|
log.debug(options.keys())
|
||||||
|
|
||||||
for id in self.spin_ids + self.spin_int_ids:
|
for spin_id in self.spin_ids + self.spin_int_ids:
|
||||||
self.glade.get_widget(id).set_value(options[id])
|
self.glade.get_widget(spin_id).set_value(options[spin_id])
|
||||||
for id in self.chk_ids:
|
for chk_id in self.chk_ids:
|
||||||
self.glade.get_widget(id).set_active(bool(options[id]))
|
self.glade.get_widget(chk_id).set_active(bool(options[chk_id]))
|
||||||
|
|
||||||
if client.is_localhost():
|
if client.is_localhost():
|
||||||
self.glade.get_widget("move_completed_path").set_filename(options["move_completed_path"])
|
self.glade.get_widget("move_completed_path").set_filename(options["move_completed_path"])
|
||||||
|
@ -196,12 +196,12 @@ class OptionsDialog(object):
|
||||||
"save options.."
|
"save options.."
|
||||||
options = {}
|
options = {}
|
||||||
|
|
||||||
for id in self.spin_ids:
|
for spin_id in self.spin_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_value()
|
options[spin_id] = self.glade.get_widget(spin_id).get_value()
|
||||||
for id in self.spin_int_ids:
|
for spin_int_id in self.spin_int_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_value_as_int()
|
options[spin_int_id] = self.glade.get_widget(spin_int_id).get_value_as_int()
|
||||||
for id in self.chk_ids:
|
for chk_id in self.chk_ids:
|
||||||
options[id] = self.glade.get_widget(id).get_active()
|
options[chk_id] = self.glade.get_widget(chk_id).get_active()
|
||||||
|
|
||||||
if client.is_localhost():
|
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()
|
||||||
|
|
|
@ -34,7 +34,6 @@ class LabelMenu(gtk.MenuItem):
|
||||||
self.items = []
|
self.items = []
|
||||||
|
|
||||||
# attach..
|
# attach..
|
||||||
component.get("MenuBar").torrentmenu
|
|
||||||
self.sub_menu.connect("show", self.on_show, None)
|
self.sub_menu.connect("show", self.on_show, None)
|
||||||
|
|
||||||
def get_torrent_ids(self):
|
def get_torrent_ids(self):
|
||||||
|
@ -57,6 +56,6 @@ class LabelMenu(gtk.MenuItem):
|
||||||
self.show_all()
|
self.show_all()
|
||||||
|
|
||||||
def on_select_label(self, widget=None, label_id=None):
|
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():
|
for torrent_id in self.get_torrent_ids():
|
||||||
client.label.set_torrent(torrent_id, label_id)
|
client.label.set_torrent(torrent_id, label_id)
|
||||||
|
|
|
@ -27,9 +27,9 @@ if "label" not in sclient.get_enabled_plugins():
|
||||||
print("#init labels")
|
print("#init labels")
|
||||||
try:
|
try:
|
||||||
sclient.label_remove("test")
|
sclient.label_remove("test")
|
||||||
except:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
id = sclient.get_session_state()[0]
|
sess_id = sclient.get_session_state()[0]
|
||||||
|
|
||||||
print("#add")
|
print("#add")
|
||||||
sclient.label_add("test")
|
sclient.label_add("test")
|
||||||
|
@ -41,10 +41,10 @@ print(sclient.get_torrents_status({"label": "test"}, "name"))
|
||||||
|
|
||||||
print("#set options")
|
print("#set options")
|
||||||
sclient.label_set_options("test", {"max_download_speed": 999}, True)
|
sclient.label_set_options("test", {"max_download_speed": 999}, True)
|
||||||
print(sclient.get_torrent_status(id, ["max_download_speed"]), "999")
|
print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "999")
|
||||||
sclient.label_set_options("test", {"max_download_speed": 9}, True)
|
sclient.label_set_options("test", {"max_download_speed": 9}, True)
|
||||||
print(sclient.get_torrent_status(id, ["max_download_speed"]), "9")
|
print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "9")
|
||||||
sclient.label_set_options("test", {"max_download_speed": 888}, False)
|
sclient.label_set_options("test", {"max_download_speed": 888}, False)
|
||||||
print(sclient.get_torrent_status(id, ["max_download_speed"]), "9 (888)")
|
print(sclient.get_torrent_status(sess_id, ["max_download_speed"]), "9 (888)")
|
||||||
|
|
||||||
print(sclient.get_torrent_status(id, ['name', 'tracker_host', 'label']))
|
print(sclient.get_torrent_status(sess_id, ['name', 'tracker_host', 'label']))
|
||||||
|
|
|
@ -34,7 +34,6 @@ def get_resource(filename):
|
||||||
|
|
||||||
|
|
||||||
class CustomNotifications(object):
|
class CustomNotifications(object):
|
||||||
config = None # shut-up pylint
|
|
||||||
|
|
||||||
def __init__(self, plugin_name=None):
|
def __init__(self, plugin_name=None):
|
||||||
self.custom_notifications = {
|
self.custom_notifications = {
|
||||||
|
@ -100,7 +99,7 @@ class CustomNotifications(object):
|
||||||
|
|
||||||
def _handled_eventtype(self, eventtype, handler):
|
def _handled_eventtype(self, eventtype, handler):
|
||||||
if eventtype not in known_events:
|
if eventtype not in known_events:
|
||||||
log.error("The event \"%s\" is not known" % eventtype)
|
log.error("The event \"%s\" is not known", eventtype)
|
||||||
return False
|
return False
|
||||||
if known_events[eventtype].__module__.startswith('deluge.event'):
|
if known_events[eventtype].__module__.startswith('deluge.event'):
|
||||||
if handler.__self__ is self:
|
if handler.__self__ is self:
|
||||||
|
|
|
@ -94,6 +94,11 @@ class CoreNotifications(CustomNotifications):
|
||||||
log.debug("Email prepared")
|
log.debug("Email prepared")
|
||||||
to_addrs = self.config['smtp_recipients']
|
to_addrs = self.config['smtp_recipients']
|
||||||
to_addrs_str = ', '.join(self.config['smtp_recipients'])
|
to_addrs_str = ', '.join(self.config['smtp_recipients'])
|
||||||
|
headers_dict = {
|
||||||
|
'smtp_from': self.config['smtp_from'],
|
||||||
|
'subject': subject,
|
||||||
|
'smtp_recipients': to_addrs_str,
|
||||||
|
'date': formatdate()}
|
||||||
headers = """\
|
headers = """\
|
||||||
From: %(smtp_from)s
|
From: %(smtp_from)s
|
||||||
To: %(smtp_recipients)s
|
To: %(smtp_recipients)s
|
||||||
|
@ -101,27 +106,15 @@ Subject: %(subject)s
|
||||||
Date: %(date)s
|
Date: %(date)s
|
||||||
|
|
||||||
|
|
||||||
""" % {'smtp_from': self.config['smtp_from'],
|
""" % headers_dict
|
||||||
'subject': subject,
|
|
||||||
'smtp_recipients': to_addrs_str,
|
|
||||||
'date': formatdate()
|
|
||||||
}
|
|
||||||
|
|
||||||
message = '\r\n'.join((headers + message).splitlines())
|
message = '\r\n'.join((headers + message).splitlines())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
try:
|
# Python 2.6
|
||||||
# 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:
|
|
||||||
# Python 2.5
|
|
||||||
server = smtplib.SMTP(self.config["smtp_host"],
|
|
||||||
self.config["smtp_port"])
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
err_msg = _("There was an error sending the notification email:"
|
err_msg = _("There was an error sending the notification email: %s") % ex
|
||||||
" %s") % ex
|
|
||||||
log.error(err_msg)
|
log.error(err_msg)
|
||||||
return ex
|
return ex
|
||||||
|
|
||||||
|
@ -185,12 +178,12 @@ Date: %(date)s
|
||||||
) % torrent_status
|
) % torrent_status
|
||||||
return subject, message
|
return subject, message
|
||||||
|
|
||||||
d = defer.maybeDeferred(self.handle_custom_email_notification,
|
# d = defer.maybeDeferred(self.handle_custom_email_notification,
|
||||||
[subject, message],
|
# [subject, message],
|
||||||
"TorrentFinishedEvent")
|
# "TorrentFinishedEvent")
|
||||||
d.addCallback(self._on_notify_sucess, 'email')
|
# d.addCallback(self._on_notify_sucess, 'email')
|
||||||
d.addErrback(self._on_notify_failure, 'email')
|
# d.addErrback(self._on_notify_failure, 'email')
|
||||||
return d
|
# return d
|
||||||
|
|
||||||
|
|
||||||
class Core(CorePluginBase, CoreNotifications):
|
class Core(CorePluginBase, CoreNotifications):
|
||||||
|
|
|
@ -143,7 +143,7 @@ class GtkUiNotifications(CustomNotifications):
|
||||||
if result:
|
if result:
|
||||||
return defer.maybeDeferred(self.__blink)
|
return defer.maybeDeferred(self.__blink)
|
||||||
return defer.succeed("Won't blink. The returned value from the custom "
|
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):
|
def handle_custom_sound_notification(self, result, eventtype):
|
||||||
if isinstance(result, basestring):
|
if isinstance(result, basestring):
|
||||||
|
@ -152,14 +152,13 @@ class GtkUiNotifications(CustomNotifications):
|
||||||
self.__play_sound, self.config['custom_sounds'][eventtype])
|
self.__play_sound, self.config['custom_sounds'][eventtype])
|
||||||
return defer.maybeDeferred(self.__play_sound, result)
|
return defer.maybeDeferred(self.__play_sound, result)
|
||||||
return defer.succeed("Won't play sound. The returned value from the "
|
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):
|
def __blink(self):
|
||||||
self.systray.blink(True)
|
self.systray.blink(True)
|
||||||
return defer.succeed(_("Notification Blink shown"))
|
return defer.succeed(_("Notification Blink shown"))
|
||||||
|
|
||||||
def __popup(self, title='', message=''):
|
def __popup(self, title='', message=''):
|
||||||
import gtk
|
|
||||||
if not self.config['popup_enabled']:
|
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:
|
if not POPUP_AVAILABLE:
|
||||||
|
@ -407,8 +406,9 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
self.subscriptions_treeview.append_column(column)
|
self.subscriptions_treeview.append_column(column)
|
||||||
self.subscriptions_treeview.set_model(self.subscriptions_model)
|
self.subscriptions_treeview.set_model(self.subscriptions_model)
|
||||||
|
|
||||||
def popuplate_what_needs_handled_events(self, handled_events,
|
def popuplate_what_needs_handled_events(self, handled_events, email_subscriptions=None):
|
||||||
email_subscriptions=[]):
|
if email_subscriptions is None:
|
||||||
|
email_subscriptions = []
|
||||||
self.populate_subscriptions(handled_events, email_subscriptions)
|
self.populate_subscriptions(handled_events, email_subscriptions)
|
||||||
self.populate_sounds(handled_events)
|
self.populate_sounds(handled_events)
|
||||||
|
|
||||||
|
@ -429,7 +429,9 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
SND_PATH, snd_path
|
SND_PATH, snd_path
|
||||||
)
|
)
|
||||||
|
|
||||||
def populate_subscriptions(self, handled_events, email_subscriptions=[]):
|
def populate_subscriptions(self, handled_events, email_subscriptions=None):
|
||||||
|
if email_subscriptions is None:
|
||||||
|
email_subscriptions = []
|
||||||
subscriptions_dict = self.config['subscriptions']
|
subscriptions_dict = self.config['subscriptions']
|
||||||
self.subscriptions_model.clear()
|
self.subscriptions_model.clear()
|
||||||
# self.handled_events = handled_events
|
# self.handled_events = handled_events
|
||||||
|
@ -557,13 +559,13 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
|
|
||||||
def on_delete_button_clicked(self, widget, treeview):
|
def on_delete_button_clicked(self, widget, treeview):
|
||||||
selection = treeview.get_selection()
|
selection = treeview.get_selection()
|
||||||
model, iter = selection.get_selected()
|
model, selected_iter = selection.get_selected()
|
||||||
if iter:
|
if selected_iter:
|
||||||
model.remove(iter)
|
model.remove(selected_iter)
|
||||||
|
|
||||||
def on_cell_edited(self, cell, path_string, new_text, model):
|
def on_cell_edited(self, cell, path_string, new_text, model):
|
||||||
iter = model.get_iter_from_string(path_string)
|
str_iter = model.get_iter_from_string(path_string)
|
||||||
model.set(iter, RECIPIENT_FIELD, new_text)
|
model.set(str_iter, RECIPIENT_FIELD, new_text)
|
||||||
|
|
||||||
def on_recipients_treeview_selection_changed(self, selection):
|
def on_recipients_treeview_selection_changed(self, selection):
|
||||||
model, selected_connection_iter = selection.get_selected()
|
model, selected_connection_iter = selection.get_selected()
|
||||||
|
@ -584,10 +586,10 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
False)
|
False)
|
||||||
|
|
||||||
def on_sounds_treeview_selection_changed(self, selection):
|
def on_sounds_treeview_selection_changed(self, selection):
|
||||||
model, iter = selection.get_selected()
|
model, selected_iter = selection.get_selected()
|
||||||
if iter:
|
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(iter, SND_PATH)[0]
|
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']:
|
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)
|
||||||
|
@ -600,19 +602,19 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
def on_sounds_revert_button_clicked(self, widget):
|
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()
|
selection = self.sounds_treeview.get_selection()
|
||||||
model, iter = selection.get_selected()
|
model, selected_iter = selection.get_selected()
|
||||||
if iter:
|
if selected_iter:
|
||||||
log.debug("on_sounds_revert_button_clicked: got iter")
|
log.debug("on_sounds_revert_button_clicked: got iter")
|
||||||
model.set(iter,
|
model.set(selected_iter,
|
||||||
SND_PATH, self.config['sound_path'],
|
SND_PATH, self.config['sound_path'],
|
||||||
SND_NAME, basename(self.config['sound_path']))
|
SND_NAME, basename(self.config['sound_path']))
|
||||||
|
|
||||||
def on_sounds_edit_button_clicked(self, widget):
|
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()
|
selection = self.sounds_treeview.get_selection()
|
||||||
model, iter = selection.get_selected()
|
model, selected_iter = selection.get_selected()
|
||||||
if iter:
|
if selected_iter:
|
||||||
path = model.get(iter, SND_PATH)[0]
|
path = model.get(selected_iter, SND_PATH)[0]
|
||||||
dialog = gtk.FileChooserDialog(
|
dialog = gtk.FileChooserDialog(
|
||||||
title=_("Choose Sound File"),
|
title=_("Choose Sound File"),
|
||||||
buttons=(gtk.STOCK_CANCEL,
|
buttons=(gtk.STOCK_CANCEL,
|
||||||
|
@ -627,7 +629,7 @@ class GtkUI(GtkPluginBase, GtkUiNotifications):
|
||||||
new_filename = dialog.get_filename()
|
new_filename = dialog.get_filename()
|
||||||
dialog.destroy()
|
dialog.destroy()
|
||||||
log.debug(new_filename)
|
log.debug(new_filename)
|
||||||
model.set(iter,
|
model.set(selected_iter,
|
||||||
SND_PATH, new_filename,
|
SND_PATH, new_filename,
|
||||||
SND_NAME, basename(new_filename))
|
SND_NAME, basename(new_filename))
|
||||||
d = defer.maybeDeferred(dialog.run)
|
d = defer.maybeDeferred(dialog.run)
|
||||||
|
|
|
@ -92,4 +92,3 @@ class TestEmailNotifications(component.Component):
|
||||||
def custom_sound_message_provider(self, *evt_args, **evt_kwargs):
|
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 ''
|
return ''
|
||||||
return '/usr/share/kde4/apps/korganizer/sounds/alert.wav'
|
|
||||||
|
|
|
@ -85,10 +85,8 @@ class Core(CorePluginBase):
|
||||||
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):
|
def disable(self):
|
||||||
try:
|
if self.timer.active():
|
||||||
self.timer.cancel()
|
self.timer.cancel()
|
||||||
except:
|
|
||||||
pass
|
|
||||||
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()
|
self.__apply_set_functions()
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,7 @@ class PluginInitBase(object):
|
||||||
_plugin_cls = None
|
_plugin_cls = None
|
||||||
|
|
||||||
def __init__(self, plugin_name):
|
def __init__(self, plugin_name):
|
||||||
self.plugin = self._plugin_cls(plugin_name)
|
self.plugin = self._plugin_cls(plugin_name) # pylint: disable=not-callable
|
||||||
|
|
||||||
def enable(self):
|
def enable(self):
|
||||||
return self.plugin.enable()
|
return self.plugin.enable()
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue