[Lint] Quote cleanup
This commit is contained in:
parent
441861786b
commit
2657cc3921
|
@ -208,7 +208,7 @@ def get_pixmap(fname):
|
||||||
|
|
||||||
def resource_filename(module, path):
|
def resource_filename(module, path):
|
||||||
# While developing, if there's a second deluge package, installed globally
|
# While developing, if there's a second deluge package, installed globally
|
||||||
# and another in develop mode somewhere else, while pkg_resources.require("Deluge")
|
# and another in develop mode somewhere else, while pkg_resources.require('Deluge')
|
||||||
# returns the proper deluge instance, pkg_resources.resource_filename does
|
# returns the proper deluge instance, pkg_resources.resource_filename does
|
||||||
# not, it returns the first found on the python path, which is not good
|
# not, it returns the first found on the python path, which is not good
|
||||||
# enough.
|
# enough.
|
||||||
|
@ -556,7 +556,7 @@ def is_url(url):
|
||||||
|
|
||||||
**Usage**
|
**Usage**
|
||||||
|
|
||||||
>>> is_url("http://deluge-torrent.org")
|
>>> is_url('http://deluge-torrent.org')
|
||||||
True
|
True
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -588,7 +588,7 @@ def is_magnet(uri):
|
||||||
|
|
||||||
**Usage**
|
**Usage**
|
||||||
|
|
||||||
>>> is_magnet("magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN")
|
>>> is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN')
|
||||||
True
|
True
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
@ -732,7 +732,7 @@ def is_ip(ip):
|
||||||
|
|
||||||
** Usage **
|
** Usage **
|
||||||
|
|
||||||
>>> is_ip("127.0.0.1")
|
>>> is_ip('127.0.0.1')
|
||||||
True
|
True
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -142,8 +142,10 @@ class Component(object):
|
||||||
elif self._component_state == 'Started':
|
elif self._component_state == 'Started':
|
||||||
d = succeed(True)
|
d = succeed(True)
|
||||||
else:
|
else:
|
||||||
d = fail(ComponentException("Trying to start a component ('%s') not in stopped state. Current state: '%s'" %
|
d = fail(ComponentException('Trying to start component "%s" but it is '
|
||||||
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
|
'not in a stopped state. Current state: %s' %
|
||||||
|
(self._component_name, self._component_state),
|
||||||
|
traceback.format_stack(limit=4)))
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def _component_stop(self):
|
def _component_stop(self):
|
||||||
|
@ -187,8 +189,10 @@ class Component(object):
|
||||||
elif self._component_state == 'Paused':
|
elif self._component_state == 'Paused':
|
||||||
d = succeed(None)
|
d = succeed(None)
|
||||||
else:
|
else:
|
||||||
d = fail(ComponentException("Trying to pause a component ('%s') not in started state. Current state: '%s'" %
|
d = fail(ComponentException('Trying to pause component "%s" but it is '
|
||||||
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
|
'not in a started state. Current state: %s' %
|
||||||
|
(self._component_name, self._component_state),
|
||||||
|
traceback.format_stack(limit=4)))
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def _component_resume(self):
|
def _component_resume(self):
|
||||||
|
@ -199,8 +203,10 @@ class Component(object):
|
||||||
d = maybeDeferred(self._component_start_timer)
|
d = maybeDeferred(self._component_start_timer)
|
||||||
d.addCallback(on_resume)
|
d.addCallback(on_resume)
|
||||||
else:
|
else:
|
||||||
d = fail(ComponentException("Trying to resume a component ('%s') not in paused state. Current state: '%s'" %
|
d = fail(ComponentException('Trying to resume component "%s" but it is '
|
||||||
(self._component_name, self._component_state), traceback.format_stack(limit=4)))
|
'not in a paused state. Current state: %s' %
|
||||||
|
(self._component_name, self._component_state),
|
||||||
|
traceback.format_stack(limit=4)))
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def _component_shutdown(self):
|
def _component_shutdown(self):
|
||||||
|
|
168
deluge/config.py
168
deluge/config.py
|
@ -101,15 +101,15 @@ def find_json_objects(s):
|
||||||
|
|
||||||
|
|
||||||
class Config(object):
|
class Config(object):
|
||||||
"""This class is used to access/create/modify config files
|
"""This class is used to access/create/modify config files.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filename (str): The config filename.
|
filename (str): The config filename.
|
||||||
defaults (dict): The default config values to insert before loading the config file
|
defaults (dict): The default config values to insert before loading the config file.
|
||||||
config_dir (str): the path to the config directory
|
config_dir (str): the path to the config directory.
|
||||||
file_version (int): The file format for the default config values when creating
|
file_version (int): The file format for the default config values when creating
|
||||||
a fresh config. This value should be increased whenever a new migration function is
|
a fresh config. This value should be increased whenever a new migration function is
|
||||||
setup to convert old config files. Default value is 1.
|
setup to convert old config files. (default: 1)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
def __init__(self, filename, defaults=None, config_dir=None, file_version=1):
|
def __init__(self, filename, defaults=None, config_dir=None, file_version=1):
|
||||||
|
@ -148,25 +148,28 @@ class Config(object):
|
||||||
return self.set_item(key, value)
|
return self.set_item(key, value)
|
||||||
|
|
||||||
def set_item(self, key, value):
|
def set_item(self, key, value):
|
||||||
"""Sets item 'key' to 'value' in the config dictionary, but does not allow
|
"""Sets item 'key' to 'value' in the config dictionary.
|
||||||
changing the item's type unless it is None. If the types do not match,
|
|
||||||
it will attempt to convert it to the set type before raising a ValueError.
|
Does not allow changing the item's type unless it is None.
|
||||||
|
|
||||||
|
If the types do not match, it will attempt to convert it to the
|
||||||
|
set type before raising a ValueError.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key (str): item to change to change
|
key (str): Item to change to change.
|
||||||
value (any): the value to change item to, must be same type as what is
|
value (any): The value to change item to, must be same type as what is
|
||||||
currently in the config
|
currently in the config.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: raised when the type of value is not the same as what is
|
ValueError: Raised when the type of value is not the same as what is
|
||||||
currently in the config and it could not convert the value
|
currently in the config and it could not convert the value.
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf")
|
>>> config = Config('test.conf')
|
||||||
>>> config["test"] = 5
|
>>> config['test'] = 5
|
||||||
>>> config["test"]
|
>>> config['test']
|
||||||
5
|
5
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if isinstance(value, basestring):
|
if isinstance(value, basestring):
|
||||||
|
@ -174,7 +177,7 @@ class Config(object):
|
||||||
|
|
||||||
if key not in self.__config:
|
if key not in self.__config:
|
||||||
self.__config[key] = value
|
self.__config[key] = value
|
||||||
log.debug("Setting '%s' to %s of %s", key, value, type(value))
|
log.debug('Setting key "%s" to: %s (of type: %s)', key, value, type(value))
|
||||||
return
|
return
|
||||||
|
|
||||||
if self.__config[key] == value:
|
if self.__config[key] == value:
|
||||||
|
@ -190,10 +193,10 @@ class Config(object):
|
||||||
else:
|
else:
|
||||||
value = oldtype(value)
|
value = oldtype(value)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
log.warning("Type '%s' invalid for '%s'", type(value), key)
|
log.warning('Value Type "%s" invalid for key: %s', type(value), key)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
log.debug("Setting '%s' to %s of %s", key, value, type(value))
|
log.debug('Setting key "%s" to: %s (of type: %s)', key, value, type(value))
|
||||||
|
|
||||||
self.__config[key] = value
|
self.__config[key] = value
|
||||||
|
|
||||||
|
@ -224,22 +227,22 @@ class Config(object):
|
||||||
return self.get_item(key)
|
return self.get_item(key)
|
||||||
|
|
||||||
def get_item(self, key):
|
def get_item(self, key):
|
||||||
"""Gets the value of item 'key'
|
"""Gets the value of item 'key'.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key (str): the item for which you want it's value
|
key (str): The item for which you want it's value.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
the value of item 'key'
|
any: The value of item 'key'.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: if 'key' is not in the config dictionary
|
ValueError: If 'key' is not in the config dictionary.
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
>>> config["test"]
|
>>> config['test']
|
||||||
5
|
5
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if isinstance(self.__config[key], str):
|
if isinstance(self.__config[key], str):
|
||||||
|
@ -252,6 +255,7 @@ class Config(object):
|
||||||
|
|
||||||
def get(self, key, default=None):
|
def get(self, key, default=None):
|
||||||
"""Gets the value of item 'key' if key is in the config, else default.
|
"""Gets the value of item 'key' if key is in the config, else default.
|
||||||
|
|
||||||
If default is not given, it defaults to None, so that this method
|
If default is not given, it defaults to None, so that this method
|
||||||
never raises a KeyError.
|
never raises a KeyError.
|
||||||
|
|
||||||
|
@ -260,15 +264,15 @@ class Config(object):
|
||||||
default (any): the default value if key is missing
|
default (any): the default value if key is missing
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
the value of item 'key' or default
|
any: The value of item 'key' or default.
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
>>> config.get("test", 10)
|
>>> config.get('test', 10)
|
||||||
5
|
5
|
||||||
>>> config.get("bad_key", 10)
|
>>> config.get('bad_key', 10)
|
||||||
10
|
10
|
||||||
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
|
@ -287,15 +291,18 @@ class Config(object):
|
||||||
"""Deletes item with a specific key from the configuration.
|
"""Deletes item with a specific key from the configuration.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key (str): the item which you wish to delete.
|
key (str): The item which you wish to delete.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: if 'key' is not in the config dictionary
|
ValueError: If 'key' is not in the config dictionary.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
|
>>> del config['test']
|
||||||
|
|
||||||
**Usage**
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
|
||||||
>>> del config["test"]
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
del self.__config[key]
|
del self.__config[key]
|
||||||
|
|
||||||
global callLater
|
global callLater
|
||||||
|
@ -308,38 +315,40 @@ class Config(object):
|
||||||
self._save_timer = callLater(5, self.save)
|
self._save_timer = callLater(5, self.save)
|
||||||
|
|
||||||
def register_change_callback(self, callback):
|
def register_change_callback(self, callback):
|
||||||
"""Registers a callback function that will be called when a value is changed in the config dictionary
|
"""Registers a callback function for any changed value.
|
||||||
|
|
||||||
|
Will be called when any value is changed in the config dictionary.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
callback (func): the function, callback(key, value)
|
callback (func): The function to call with parameters: f(key, value).
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
>>> def cb(key, value):
|
>>> def cb(key, value):
|
||||||
... print key, value
|
... print key, value
|
||||||
...
|
...
|
||||||
>>> config.register_change_callback(cb)
|
>>> config.register_change_callback(cb)
|
||||||
|
|
||||||
"""
|
"""
|
||||||
self.__change_callbacks.append(callback)
|
self.__change_callbacks.append(callback)
|
||||||
|
|
||||||
def register_set_function(self, key, function, apply_now=True):
|
def register_set_function(self, key, function, apply_now=True):
|
||||||
"""Register a function to be called when a config value changes
|
"""Register a function to be called when a config value changes.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
key (str): the item to monitor for change
|
key (str): The item to monitor for change.
|
||||||
function (func): the function to call when the value changes, f(key, value)
|
function (func): The function to call when the value changes, f(key, value).
|
||||||
apply_now (bool): if True, the function will be called after it's registered
|
apply_now (bool): If True, the function will be called immediately after it's registered.
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
>>> def cb(key, value):
|
>>> def cb(key, value):
|
||||||
... print key, value
|
... print key, value
|
||||||
...
|
...
|
||||||
>>> config.register_set_function("test", cb, apply_now=True)
|
>>> config.register_set_function('test', cb, apply_now=True)
|
||||||
test 5
|
test 5
|
||||||
|
|
||||||
"""
|
"""
|
||||||
log.debug('Registering function for %s key..', key)
|
log.debug('Registering function for %s key..', key)
|
||||||
|
@ -354,17 +363,17 @@ class Config(object):
|
||||||
return
|
return
|
||||||
|
|
||||||
def apply_all(self):
|
def apply_all(self):
|
||||||
"""Calls all set functions
|
"""Calls all set functions.
|
||||||
|
|
||||||
**Usage**
|
Examples:
|
||||||
|
|
||||||
>>> config = Config("test.conf", defaults={"test": 5})
|
>>> config = Config('test.conf', defaults={'test': 5})
|
||||||
>>> def cb(key, value):
|
>>> def cb(key, value):
|
||||||
... print key, value
|
... print key, value
|
||||||
...
|
...
|
||||||
>>> config.register_set_function("test", cb, apply_now=False)
|
>>> config.register_set_function('test', cb, apply_now=False)
|
||||||
>>> config.apply_all()
|
>>> config.apply_all()
|
||||||
test 5
|
test 5
|
||||||
|
|
||||||
"""
|
"""
|
||||||
log.debug('Calling all set functions..')
|
log.debug('Calling all set functions..')
|
||||||
|
@ -385,10 +394,10 @@ class Config(object):
|
||||||
func(key, self.__config[key])
|
func(key, self.__config[key])
|
||||||
|
|
||||||
def load(self, filename=None):
|
def load(self, filename=None):
|
||||||
"""Load a config file
|
"""Load a config file.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filename (str): if None, uses filename set in object initialization
|
filename (str): If None, uses filename set in object initialization
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if not filename:
|
if not filename:
|
||||||
|
@ -431,13 +440,13 @@ class Config(object):
|
||||||
self.__version['format'], self.__version['file'], self.__config)
|
self.__version['format'], self.__version['file'], self.__config)
|
||||||
|
|
||||||
def save(self, filename=None):
|
def save(self, filename=None):
|
||||||
"""Save configuration to disk
|
"""Save configuration to disk.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
filename (str): if None, uses filename set in object initialization
|
filename (str): If None, uses filename set in object initialization
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: whether or not the save succeeded.
|
bool: Whether or not the save succeeded.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if not filename:
|
if not filename:
|
||||||
|
@ -494,17 +503,16 @@ class Config(object):
|
||||||
self._save_timer.cancel()
|
self._save_timer.cancel()
|
||||||
|
|
||||||
def run_converter(self, input_range, output_version, func):
|
def run_converter(self, input_range, output_version, func):
|
||||||
"""Runs a function that will convert file versions in the `:param:input_range`
|
"""Runs a function that will convert file versions.
|
||||||
to the `:param:output_version`.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_range (tuple): (int, int) the range of input versions this function will accept
|
input_range (tuple): (int, int) The range of input versions this function will accept.
|
||||||
output_version (int): the version this function will return
|
output_version (int): The version this function will convert to.
|
||||||
func (func): the function that will do the conversion, it will take the config
|
func (func): The function that will do the conversion, it will take the config
|
||||||
dict as an argument and return the augmented dict
|
dict as an argument and return the augmented dict.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: if the output_version is less than the input_range
|
ValueError: If output_version is less than the input_range.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if output_version in input_range or output_version <= max(input_range):
|
if output_version in input_range or output_version <= max(input_range):
|
||||||
|
|
|
@ -86,7 +86,7 @@ class _ConfigManager(object):
|
||||||
|
|
||||||
def get_config(self, config_file, defaults=None, file_version=1):
|
def get_config(self, config_file, defaults=None, file_version=1):
|
||||||
"""Get a reference to the Config object for this filename"""
|
"""Get a reference to the Config object for this filename"""
|
||||||
log.debug("Getting config '%s'", config_file)
|
log.debug('Getting config: %s', config_file)
|
||||||
# Create the config object if not already created
|
# Create the config object if not already created
|
||||||
if config_file not in self.config_files.keys():
|
if config_file not in self.config_files.keys():
|
||||||
self.config_files[config_file] = Config(config_file, defaults,
|
self.config_files[config_file] = Config(config_file, defaults,
|
||||||
|
|
|
@ -128,7 +128,7 @@ class AuthManager(component.Component):
|
||||||
if username in self.__auth:
|
if username in self.__auth:
|
||||||
raise AuthManagerError('Username in use.', username)
|
raise AuthManagerError('Username in use.', username)
|
||||||
if authlevel not in AUTH_LEVELS_MAPPING:
|
if authlevel not in AUTH_LEVELS_MAPPING:
|
||||||
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
|
raise AuthManagerError('Invalid auth level: %s' % authlevel)
|
||||||
try:
|
try:
|
||||||
self.__auth[username] = Account(username, password,
|
self.__auth[username] = Account(username, password,
|
||||||
AUTH_LEVELS_MAPPING[authlevel])
|
AUTH_LEVELS_MAPPING[authlevel])
|
||||||
|
@ -142,7 +142,7 @@ class AuthManager(component.Component):
|
||||||
if username not in self.__auth:
|
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:
|
if authlevel not in AUTH_LEVELS_MAPPING:
|
||||||
raise AuthManagerError("Invalid auth level: '%s'" % authlevel)
|
raise AuthManagerError('Invalid auth level: %s' % authlevel)
|
||||||
try:
|
try:
|
||||||
self.__auth[username].username = username
|
self.__auth[username].username = username
|
||||||
self.__auth[username].password = password
|
self.__auth[username].password = password
|
||||||
|
|
|
@ -281,7 +281,7 @@ class Core(component.Component):
|
||||||
yield self._add_torrent_file(torrent[0], torrent[1],
|
yield self._add_torrent_file(torrent[0], torrent[1],
|
||||||
torrent[2], save_state=idx == last_index)
|
torrent[2], save_state=idx == last_index)
|
||||||
except AddTorrentError as ex:
|
except AddTorrentError as ex:
|
||||||
log.warn("Error when adding torrent: '%s'", ex)
|
log.warn('Error when adding torrent: %s', ex)
|
||||||
errors.append(ex)
|
errors.append(ex)
|
||||||
defer.returnValue(errors)
|
defer.returnValue(errors)
|
||||||
return task.deferLater(reactor, 0, add_torrents)
|
return task.deferLater(reactor, 0, add_torrents)
|
||||||
|
@ -310,7 +310,7 @@ class Core(component.Component):
|
||||||
try:
|
try:
|
||||||
os.remove(filename)
|
os.remove(filename)
|
||||||
except OSError as ex:
|
except OSError as ex:
|
||||||
log.warning("Couldn't remove temp file: %s", ex)
|
log.warning('Could not remove temp file: %s', ex)
|
||||||
return self.add_torrent_file(filename, base64.encodestring(data), options)
|
return self.add_torrent_file(filename, base64.encodestring(data), options)
|
||||||
|
|
||||||
def on_download_fail(failure):
|
def on_download_fail(failure):
|
||||||
|
@ -372,7 +372,7 @@ class Core(component.Component):
|
||||||
list: An empty list if no errors occurred otherwise the list contains
|
list: An empty list if no errors occurred otherwise the list contains
|
||||||
tuples of strings, a torrent ID and an error message. For example:
|
tuples of strings, a torrent ID and an error message. For example:
|
||||||
|
|
||||||
[("<torrent_id>", "Error removing torrent")]
|
[('<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))
|
||||||
|
|
|
@ -30,7 +30,7 @@ class EventManager(component.Component):
|
||||||
# Call any handlers for the event
|
# Call any handlers for the event
|
||||||
if event.name in self.handlers:
|
if event.name in self.handlers:
|
||||||
for handler in self.handlers[event.name]:
|
for handler in self.handlers[event.name]:
|
||||||
# log.debug("Running handler %s for event %s with args: %s", event.name, handler, event.args)
|
# log.debug('Running handler %s for event %s with args: %s', event.name, handler, event.args)
|
||||||
try:
|
try:
|
||||||
handler(*event.args)
|
handler(*event.args)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
|
|
|
@ -124,7 +124,7 @@ class PreferencesManager(component.Component):
|
||||||
component.Component.__init__(self, 'PreferencesManager')
|
component.Component.__init__(self, 'PreferencesManager')
|
||||||
self.config = deluge.configmanager.ConfigManager('core.conf', DEFAULT_PREFS)
|
self.config = deluge.configmanager.ConfigManager('core.conf', DEFAULT_PREFS)
|
||||||
if 'proxies' in self.config:
|
if 'proxies' in self.config:
|
||||||
log.warning("Updating config file for proxy, using 'peer' values to fill new 'proxy' setting")
|
log.warning('Updating config file for proxy, using "peer" values to fill new "proxy" setting')
|
||||||
self.config['proxy'].update(self.config['proxies']['peer'])
|
self.config['proxy'].update(self.config['proxies']['peer'])
|
||||||
log.warning('New proxy config is: %s', self.config['proxy'])
|
log.warning('New proxy config is: %s', self.config['proxy'])
|
||||||
del self.config['proxies']
|
del self.config['proxies']
|
||||||
|
|
|
@ -130,7 +130,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
|
||||||
log.debug('Received invalid rpc request: number of items '
|
log.debug('Received invalid rpc request: number of items '
|
||||||
'in request is %s', len(call))
|
'in request is %s', len(call))
|
||||||
continue
|
continue
|
||||||
# log.debug("RPCRequest: %s", format_request(call))
|
# log.debug('RPCRequest: %s', format_request(call))
|
||||||
reactor.callLater(0, self.dispatch, *call)
|
reactor.callLater(0, self.dispatch, *call)
|
||||||
|
|
||||||
def sendData(self, data): # NOQA: N802
|
def sendData(self, data): # NOQA: N802
|
||||||
|
@ -273,7 +273,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
|
||||||
if method not in self.factory.methods:
|
if method not in self.factory.methods:
|
||||||
try:
|
try:
|
||||||
# Raise exception to be sent back to client
|
# Raise exception to be sent back to client
|
||||||
raise AttributeError("RPC call on invalid function '%s'." % method)
|
raise AttributeError('RPC call on invalid function: %s' % method)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
send_error()
|
send_error()
|
||||||
return
|
return
|
||||||
|
|
|
@ -495,7 +495,7 @@ class Torrent(object):
|
||||||
return
|
return
|
||||||
|
|
||||||
if log.isEnabledFor(logging.DEBUG):
|
if log.isEnabledFor(logging.DEBUG):
|
||||||
log.debug("Setting %s's file priorities: %s", self.torrent_id, file_priorities)
|
log.debug('Setting %s file priorities to: %s', self.torrent_id, file_priorities)
|
||||||
|
|
||||||
self.handle.prioritize_files(file_priorities)
|
self.handle.prioritize_files(file_priorities)
|
||||||
|
|
||||||
|
@ -650,7 +650,7 @@ class Torrent(object):
|
||||||
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):
|
if log.isEnabledFor(logging.DEBUG):
|
||||||
log.debug("State from lt was: %s | Session is paused: %s\nTorrent state set from '%s' to '%s' (%s)",
|
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:
|
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)
|
||||||
|
@ -1080,10 +1080,10 @@ class Torrent(object):
|
||||||
if self.status.paused and self.status.auto_managed:
|
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:
|
elif self.forced_error and self.forced_error.was_paused:
|
||||||
log.debug("Resume skipped for error'd torrent as it was originally paused.")
|
log.debug('Resume skipped for forced_error torrent as it was originally paused.')
|
||||||
elif (self.status.is_finished and self.options['stop_at_ratio'] and
|
elif (self.status.is_finished and self.options['stop_at_ratio'] and
|
||||||
self.get_ratio() >= self.options['stop_ratio']):
|
self.get_ratio() >= self.options['stop_ratio']):
|
||||||
log.debug("Resume skipped for torrent as it has reached 'stop_seed_ratio'.")
|
log.debug('Resume skipped for torrent as it has reached "stop_seed_ratio".')
|
||||||
else:
|
else:
|
||||||
# Check if torrent was originally being auto-managed.
|
# Check if torrent was originally being auto-managed.
|
||||||
if self.options['auto_managed']:
|
if self.options['auto_managed']:
|
||||||
|
|
|
@ -483,7 +483,7 @@ class TorrentManager(component.Component):
|
||||||
try:
|
try:
|
||||||
torrent = self.torrents[torrent_id]
|
torrent = self.torrents[torrent_id]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise InvalidTorrentError("torrent_id '%s' not in session." % torrent_id)
|
raise InvalidTorrentError('torrent_id %s not in session.' % torrent_id)
|
||||||
|
|
||||||
torrent_name = torrent.get_status(['name'])['name']
|
torrent_name = torrent.get_status(['name'])['name']
|
||||||
|
|
||||||
|
@ -508,8 +508,8 @@ class TorrentManager(component.Component):
|
||||||
try:
|
try:
|
||||||
self.queued_torrents.remove(torrent_id)
|
self.queued_torrents.remove(torrent_id)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
log.debug("%s isn't in queued torrents set?", torrent_id)
|
log.debug('%s is not in queued torrents set.', torrent_id)
|
||||||
raise InvalidTorrentError("%s isn't in queued torrents set?" % torrent_id)
|
raise InvalidTorrentError('%s is not in queued torrents set.' % torrent_id)
|
||||||
|
|
||||||
# Remove the torrent from deluge's session
|
# Remove the torrent from deluge's session
|
||||||
del self.torrents[torrent_id]
|
del self.torrents[torrent_id]
|
||||||
|
@ -607,7 +607,7 @@ class TorrentManager(component.Component):
|
||||||
d = self.add(torrent_info=torrent_info, state=t_state, options=options, save_state=False,
|
d = self.add(torrent_info=torrent_info, state=t_state, options=options, save_state=False,
|
||||||
magnet=magnet, resume_data=resume_data.get(t_state.torrent_id))
|
magnet=magnet, resume_data=resume_data.get(t_state.torrent_id))
|
||||||
except AddTorrentError as ex:
|
except AddTorrentError as ex:
|
||||||
log.warn("Error when adding torrent '%s' to session: %s", t_state.torrent_id, ex)
|
log.warn('Error when adding torrent "%s" to session: %s', t_state.torrent_id, ex)
|
||||||
else:
|
else:
|
||||||
deferreds.append(d)
|
deferreds.append(d)
|
||||||
|
|
||||||
|
@ -981,7 +981,7 @@ class TorrentManager(component.Component):
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# Sometimes libtorrent fires a TorrentFinishedEvent twice
|
# Sometimes libtorrent fires a TorrentFinishedEvent twice
|
||||||
if log.isEnabledFor(logging.DEBUG):
|
if log.isEnabledFor(logging.DEBUG):
|
||||||
log.debug("%s isn't in queued torrents set?", torrent_id)
|
log.debug('%s is not in queued torrents set.', torrent_id)
|
||||||
|
|
||||||
# Only save resume data if it was actually downloaded something. Helps
|
# Only save resume data if it was actually downloaded something. Helps
|
||||||
# on startup with big queues with lots of seeding torrents. Libtorrent
|
# on startup with big queues with lots of seeding torrents. Libtorrent
|
||||||
|
|
|
@ -102,15 +102,15 @@ def _overrides(stack, method, explicit_base_classes=None):
|
||||||
if issubclass(classes[bc], classes[cc]):
|
if issubclass(classes[bc], classes[cc]):
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise Exception("Excplicit override class '%s' is not a super class of '%s'"
|
raise Exception('Excplicit override class "%s" is not a super class of: %s'
|
||||||
% (explicit_base_classes, class_name))
|
% (explicit_base_classes, class_name))
|
||||||
if not all(hasattr(classes[cls], method.__name__) for cls in check_classes):
|
if not all(hasattr(classes[cls], method.__name__) for cls in check_classes):
|
||||||
for cls in check_classes:
|
for cls in check_classes:
|
||||||
if not hasattr(classes[cls], method.__name__):
|
if not hasattr(classes[cls], method.__name__):
|
||||||
raise Exception("Function override '%s' not found in superclass: '%s'\n%s"
|
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):
|
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"
|
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
|
return method
|
||||||
|
|
|
@ -124,18 +124,18 @@ def sanitise_filename(filename):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Remove any quotes
|
# Remove any quotes
|
||||||
filename = filename.strip("'\"")
|
filename = filename.strip('\'"')
|
||||||
|
|
||||||
if os.path.basename(filename) != filename:
|
if os.path.basename(filename) != filename:
|
||||||
# Dodgy server, log it
|
# Dodgy server, log it
|
||||||
log.warning("Potentially malicious server: trying to write to file '%s'", filename)
|
log.warning('Potentially malicious server: trying to write to file: %s', filename)
|
||||||
# Only use the basename
|
# Only use the basename
|
||||||
filename = os.path.basename(filename)
|
filename = os.path.basename(filename)
|
||||||
|
|
||||||
filename = filename.strip()
|
filename = filename.strip()
|
||||||
if filename.startswith('.') or ';' in filename or '|' in filename:
|
if filename.startswith('.') or ';' in filename or '|' in filename:
|
||||||
# Dodgy server, log it
|
# Dodgy server, log it
|
||||||
log.warning("Potentially malicious server: trying to write to file '%s'", filename)
|
log.warning('Potentially malicious server: trying to write to file: %s', filename)
|
||||||
|
|
||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
@ -253,7 +253,7 @@ def download_file(url, filename, callback=None, headers=None, force_filename=Fal
|
||||||
result.addCallbacks(on_download_success, on_download_fail)
|
result.addCallbacks(on_download_success, on_download_fail)
|
||||||
else:
|
else:
|
||||||
# Log the failure and pass to the caller
|
# Log the failure and pass to the caller
|
||||||
log.warning("Error occurred downloading file from '%s': %s",
|
log.warning('Error occurred downloading file from "%s": %s',
|
||||||
url, failure.getErrorMessage())
|
url, failure.getErrorMessage())
|
||||||
result = failure
|
result = failure
|
||||||
return result
|
return result
|
||||||
|
|
|
@ -114,7 +114,7 @@ def setup_logger(level='error', filename=None, filemode='w', logrotate=None,
|
||||||
to that file instead of stdout.
|
to that file instead of stdout.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
level (str): The log level to use (Default: "error")
|
level (str): The log level to use (Default: 'error')
|
||||||
filename (str, optional): The log filename. Default is None meaning log
|
filename (str, optional): The log filename. Default is None meaning log
|
||||||
to terminal
|
to terminal
|
||||||
filemode (str): The filemode to use when opening the log file
|
filemode (str): The filemode to use when opening the log file
|
||||||
|
|
|
@ -37,10 +37,10 @@ class TorrentMetadata(object):
|
||||||
Examples:
|
Examples:
|
||||||
|
|
||||||
>>> t = TorrentMetadata()
|
>>> t = TorrentMetadata()
|
||||||
>>> t.data_path = "/tmp/torrent"
|
>>> t.data_path = '/tmp/torrent'
|
||||||
>>> t.comment = "My Test Torrent"
|
>>> t.comment = 'My Test Torrent'
|
||||||
>>> t.trackers = [["http://tracker.openbittorent.com"]]
|
>>> t.trackers = [['http://tracker.openbittorent.com']]
|
||||||
>>> t.save("/tmp/test.torrent")
|
>>> t.save('/tmp/test.torrent')
|
||||||
|
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
|
@ -152,7 +152,7 @@ class PluginManagerBase(object):
|
||||||
try:
|
try:
|
||||||
return_d = defer.maybeDeferred(instance.enable)
|
return_d = defer.maybeDeferred(instance.enable)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
log.error("Unable to enable plugin '%s'!", name)
|
log.error('Unable to enable plugin: %s', name)
|
||||||
log.exception(ex)
|
log.exception(ex)
|
||||||
return_d = defer.fail(False)
|
return_d = defer.fail(False)
|
||||||
|
|
||||||
|
@ -174,11 +174,11 @@ class PluginManagerBase(object):
|
||||||
if plugin_name_space not in self.config['enabled_plugins']:
|
if plugin_name_space not in self.config['enabled_plugins']:
|
||||||
log.debug('Adding %s to enabled_plugins list in config', plugin_name_space)
|
log.debug('Adding %s to enabled_plugins list in config', plugin_name_space)
|
||||||
self.config['enabled_plugins'].append(plugin_name_space)
|
self.config['enabled_plugins'].append(plugin_name_space)
|
||||||
log.info('Plugin %s enabled..', plugin_name_space)
|
log.info('Plugin %s enabled...', plugin_name_space)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def on_started_error(result, instance):
|
def on_started_error(result, instance):
|
||||||
log.warn("Failed to start plugin '%s': %s", plugin_name, result.getTraceback())
|
log.warn('Failed to start plugin: %s\n%s', plugin_name, result.getTraceback())
|
||||||
component.deregister(instance.plugin)
|
component.deregister(instance.plugin)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
@ -199,20 +199,20 @@ class PluginManagerBase(object):
|
||||||
|
|
||||||
"""
|
"""
|
||||||
if name not in self.plugins:
|
if name not in self.plugins:
|
||||||
log.warning("Plugin '%s' is not enabled..", name)
|
log.warning('Plugin "%s" is not enabled...', name)
|
||||||
return defer.succeed(True)
|
return defer.succeed(True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
d = defer.maybeDeferred(self.plugins[name].disable)
|
d = defer.maybeDeferred(self.plugins[name].disable)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
log.error("Error when disabling plugin '%s'", self.plugin._component_name)
|
log.error('Error when disabling plugin: %s', self.plugin._component_name)
|
||||||
log.exception(ex)
|
log.exception(ex)
|
||||||
d = defer.succeed(False)
|
d = defer.succeed(False)
|
||||||
|
|
||||||
def on_disabled(result):
|
def on_disabled(result):
|
||||||
ret = True
|
ret = True
|
||||||
if isinstance(result, Failure):
|
if isinstance(result, Failure):
|
||||||
log.error("Error when disabling plugin '%s'", name)
|
log.error('Error when disabling plugin: %s', name)
|
||||||
log.exception(result.getTraceback())
|
log.exception(result.getTraceback())
|
||||||
ret = False
|
ret = False
|
||||||
try:
|
try:
|
||||||
|
@ -220,11 +220,11 @@ class PluginManagerBase(object):
|
||||||
del self.plugins[name]
|
del self.plugins[name]
|
||||||
self.config['enabled_plugins'].remove(name)
|
self.config['enabled_plugins'].remove(name)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
log.error("Unable to disable plugin '%s'!", name)
|
log.error('Unable to disable plugin: %s', name)
|
||||||
log.exception(ex)
|
log.exception(ex)
|
||||||
ret = False
|
ret = False
|
||||||
else:
|
else:
|
||||||
log.info('Plugin %s disabled..', name)
|
log.info('Plugin %s disabled...', name)
|
||||||
return ret
|
return ret
|
||||||
|
|
||||||
d.addBoth(on_disabled)
|
d.addBoth(on_disabled)
|
||||||
|
@ -237,7 +237,7 @@ class PluginManagerBase(object):
|
||||||
cont_lines = []
|
cont_lines = []
|
||||||
# Missing plugin info
|
# Missing plugin info
|
||||||
if not self.pkg_env[name]:
|
if not self.pkg_env[name]:
|
||||||
log.warn("Failed to retrive info for plugin '%s'", name)
|
log.warn('Failed to retrive info for plugin: %s', name)
|
||||||
for k in info:
|
for k in info:
|
||||||
info[k] = 'not available'
|
info[k] = 'not available'
|
||||||
return info
|
return info
|
||||||
|
|
|
@ -116,7 +116,7 @@ class IP(object):
|
||||||
# if q3 >= 255:
|
# if q3 >= 255:
|
||||||
# if q2 >= 255:
|
# if q2 >= 255:
|
||||||
# if q1 >= 255:
|
# if q1 >= 255:
|
||||||
# raise BadIP(_("There ain't a next IP address"))
|
# raise BadIP(_('There is not a next IP address'))
|
||||||
# q1 += 1
|
# q1 += 1
|
||||||
# else:
|
# else:
|
||||||
# q2 += 1
|
# q2 += 1
|
||||||
|
@ -132,7 +132,7 @@ class IP(object):
|
||||||
# if q3 <= 1:
|
# if q3 <= 1:
|
||||||
# if q2 <= 1:
|
# if q2 <= 1:
|
||||||
# if q1 <= 1:
|
# if q1 <= 1:
|
||||||
# raise BadIP(_("There ain't a previous IP address"))
|
# raise BadIP(_('There is not a previous IP address'))
|
||||||
# q1 -= 1
|
# q1 -= 1
|
||||||
# else:
|
# else:
|
||||||
# q2 -= 1
|
# q2 -= 1
|
||||||
|
|
|
@ -225,7 +225,7 @@ class Core(CorePluginBase):
|
||||||
|
|
||||||
if needs_blocklist_import:
|
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 "
|
'do not know if they were blocked before. Re-import '
|
||||||
'current blocklist and re-add whitelisted.')
|
'current blocklist and re-add whitelisted.')
|
||||||
self.has_imported = False
|
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'))
|
||||||
|
@ -360,7 +360,8 @@ class Core(CorePluginBase):
|
||||||
else:
|
else:
|
||||||
log.warning('Blocklist download failed: %s', error_msg)
|
log.warning('Blocklist download failed: %s', error_msg)
|
||||||
if self.failed_attempts < self.config['try_times']:
|
if self.failed_attempts < self.config['try_times']:
|
||||||
log.debug("Let's try again")
|
log.debug('Try downloading blocklist again... (%s/%s)',
|
||||||
|
self.failed_attempts, self.config['try_times'])
|
||||||
self.failed_attempts += 1
|
self.failed_attempts += 1
|
||||||
d = self.download_list()
|
d = self.download_list()
|
||||||
d.addCallbacks(self.on_download_complete, self.on_download_error)
|
d.addCallbacks(self.on_download_complete, self.on_download_error)
|
||||||
|
@ -380,7 +381,7 @@ class Core(CorePluginBase):
|
||||||
|
|
||||||
def on_read_ip_range(start, end):
|
def on_read_ip_range(start, end):
|
||||||
"""Add ip range to blocklist"""
|
"""Add ip range to blocklist"""
|
||||||
# log.trace("Adding ip range %s - %s to ipfilter as blocked", start, end)
|
# log.trace('Adding ip range %s - %s to ipfilter as blocked', start, end)
|
||||||
self.blocklist.add_rule(start.address, end.address, BLOCK_RANGE)
|
self.blocklist.add_rule(start.address, end.address, BLOCK_RANGE)
|
||||||
self.num_blocked += 1
|
self.num_blocked += 1
|
||||||
|
|
||||||
|
@ -422,7 +423,7 @@ class Core(CorePluginBase):
|
||||||
log.debug('Importing using reader: %s', self.reader)
|
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('Reader type: %s compression: %s', self.config['list_type'], self.config['list_compression'])
|
||||||
log.debug('Clearing current ip filtering')
|
log.debug('Clearing current ip filtering')
|
||||||
# self.blocklist.add_rule("0.0.0.0", "255.255.255.255", ALLOW_RANGE)
|
# 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 = threads.deferToThread(self.reader(blocklist).read, on_read_ip_range)
|
||||||
d.addCallback(on_finish_read).addErrback(on_reader_failure)
|
d.addCallback(on_finish_read).addErrback(on_reader_failure)
|
||||||
|
|
||||||
|
|
|
@ -106,7 +106,7 @@ class Core(CorePluginBase):
|
||||||
def log_error(result, command):
|
def log_error(result, command):
|
||||||
(stdout, stderr, exit_code) = result
|
(stdout, stderr, exit_code) = result
|
||||||
if exit_code:
|
if exit_code:
|
||||||
log.warn("Command '%s' failed with exit code %d", command, exit_code)
|
log.warn('Command "%s" failed with exit code %d', command, exit_code)
|
||||||
if stdout:
|
if stdout:
|
||||||
log.warn('stdout: %s', stdout)
|
log.warn('stdout: %s', stdout)
|
||||||
if stderr:
|
if stderr:
|
||||||
|
|
|
@ -121,7 +121,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.debug("Can't extract file with unknown file type: %s", f['path'])
|
log.debug('Cannot extract file with unknown file type: %s', f['path'])
|
||||||
continue
|
continue
|
||||||
elif file_ext == '.rar' and 'part' in file_ext_sec:
|
elif file_ext == '.rar' and 'part' in file_ext_sec:
|
||||||
part_num = file_ext_sec.split('part')[1]
|
part_num = file_ext_sec.split('part')[1]
|
||||||
|
|
|
@ -53,13 +53,11 @@ class CustomNotifications(object):
|
||||||
self._deregister_custom_provider(kind, eventtype)
|
self._deregister_custom_provider(kind, eventtype)
|
||||||
|
|
||||||
def _handle_custom_providers(self, kind, eventtype, *args, **kwargs):
|
def _handle_custom_providers(self, kind, eventtype, *args, **kwargs):
|
||||||
log.debug("Calling CORE's custom %s providers for %s: %s %s",
|
log.debug('Calling CORE custom %s providers for %s: %s %s', kind, eventtype, args, kwargs)
|
||||||
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]
|
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,
|
custom_notif_func = getattr(self, 'handle_custom_%s_notification' % kind)
|
||||||
'handle_custom_%s_notification' % kind)
|
|
||||||
d = defer.maybeDeferred(handler, *args, **kwargs)
|
d = defer.maybeDeferred(handler, *args, **kwargs)
|
||||||
d.addCallback(custom_notif_func, eventtype)
|
d.addCallback(custom_notif_func, eventtype)
|
||||||
d.addCallback(self._on_notify_sucess, kind)
|
d.addCallback(self._on_notify_sucess, kind)
|
||||||
|
|
|
@ -135,13 +135,11 @@ Date: %(date)s
|
||||||
try:
|
try:
|
||||||
server.login(self.config['smtp_user'], self.config['smtp_pass'])
|
server.login(self.config['smtp_user'], self.config['smtp_pass'])
|
||||||
except smtplib.SMTPHeloError as ex:
|
except smtplib.SMTPHeloError as ex:
|
||||||
err_msg = _("The server didn't reply properly to the helo "
|
err_msg = _('Server did not reply properly to HELO greeting: %s') % ex
|
||||||
'greeting: %s') % ex
|
|
||||||
log.error(err_msg)
|
log.error(err_msg)
|
||||||
return ex
|
return ex
|
||||||
except smtplib.SMTPAuthenticationError as ex:
|
except smtplib.SMTPAuthenticationError as ex:
|
||||||
err_msg = _("The server didn't accept the username/password "
|
err_msg = _('Server refused username/password combination: %s') % ex
|
||||||
'combination: %s') % ex
|
|
||||||
log.error(err_msg)
|
log.error(err_msg)
|
||||||
return ex
|
return ex
|
||||||
|
|
||||||
|
@ -149,8 +147,7 @@ Date: %(date)s
|
||||||
try:
|
try:
|
||||||
server.sendmail(self.config['smtp_from'], to_addrs, message)
|
server.sendmail(self.config['smtp_from'], to_addrs, message)
|
||||||
except smtplib.SMTPException as ex:
|
except smtplib.SMTPException 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
|
||||||
finally:
|
finally:
|
||||||
|
@ -174,7 +171,7 @@ Date: %(date)s
|
||||||
subject = _('Finished Torrent "%(name)s"') % torrent_status
|
subject = _('Finished Torrent "%(name)s"') % torrent_status
|
||||||
message = _(
|
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.'
|
'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"
|
"notification in Deluge's preferences.\n\n"
|
||||||
'Thank you,\nDeluge.'
|
'Thank you,\nDeluge.'
|
||||||
|
@ -183,7 +180,7 @@ Date: %(date)s
|
||||||
|
|
||||||
# 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
|
||||||
|
|
|
@ -145,7 +145,7 @@ class GtkUiNotifications(CustomNotifications):
|
||||||
def handle_custom_blink_notification(self, result, eventtype):
|
def handle_custom_blink_notification(self, result, eventtype):
|
||||||
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('Will not 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):
|
||||||
|
@ -154,7 +154,7 @@ class GtkUiNotifications(CustomNotifications):
|
||||||
return defer.maybeDeferred(
|
return defer.maybeDeferred(
|
||||||
self.__play_sound, self.config['custom_sounds'][eventtype])
|
self.__play_sound, self.config['custom_sounds'][eventtype])
|
||||||
return defer.maybeDeferred(self.__play_sound, result)
|
return defer.maybeDeferred(self.__play_sound, result)
|
||||||
return defer.succeed("Won't play sound. The returned value from the "
|
return defer.succeed('Will not play sound. The returned value from the '
|
||||||
'custom handler was: %s' % result)
|
'custom handler was: %s' % result)
|
||||||
|
|
||||||
def __blink(self):
|
def __blink(self):
|
||||||
|
@ -222,7 +222,7 @@ class GtkUiNotifications(CustomNotifications):
|
||||||
'Got Torrent Status')
|
'Got Torrent Status')
|
||||||
title = _('Finished Torrent')
|
title = _('Finished Torrent')
|
||||||
torrent_status['num_files'] = torrent_status['file_progress'].count(1.0)
|
torrent_status['num_files'] = torrent_status['file_progress'].count(1.0)
|
||||||
message = _('The torrent \"%(name)s\" including %(num_files)i file(s) '
|
message = _('The torrent "%(name)s" including %(num_files)i file(s) '
|
||||||
'has finished downloading.') % torrent_status
|
'has finished downloading.') % torrent_status
|
||||||
return title, message
|
return title, message
|
||||||
|
|
||||||
|
|
|
@ -40,7 +40,7 @@ class TestEmailNotifications(component.Component):
|
||||||
log.debug('\n\nEnabling %s', self.__class__.__name__)
|
log.debug('\n\nEnabling %s', self.__class__.__name__)
|
||||||
for event in self.events:
|
for event in self.events:
|
||||||
if self.__imp == 'core':
|
if self.__imp == 'core':
|
||||||
# component.get("CorePlugin.Notifications").register_custom_email_notification(
|
# 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__,
|
event.__class__.__name__,
|
||||||
self.custom_email_message_provider
|
self.custom_email_message_provider
|
||||||
|
|
|
@ -77,7 +77,7 @@ class Core(CorePluginBase):
|
||||||
|
|
||||||
self.length = self.config['length']
|
self.length = self.config['length']
|
||||||
|
|
||||||
# self.stats = get_key(self.saved_stats, "stats") or {}
|
# self.stats = get_key(self.saved_stats, 'stats') or {}
|
||||||
self.stats_keys = []
|
self.stats_keys = []
|
||||||
self.add_stats(
|
self.add_stats(
|
||||||
'upload_rate',
|
'upload_rate',
|
||||||
|
|
|
@ -113,7 +113,7 @@ import deluge.configmanager
|
||||||
from deluge.core.rpcserver import export
|
from deluge.core.rpcserver import export
|
||||||
|
|
||||||
DEFAULT_PREFS = {
|
DEFAULT_PREFS = {
|
||||||
"test": "NiNiNi"
|
'test': 'NiNiNi'
|
||||||
}
|
}
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
@ -121,7 +121,7 @@ log = logging.getLogger(__name__)
|
||||||
|
|
||||||
class Core(CorePluginBase):
|
class Core(CorePluginBase):
|
||||||
def enable(self):
|
def enable(self):
|
||||||
self.config = deluge.configmanager.ConfigManager("%(safe_name)s.conf", DEFAULT_PREFS)
|
self.config = deluge.configmanager.ConfigManager('%(safe_name)s.conf', DEFAULT_PREFS)
|
||||||
|
|
||||||
def disable(self):
|
def disable(self):
|
||||||
pass
|
pass
|
||||||
|
@ -171,15 +171,15 @@ class WebUIPlugin(PluginInitBase):
|
||||||
SETUP = """
|
SETUP = """
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
|
|
||||||
__plugin_name__ = "%(name)s"
|
__plugin_name__ = '%(name)s'
|
||||||
__author__ = "%(author_name)s"
|
__author__ = '%(author_name)s'
|
||||||
__author_email__ = "%(author_email)s"
|
__author_email__ = '%(author_email)s'
|
||||||
__version__ = "0.1"
|
__version__ = '0.1'
|
||||||
__url__ = "%(url)s"
|
__url__ = '%(url)s'
|
||||||
__license__ = "GPLv3"
|
__license__ = 'GPLv3'
|
||||||
__description__ = ""
|
__description__ = ''
|
||||||
__long_description__ = \"\"\"\"\"\"
|
__long_description__ = \"\"\"\"\"\"
|
||||||
__pkg_data__ = {"deluge.plugins."+__plugin_name__.lower(): ["template/*", "data/*"]}
|
__pkg_data__ = {'deluge.plugins.'+__plugin_name__.lower(): ['template/*', 'data/*']}
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name=__plugin_name__,
|
name=__plugin_name__,
|
||||||
|
@ -192,7 +192,7 @@ setup(
|
||||||
long_description=__long_description__ if __long_description__ else __description__,
|
long_description=__long_description__ if __long_description__ else __description__,
|
||||||
|
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
namespace_packages=["deluge", "deluge.plugins"],
|
namespace_packages=['deluge', 'deluge.plugins'],
|
||||||
package_data=__pkg_data__,
|
package_data=__pkg_data__,
|
||||||
|
|
||||||
entry_points=\"\"\"
|
entry_points=\"\"\"
|
||||||
|
@ -211,8 +211,8 @@ COMMON = """
|
||||||
def get_resource(filename):
|
def get_resource(filename):
|
||||||
import pkg_resources
|
import pkg_resources
|
||||||
import os
|
import os
|
||||||
return pkg_resources.resource_filename("deluge.plugins.%(safe_name)s",
|
return pkg_resources.resource_filename('deluge.plugins.%(safe_name)s',
|
||||||
os.path.join("data", filename))
|
os.path.join('data', filename))
|
||||||
"""
|
"""
|
||||||
|
|
||||||
GTKUI = """
|
GTKUI = """
|
||||||
|
@ -230,21 +230,21 @@ log = logging.getLogger(__name__)
|
||||||
|
|
||||||
class GtkUI(GtkPluginBase):
|
class GtkUI(GtkPluginBase):
|
||||||
def enable(self):
|
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("%(name)s", self.glade.get_widget("prefs_box"))
|
component.get('Preferences').add_page('%(name)s', self.glade.get_widget('prefs_box'))
|
||||||
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)
|
||||||
|
|
||||||
def disable(self):
|
def disable(self):
|
||||||
component.get("Preferences").remove_page("%(name)s")
|
component.get('Preferences').remove_page('%(name)s')
|
||||||
component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_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)
|
component.get('PluginManager').deregister_hook('on_show_prefs', self.on_show_prefs)
|
||||||
|
|
||||||
def on_apply_prefs(self):
|
def on_apply_prefs(self):
|
||||||
log.debug("applying prefs for %(name)s")
|
log.debug('applying prefs for %(name)s')
|
||||||
config = {
|
config = {
|
||||||
"test": self.glade.get_widget("txt_test").get_text()
|
'test': self.glade.get_widget('txt_test').get_text()
|
||||||
}
|
}
|
||||||
client.%(safe_name)s.set_config(config)
|
client.%(safe_name)s.set_config(config)
|
||||||
|
|
||||||
|
@ -252,8 +252,8 @@ class GtkUI(GtkPluginBase):
|
||||||
client.%(safe_name)s.get_config().addCallback(self.cb_get_config)
|
client.%(safe_name)s.get_config().addCallback(self.cb_get_config)
|
||||||
|
|
||||||
def cb_get_config(self, config):
|
def cb_get_config(self, config):
|
||||||
"callback for on show_prefs"
|
\"\"\"callback for on show_prefs\"\"\"
|
||||||
self.glade.get_widget("txt_test").set_text(config["test"])
|
self.glade.get_widget('txt_test').set_text(config['test'])
|
||||||
"""
|
"""
|
||||||
|
|
||||||
GLADE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
GLADE = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
@ -297,7 +297,7 @@ log = logging.getLogger(__name__)
|
||||||
|
|
||||||
class WebUI(WebPluginBase):
|
class WebUI(WebPluginBase):
|
||||||
|
|
||||||
scripts = [get_resource("%(safe_name)s.js")]
|
scripts = [get_resource('%(safe_name)s.js')]
|
||||||
|
|
||||||
def enable(self):
|
def enable(self):
|
||||||
pass
|
pass
|
||||||
|
@ -321,7 +321,7 @@ Copyright:
|
||||||
%(name)sPlugin = Ext.extend(Deluge.Plugin, {
|
%(name)sPlugin = Ext.extend(Deluge.Plugin, {
|
||||||
constructor: function(config) {
|
constructor: function(config) {
|
||||||
config = Ext.apply({
|
config = Ext.apply({
|
||||||
name: "%(name)s"
|
name: '%(name)s'
|
||||||
}, config);
|
}, config);
|
||||||
%(name)sPlugin.superclass.constructor.call(this, config);
|
%(name)sPlugin.superclass.constructor.call(this, config);
|
||||||
},
|
},
|
||||||
|
|
|
@ -17,7 +17,7 @@ class BaseTestCase(unittest.TestCase):
|
||||||
|
|
||||||
if len(component._ComponentRegistry.components) != 0:
|
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" %
|
'This is probably caused by another test that did not clean up after finishing!: %s' %
|
||||||
component._ComponentRegistry.components)
|
component._ComponentRegistry.components)
|
||||||
d = maybeDeferred(self.set_up)
|
d = maybeDeferred(self.set_up)
|
||||||
|
|
||||||
|
|
|
@ -174,7 +174,7 @@ class ProcessOutputHandler(protocol.ProcessProtocol):
|
||||||
if 'cb' in trigger:
|
if 'cb' in trigger:
|
||||||
trigger['cb'](self, c['deferred'], data, self.log_output)
|
trigger['cb'](self, c['deferred'], data, self.log_output)
|
||||||
elif 'value' not in trigger:
|
elif 'value' not in trigger:
|
||||||
raise Exception("Trigger must specify either 'cb' or 'value'")
|
raise Exception('Trigger must specify either "cb" or "value"')
|
||||||
else:
|
else:
|
||||||
val = trigger['value'](self, data, self.log_output)
|
val = trigger['value'](self, data, self.log_output)
|
||||||
if trigger.get('type', 'callback') == 'errback':
|
if trigger.get('type', 'callback') == 'errback':
|
||||||
|
@ -237,7 +237,7 @@ try:
|
||||||
daemon.start()
|
daemon.start()
|
||||||
except:
|
except:
|
||||||
import traceback
|
import traceback
|
||||||
sys.stderr.write("Exception raised:\\n %%s" %% traceback.format_exc())
|
sys.stderr.write('Exception raised:\\n %%s' %% traceback.format_exc())
|
||||||
""" % (config_directory, listen_port, custom_script)
|
""" % (config_directory, listen_port, custom_script)
|
||||||
callbacks = []
|
callbacks = []
|
||||||
default_core_cb = {'deferred': Deferred(), 'types': 'stdout'}
|
default_core_cb = {'deferred': Deferred(), 'types': 'stdout'}
|
||||||
|
@ -247,7 +247,7 @@ except:
|
||||||
# Specify the triggers for daemon log output
|
# Specify the triggers for daemon log output
|
||||||
default_core_cb['triggers'] = [
|
default_core_cb['triggers'] = [
|
||||||
{'expr': 'Finished loading ', 'value': lambda reader, data, data_all: reader},
|
{'expr': 'Finished loading ', 'value': lambda reader, data, data_all: reader},
|
||||||
{'expr': "Couldn't listen on localhost:%d" % (listen_port), 'type': 'errback', # Error from libtorrent
|
{'expr': 'Could not listen on localhost:%d' % (listen_port), 'type': 'errback', # Error from libtorrent
|
||||||
'value': lambda reader, data, data_all: CannotListenError('localhost', listen_port,
|
'value': lambda reader, data, data_all: CannotListenError('localhost', listen_port,
|
||||||
'Could not start deluge test client!\n%s' % data)},
|
'Could not start deluge test client!\n%s' % data)},
|
||||||
{'expr': 'Traceback', 'type': 'errback',
|
{'expr': 'Traceback', 'type': 'errback',
|
||||||
|
|
|
@ -107,4 +107,4 @@ class CommonTestCase(unittest.TestCase):
|
||||||
|
|
||||||
for human_size, byte_size in sizes:
|
for human_size, byte_size in sizes:
|
||||||
parsed = parse_human_size(human_size)
|
parsed = parse_human_size(human_size)
|
||||||
self.assertEquals(parsed, byte_size, "Mismatch when converting '%s'" % human_size)
|
self.assertEquals(parsed, byte_size, 'Mismatch when converting: %s' % human_size)
|
||||||
|
|
|
@ -221,8 +221,8 @@ class ComponentTestClass(BaseTestCase):
|
||||||
result = yield component.start()
|
result = yield component.start()
|
||||||
self.failUnlessEqual([(result[0][0], result[0][1].value)],
|
self.failUnlessEqual([(result[0][0], result[0][1].value)],
|
||||||
[(defer.FAILURE,
|
[(defer.FAILURE,
|
||||||
component.ComponentException("Trying to start a component ('%s') not in "
|
component.ComponentException('Trying to start component "%s" but it is '
|
||||||
"stopped state. Current state: '%s'" %
|
'not in a stopped state. Current state: %s' %
|
||||||
('test_pause_c1', 'Paused'), ''))])
|
('test_pause_c1', 'Paused'), ''))])
|
||||||
|
|
||||||
def test_shutdown(self):
|
def test_shutdown(self):
|
||||||
|
|
|
@ -244,8 +244,8 @@ class CoreTestCase(BaseTestCase):
|
||||||
torrent_id = yield self.core.add_torrent_file(filename, filedump, options)
|
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(len(val), 2)
|
||||||
self.assertEqual(val[0], ('invalidid1', "torrent_id 'invalidid1' not in session."))
|
self.assertEqual(val[0], ('invalidid1', 'torrent_id invalidid1 not in session.'))
|
||||||
self.assertEqual(val[1], ('invalidid2', "torrent_id 'invalidid2' not in session."))
|
self.assertEqual(val[1], ('invalidid2', 'torrent_id invalidid2 not in session.'))
|
||||||
|
|
||||||
def test_get_session_status(self):
|
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'])
|
||||||
|
|
|
@ -67,7 +67,7 @@ class PartialDownloadResource(Resource):
|
||||||
self.render_count = 0
|
self.render_count = 0
|
||||||
|
|
||||||
def render(self, request):
|
def render(self, request):
|
||||||
# encoding = request.requestHeaders._rawHeaders.get("accept-encoding", None)
|
# encoding = request.requestHeaders._rawHeaders.get('accept-encoding', None)
|
||||||
if self.render_count == 0:
|
if self.render_count == 0:
|
||||||
request.setHeader('content-length', '5')
|
request.setHeader('content-length', '5')
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -149,7 +149,7 @@ class RPCRaiseDelugeErrorJSONTestCase(JSONBase):
|
||||||
class TestClass(object):
|
class TestClass(object):
|
||||||
@export()
|
@export()
|
||||||
def test(self):
|
def test(self):
|
||||||
raise DelugeError("DelugeERROR")
|
raise DelugeError('DelugeERROR')
|
||||||
|
|
||||||
test = TestClass()
|
test = TestClass()
|
||||||
daemon.rpcserver.register_object(test)
|
daemon.rpcserver.register_object(test)
|
||||||
|
@ -199,7 +199,7 @@ class JSONRequestFailedTestCase(JSONBase, WebServerMockBase):
|
||||||
@export()
|
@export()
|
||||||
def test(self):
|
def test(self):
|
||||||
def test_raise_error():
|
def test_raise_error():
|
||||||
raise DelugeError("DelugeERROR")
|
raise DelugeError('DelugeERROR')
|
||||||
|
|
||||||
return task.deferLater(reactor, 1, test_raise_error)
|
return task.deferLater(reactor, 1, test_raise_error)
|
||||||
|
|
||||||
|
|
|
@ -91,7 +91,7 @@ class TransferTestClass(DelugeTransferProtocol):
|
||||||
(len(data), len(data) - len(dobj.unused_data), len(dobj.unused_data)))
|
(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:
|
except Exception as ex:
|
||||||
# log.debug("Received possible invalid message (%r): %s", data, e)
|
# log.debug('Received possible invalid message (%r): %s', data, e)
|
||||||
# This could be cut-off data, so we'll save this in the buffer
|
# This could be cut-off data, so we'll save this in the buffer
|
||||||
# and try to prepend it on the next dataReceived()
|
# and try to prepend it on the next dataReceived()
|
||||||
self._buffer = data
|
self._buffer = data
|
||||||
|
@ -307,9 +307,9 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
|
||||||
|
|
||||||
# Needs file containing big data structure e.g. like thetorrent list as it is transfered by the daemon
|
# Needs file containing big data structure e.g. like thetorrent list as it is transfered by the daemon
|
||||||
# def test_simulate_big_transfer(self):
|
# def test_simulate_big_transfer(self):
|
||||||
# filename = "../deluge.torrentlist"
|
# filename = '../deluge.torrentlist'
|
||||||
#
|
#
|
||||||
# f = open(filename, "r")
|
# f = open(filename, 'r')
|
||||||
# data = f.read()
|
# data = f.read()
|
||||||
# message_to_send = eval(data)
|
# message_to_send = eval(data)
|
||||||
# self.transfer.transfer_message(message_to_send)
|
# self.transfer.transfer_message(message_to_send)
|
||||||
|
@ -331,7 +331,7 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
|
||||||
# self.assertTrue(transfered_message == message_to_send)
|
# self.assertTrue(transfered_message == message_to_send)
|
||||||
#
|
#
|
||||||
# f.close()
|
# f.close()
|
||||||
# f = open("rencode.torrentlist", "w")
|
# f = open('rencode.torrentlist', 'w')
|
||||||
# f.write(str(transfered_message))
|
# f.write(str(transfered_message))
|
||||||
# f.close()
|
# f.close()
|
||||||
|
|
||||||
|
|
|
@ -38,7 +38,7 @@ sys_stdout = sys.stdout
|
||||||
# the file descriptors in sys and argparse._sys with StringFileDescriptor.
|
# the file descriptors in sys and argparse._sys with StringFileDescriptor.
|
||||||
# Regular print statements from such tests will therefore write to the
|
# Regular print statements from such tests will therefore write to the
|
||||||
# StringFileDescriptor object instead of the terminal.
|
# StringFileDescriptor object instead of the terminal.
|
||||||
# To print to terminal from the tests, use: print("Message...", file=sys_stdout)
|
# To print to terminal from the tests, use: print('Message...', file=sys_stdout)
|
||||||
|
|
||||||
|
|
||||||
class StringFileDescriptor(object):
|
class StringFileDescriptor(object):
|
||||||
|
@ -71,7 +71,7 @@ class UIBaseTestCase(object):
|
||||||
|
|
||||||
def exec_command(self):
|
def exec_command(self):
|
||||||
if DEBUG_COMMAND:
|
if DEBUG_COMMAND:
|
||||||
print("Executing: '%s'\n" % sys.argv, file=sys_stdout)
|
print('Executing: %s\n' % sys.argv, file=sys_stdout)
|
||||||
return self.var['start_cmd']()
|
return self.var['start_cmd']()
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -47,7 +47,7 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
|
||||||
try:
|
try:
|
||||||
body = yield twisted.web.client.readBody(d)
|
body = yield twisted.web.client.readBody(d)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
raise SkipTest("This test requires 't.w.c.readBody()' in Twisted version >= 13.2")
|
raise SkipTest('This test requires "t.w.c.readBody()" in Twisted version >= 13.2')
|
||||||
|
|
||||||
json = json_lib.loads(body)
|
json = json_lib.loads(body)
|
||||||
self.assertEqual(None, json['error'])
|
self.assertEqual(None, json['error'])
|
||||||
|
|
|
@ -21,7 +21,7 @@ parts.
|
||||||
|
|
||||||
>>> import PIL.Image
|
>>> import PIL.Image
|
||||||
>>> import Win32IconImagePlugin
|
>>> import Win32IconImagePlugin
|
||||||
>>> ico = PIL.Image.open("down.ico")
|
>>> ico = PIL.Image.open('down.ico')
|
||||||
>>> print ico.info['sizes']
|
>>> print ico.info['sizes']
|
||||||
set([(16, 16), (48, 48), (256, 256), (32, 32)])
|
set([(16, 16), (48, 48), (256, 256), (32, 32)])
|
||||||
>>> ico.size = (16, 16)
|
>>> ico.size = (16, 16)
|
||||||
|
|
|
@ -104,7 +104,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
|
||||||
|
|
||||||
if message_type == RPC_EVENT:
|
if message_type == RPC_EVENT:
|
||||||
event = request[1]
|
event = request[1]
|
||||||
# log.debug("Received RPCEvent: %s", event)
|
# log.debug('Received RPCEvent: %s', event)
|
||||||
# A RPCEvent was received from the daemon so run any handlers
|
# A RPCEvent was received from the daemon so run any handlers
|
||||||
# associated with it.
|
# associated with it.
|
||||||
if event in self.factory.event_handlers:
|
if event in self.factory.event_handlers:
|
||||||
|
@ -178,7 +178,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
|
||||||
# response to this request. We use the extra information when printing
|
# response to this request. We use the extra information when printing
|
||||||
# out the error for debugging purposes.
|
# out the error for debugging purposes.
|
||||||
self.__rpc_requests[request.request_id] = request
|
self.__rpc_requests[request.request_id] = request
|
||||||
# log.debug("Sending RPCRequest %s: %s", request.request_id, request)
|
# log.debug('Sending RPCRequest %s: %s', request.request_id, request)
|
||||||
# Send the request in a tuple because multiple requests can be sent at once
|
# Send the request in a tuple because multiple requests can be sent at once
|
||||||
self.transfer_message((request.format_message(),))
|
self.transfer_message((request.format_message(),))
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
|
@ -453,7 +453,7 @@ class DaemonStandaloneProxy(DaemonProxy):
|
||||||
self.__daemon = None
|
self.__daemon = None
|
||||||
|
|
||||||
def call(self, method, *args, **kwargs):
|
def call(self, method, *args, **kwargs):
|
||||||
# log.debug("call: %s %s %s", method, args, kwargs)
|
# log.debug('call: %s %s %s', method, args, kwargs)
|
||||||
|
|
||||||
import copy
|
import copy
|
||||||
|
|
||||||
|
@ -503,7 +503,7 @@ class DottedObject(object):
|
||||||
self.base = method
|
self.base = method
|
||||||
|
|
||||||
def __call__(self, *args, **kwargs):
|
def __call__(self, *args, **kwargs):
|
||||||
raise Exception("You must make calls in the form of 'component.method'!")
|
raise Exception('You must make calls in the form of "component.method"')
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
return RemoteMethod(self.daemon, self.base + '.' + name)
|
return RemoteMethod(self.daemon, self.base + '.' + name)
|
||||||
|
@ -637,8 +637,9 @@ class Client(object):
|
||||||
except OSError as ex:
|
except OSError as ex:
|
||||||
from errno import ENOENT
|
from errno import ENOENT
|
||||||
if ex.errno == ENOENT:
|
if ex.errno == ENOENT:
|
||||||
log.error(_("Deluge cannot find the 'deluged' executable, it is likely \
|
log.error(
|
||||||
that you forgot to install the deluged package or it's not in your PATH."))
|
_('Deluge cannot find the `deluged` executable, check that '
|
||||||
|
'the deluged package is installed, or added to your PATH.'))
|
||||||
else:
|
else:
|
||||||
log.exception(ex)
|
log.exception(ex)
|
||||||
raise ex
|
raise ex
|
||||||
|
|
|
@ -109,7 +109,7 @@ class Commander(object):
|
||||||
return
|
return
|
||||||
except OptionParserError as ex:
|
except OptionParserError as ex:
|
||||||
import traceback
|
import traceback
|
||||||
log.warn("Error parsing command '%s': %s", args, ex)
|
log.warn('Error parsing command "%s": %s', args, ex)
|
||||||
self.write('{!error!} %s' % ex)
|
self.write('{!error!} %s' % ex)
|
||||||
parser.print_help()
|
parser.print_help()
|
||||||
return
|
return
|
||||||
|
|
|
@ -65,7 +65,7 @@ class Command(BaseCommand):
|
||||||
torrent = url2pathname(urlparse(torrent).path)
|
torrent = url2pathname(urlparse(torrent).path)
|
||||||
path = os.path.abspath(os.path.expanduser(torrent))
|
path = os.path.abspath(os.path.expanduser(torrent))
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
self.console.write("{!error!}%s doesn't exist!" % path)
|
self.console.write('{!error!}%s does not exist!' % path)
|
||||||
continue
|
continue
|
||||||
if not os.path.isfile(path):
|
if not os.path.isfile(path):
|
||||||
self.console.write('{!error!}This is a directory!')
|
self.console.write('{!error!}This is a directory!')
|
||||||
|
|
|
@ -122,7 +122,7 @@ class Command(BaseCommand):
|
||||||
return
|
return
|
||||||
|
|
||||||
if key not in config.keys():
|
if key not in config.keys():
|
||||||
self.console.write("{!error!}The key '%s' is invalid!" % key)
|
self.console.write('{!error!}Invalid key: %s' % key)
|
||||||
return
|
return
|
||||||
|
|
||||||
if not isinstance(config[key], type(val)):
|
if not isinstance(config[key], type(val)):
|
||||||
|
@ -135,7 +135,7 @@ class Command(BaseCommand):
|
||||||
def on_set_config(result):
|
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))
|
self.console.write('Setting "%s" to: %s' % (key, val))
|
||||||
return client.core.set_config({key: val}).addCallback(on_set_config)
|
return client.core.set_config({key: val}).addCallback(on_set_config)
|
||||||
|
|
||||||
def complete(self, text):
|
def complete(self, text):
|
||||||
|
|
|
@ -54,7 +54,7 @@ class Command(BaseCommand):
|
||||||
cmds_doc += parser.formatter.format_colors(cmd_doc)
|
cmds_doc += parser.formatter.format_colors(cmd_doc)
|
||||||
self.console.write(cmds_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.write('For help on a specific command, use `<command> --help`')
|
||||||
self.console.set_batch_write(False)
|
self.console.set_batch_write(False)
|
||||||
|
|
||||||
return deferred
|
return deferred
|
||||||
|
|
|
@ -94,7 +94,7 @@ class Command(BaseCommand):
|
||||||
torrent_ids = self.console.match_torrent(options.torrent)
|
torrent_ids = self.console.match_torrent(options.torrent)
|
||||||
|
|
||||||
if key not in torrent_options:
|
if key not in torrent_options:
|
||||||
self.console.write("{!error!}The key '%s' is invalid!" % key)
|
self.console.write('{!error!}Invalid key: %s' % key)
|
||||||
return
|
return
|
||||||
|
|
||||||
val = torrent_options[key](val)
|
val = torrent_options[key](val)
|
||||||
|
|
|
@ -20,7 +20,7 @@ class Command(BaseCommand):
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
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"))
|
help=_('One or more torrent ids. Use "*" to pause all torrents'))
|
||||||
|
|
||||||
def handle(self, options):
|
def handle(self, options):
|
||||||
self.console = component.get('ConsoleUI')
|
self.console = component.get('ConsoleUI')
|
||||||
|
|
|
@ -20,7 +20,7 @@ class Command(BaseCommand):
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
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"))
|
help=_('One or more torrent ids. Use "*" to resume all torrents'))
|
||||||
|
|
||||||
def handle(self, options):
|
def handle(self, options):
|
||||||
self.console = component.get('ConsoleUI')
|
self.console = component.get('ConsoleUI')
|
||||||
|
|
|
@ -23,7 +23,8 @@ class Command(BaseCommand):
|
||||||
aliases = ['del']
|
aliases = ['del']
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
def add_arguments(self, parser):
|
||||||
parser.add_argument('--remove_data', action='store_true', default=False, help=_("remove the torrent's data"))
|
parser.add_argument('--remove_data', action='store_true', default=False,
|
||||||
|
help=_('Also removes the torrent data'))
|
||||||
parser.add_argument('-c', '--confirm', action='store_true', default=False,
|
parser.add_argument('-c', '--confirm', action='store_true', default=False,
|
||||||
help=_('List the matching torrents without removing.'))
|
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('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids'))
|
||||||
|
|
|
@ -25,10 +25,10 @@ class Command(BaseCommand):
|
||||||
|
|
||||||
def add_arguments(self, parser):
|
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 "
|
help=_('Raw values for upload/download rates (without KiB/s suffix)'
|
||||||
'(useful for scripts that want to do their own parsing)'))
|
'(useful for scripts that want to do their own parsing)'))
|
||||||
parser.add_argument('-n', '--no-torrents', action='store_false', default=True, dest='show_torrents',
|
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)"))
|
help=_('Do not show torrent status (Improves command speed)'))
|
||||||
|
|
||||||
def handle(self, options):
|
def handle(self, options):
|
||||||
self.console = component.get('ConsoleUI')
|
self.console = component.get('ConsoleUI')
|
||||||
|
|
|
@ -249,10 +249,10 @@ Please use commands from the command line, e.g.:\n
|
||||||
return mode
|
return mode
|
||||||
|
|
||||||
def set_mode(self, mode_name, refresh=False):
|
def set_mode(self, mode_name, refresh=False):
|
||||||
log.debug("Setting console mode '%s'", mode_name)
|
log.debug('Setting console mode: %s', mode_name)
|
||||||
mode = self.modes.get(mode_name, None)
|
mode = self.modes.get(mode_name, None)
|
||||||
if mode is None:
|
if mode is None:
|
||||||
log.error("Non-existent mode requested: '%s'", mode_name)
|
log.error('Non-existent mode requested: %s', mode_name)
|
||||||
return
|
return
|
||||||
self.stdscr.erase()
|
self.stdscr.erase()
|
||||||
|
|
||||||
|
@ -268,7 +268,7 @@ Please use commands from the command line, e.g.:\n
|
||||||
# which can cause issues as the popup's screen will not be destroyed.
|
# which can cause issues as the popup's screen will not be destroyed.
|
||||||
# This can lead to the popup border being visible for short periods
|
# This can lead to the popup border being visible for short periods
|
||||||
# while the current modes' screen is repainted.
|
# while the current modes' screen is repainted.
|
||||||
log.error("Mode '%s' still has popups available after being paused."
|
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)
|
d.addCallback(on_mode_paused, self.active_mode)
|
||||||
reactor.removeReader(self.active_mode)
|
reactor.removeReader(self.active_mode)
|
||||||
|
|
|
@ -28,7 +28,7 @@ def _bracket_fixup(path):
|
||||||
while path.find(unichr(sentinal)) != -1:
|
while path.find(unichr(sentinal)) != -1:
|
||||||
sentinal += 1
|
sentinal += 1
|
||||||
if sentinal > 65535:
|
if sentinal > 65535:
|
||||||
log.error("Can't fix brackets in path, path contains all possible sentinal characters")
|
log.error('Cannot fix brackets in path, path contains all possible sentinal characters')
|
||||||
return path
|
return path
|
||||||
newpath = path.replace(']', unichr(sentinal))
|
newpath = path.replace(']', unichr(sentinal))
|
||||||
newpath = newpath.replace('[', '[[]')
|
newpath = newpath.replace('[', '[[]')
|
||||||
|
@ -53,7 +53,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
|
||||||
ress['total'] = num_files
|
ress['total'] = num_files
|
||||||
|
|
||||||
if num_files <= 0:
|
if num_files <= 0:
|
||||||
fail_cb("Doesn't exist", t_file, ress)
|
fail_cb('Does not exist', t_file, ress)
|
||||||
|
|
||||||
for f in files:
|
for f in files:
|
||||||
if is_url:
|
if is_url:
|
||||||
|
@ -62,7 +62,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress):
|
||||||
client.core.add_torrent_magnet(f, t_options).addCallback(success_cb, f, ress).addErrback(fail_cb, f, ress)
|
client.core.add_torrent_magnet(f, t_options).addCallback(success_cb, f, ress).addErrback(fail_cb, f, ress)
|
||||||
else:
|
else:
|
||||||
if not os.path.exists(f):
|
if not os.path.exists(f):
|
||||||
fail_cb("Doesn't exist", f, ress)
|
fail_cb('Does not exist', f, ress)
|
||||||
continue
|
continue
|
||||||
if not os.path.isfile(f):
|
if not os.path.isfile(f):
|
||||||
fail_cb('Is a directory', f, ress)
|
fail_cb('Is a directory', f, ress)
|
||||||
|
|
|
@ -189,7 +189,7 @@ class BaseMode(CursesStdIO, component.Component):
|
||||||
self.draw_statusbars()
|
self.draw_statusbars()
|
||||||
# Update the status bars
|
# Update the status bars
|
||||||
|
|
||||||
self.add_string(1, "{!info!}Base Mode (or subclass hasn't overridden refresh)")
|
self.add_string(1, '{!info!}Base Mode (or subclass has not overridden refresh)')
|
||||||
|
|
||||||
self.stdscr.redrawwin()
|
self.stdscr.redrawwin()
|
||||||
self.stdscr.refresh()
|
self.stdscr.refresh()
|
||||||
|
@ -287,8 +287,8 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=' ', tri
|
||||||
screen.addstr(row, col, s, color)
|
screen.addstr(row, col, s, color)
|
||||||
except curses.error as ex:
|
except curses.error as ex:
|
||||||
import traceback
|
import traceback
|
||||||
log.warn("FAILED on call screen.addstr(%s, %s, '%s', %s) - max_y: %s, max_x: %s, "
|
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",
|
'curses.LINES: %s, curses.COLS: %s, Error: %s, trace:\n%s',
|
||||||
row, col, s, color, max_y, max_x, curses.LINES, curses.COLS, ex,
|
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)))
|
||||||
|
|
||||||
|
@ -333,5 +333,5 @@ def move_cursor(screen, row, col):
|
||||||
screen.move(row, col)
|
screen.move(row, col)
|
||||||
except curses.error as ex:
|
except curses.error as ex:
|
||||||
import traceback
|
import traceback
|
||||||
log.warn("Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: '%s'\nStack: %s",
|
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()))
|
||||||
|
|
|
@ -788,7 +788,7 @@ class CmdLine(BaseMode, Commander):
|
||||||
# Let's avoid listing all torrents twice if there's no pattern
|
# Let's avoid listing all torrents twice if there's no pattern
|
||||||
if not empty and torrent_id.startswith(line):
|
if not empty and torrent_id.startswith(line):
|
||||||
# Highlight the matching part
|
# Highlight the matching part
|
||||||
text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name)
|
text = '{!info!}%s{!input!}%s - "%s"' % (torrent_id[:l], torrent_id[l:], torrent_name)
|
||||||
possible_matches.append(text)
|
possible_matches.append(text)
|
||||||
if torrent_name.startswith(line):
|
if torrent_name.startswith(line):
|
||||||
text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
|
text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % (
|
||||||
|
|
|
@ -128,13 +128,13 @@ class ConnectionManager(BaseMode, PopupsHandler):
|
||||||
try:
|
try:
|
||||||
port = int(result['port']['value'])
|
port = int(result['port']['value'])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
self.report_message("Can't add host", 'Invalid port. Must be an integer')
|
self.report_message('Cannot add host', 'Invalid port. Must be an integer')
|
||||||
return
|
return
|
||||||
username = result['username']['value']
|
username = result['username']['value']
|
||||||
password = result['password']['value']
|
password = result['password']['value']
|
||||||
for host in self.config['hosts']:
|
for host in self.config['hosts']:
|
||||||
if (host[1], host[2], host[3]) == (hostname, port, username):
|
if (host[1], host[2], host[3]) == (hostname, port, username):
|
||||||
self.report_message("Can't add host", 'Host already in list')
|
self.report_message('Cannot add host', 'Host already in list')
|
||||||
return
|
return
|
||||||
newid = hashlib.sha1(str(time.time())).hexdigest()
|
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))
|
||||||
|
|
|
@ -286,7 +286,7 @@ class TorrentDetail(BaseMode, PopupsHandler):
|
||||||
fl = s[3]
|
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("/")
|
# 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)
|
self.torrentid, self._status_keys).addCallback(self.set_state)
|
||||||
|
|
||||||
|
@ -763,8 +763,8 @@ class TorrentDetail(BaseMode, PopupsHandler):
|
||||||
# Perhaps in the future: Renaming multiple files
|
# Perhaps in the future: Renaming multiple files
|
||||||
if self.marked:
|
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 "
|
'Sorry, you cannot rename multiple files, please clear '
|
||||||
"selection with {!info!}'c'{!normal!} key")
|
'selection with {!info!}"c"{!normal!} key')
|
||||||
else:
|
else:
|
||||||
_file = self.__get_file_by_num(self.current_file_idx, self.file_list)
|
_file = self.__get_file_by_num(self.current_file_idx, self.file_list)
|
||||||
old_filename = _file[0]
|
old_filename = _file[0]
|
||||||
|
|
|
@ -191,7 +191,7 @@ def parse_color_string(s, encoding='UTF-8'):
|
||||||
|
|
||||||
end = s.find('!}')
|
end = s.find('!}')
|
||||||
if end == -1:
|
if end == -1:
|
||||||
raise BadColorString("Missing closing '!}'")
|
raise BadColorString('Missing closing "!}"')
|
||||||
|
|
||||||
# Get a list of attributes in the bracketed section
|
# Get a list of attributes in the bracketed section
|
||||||
attrs = s[begin + 2:end].split(',')
|
attrs = s[begin + 2:end].split(',')
|
||||||
|
@ -218,7 +218,7 @@ def parse_color_string(s, encoding='UTF-8'):
|
||||||
if attrs[0] in schemes:
|
if attrs[0] in schemes:
|
||||||
pair = (schemes[attrs[0]][0], schemes[attrs[0]][1])
|
pair = (schemes[attrs[0]][0], schemes[attrs[0]][1])
|
||||||
if pair not in color_pairs:
|
if pair not in color_pairs:
|
||||||
log.debug("Color pair doesn't exist: %s, attrs: %s", pair, attrs)
|
log.debug('Color pair does not exist: %s, attrs: %s', pair, attrs)
|
||||||
pair = ('white', 'black')
|
pair = ('white', 'black')
|
||||||
# Get the color pair number
|
# Get the color pair number
|
||||||
color_pair = curses.color_pair(color_pairs[pair])
|
color_pair = curses.color_pair(color_pairs[pair])
|
||||||
|
@ -248,7 +248,7 @@ def parse_color_string(s, encoding='UTF-8'):
|
||||||
# terminal settings allows no colors. If background is white, we
|
# terminal settings allows no colors. If background is white, we
|
||||||
# assume this means selection, and use "white", "black" + reverse
|
# assume this means selection, and use "white", "black" + reverse
|
||||||
# To have white background and black foreground
|
# To have white background and black foreground
|
||||||
log.debug("Color pair doesn't exist: %s", pair)
|
log.debug('Color pair does not exist: %s', pair)
|
||||||
if pair[1] == 'white':
|
if pair[1] == 'white':
|
||||||
if attrs[2] == 'ignore':
|
if attrs[2] == 'ignore':
|
||||||
attrs[2] = 'reverse'
|
attrs[2] = 'reverse'
|
||||||
|
|
|
@ -257,7 +257,7 @@ def pad_string(string, length, character=' ', side='right'):
|
||||||
return '%s%s' % (string, character * diff)
|
return '%s%s' % (string, character * diff)
|
||||||
|
|
||||||
|
|
||||||
def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/"):
|
def delete_alt_backspace(input_text, input_cursor, sep_chars=' *?!._~-#$^;\'"/'):
|
||||||
"""
|
"""
|
||||||
Remove text from input_text on ALT+backspace
|
Remove text from input_text on ALT+backspace
|
||||||
Stop removing when countering any of the sep chars
|
Stop removing when countering any of the sep chars
|
||||||
|
|
|
@ -885,7 +885,7 @@ class ComboInput(InputField):
|
||||||
msg = c[1]
|
msg = c[1]
|
||||||
break
|
break
|
||||||
if msg is None:
|
if msg is None:
|
||||||
log.warn("Setting a value '%s' found found in choices: %s", val, self.choices)
|
log.warn('Setting value "%s" found nothing in choices: %s', val, self.choices)
|
||||||
self.fmt_keys.update({'msg': msg})
|
self.fmt_keys.update({'msg': msg})
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -48,7 +48,7 @@ class BaseInputPane(InputKeyHandler):
|
||||||
self.last_lineoff_move = 0
|
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'",
|
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__)
|
self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__)
|
||||||
raise AttributeError('visible_content_pane_height')
|
raise AttributeError('visible_content_pane_height')
|
||||||
|
|
||||||
|
@ -81,7 +81,7 @@ class BaseInputPane(InputKeyHandler):
|
||||||
continue
|
continue
|
||||||
if e.name == input_element.name:
|
if e.name == input_element.name:
|
||||||
import traceback
|
import traceback
|
||||||
log.warn("Input element with name '%s' already exists in input pane (%s):\n%s",
|
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
|
return
|
||||||
|
|
||||||
|
|
|
@ -148,5 +148,5 @@ class BaseWindow(object):
|
||||||
self.screen.noutrefresh(pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol)
|
self.screen.noutrefresh(pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol)
|
||||||
except curses.error as ex:
|
except curses.error as ex:
|
||||||
import traceback
|
import traceback
|
||||||
log.warn("Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: '%s'\nStack: %s",
|
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()))
|
||||||
|
|
|
@ -163,7 +163,7 @@ class AboutDialog(object):
|
||||||
'Pål-Eivind Johnsen', 'pano', 'Paolo Naldini', 'Paracelsus',
|
'Pål-Eivind Johnsen', 'pano', 'Paolo Naldini', 'Paracelsus',
|
||||||
'Patryk13_03', 'Patryk Skorupa', 'PattogoTehen', 'Paul Lange',
|
'Patryk13_03', 'Patryk Skorupa', 'PattogoTehen', 'Paul Lange',
|
||||||
'Pavcio', 'Paweł Wysocki', 'Pedro Brites Moita',
|
'Pavcio', 'Paweł Wysocki', 'Pedro Brites Moita',
|
||||||
'Pedro Clemente Pereira Neto', 'Pekka \"PEXI\" Niemistö', 'Penegal',
|
'Pedro Clemente Pereira Neto', 'Pekka "PEXI" Niemistö', 'Penegal',
|
||||||
'Penzo', 'perdido', 'Peter Kotrcka', 'Peter Skov',
|
'Penzo', 'perdido', 'Peter Kotrcka', 'Peter Skov',
|
||||||
'Peter Van den Bosch', 'Petter Eklund', 'Petter Viklund',
|
'Peter Van den Bosch', 'Petter Eklund', 'Petter Viklund',
|
||||||
'phatsphere', 'Phenomen', 'Philipi', 'Philippides Homer', 'phoenix',
|
'phatsphere', 'Phenomen', 'Philipi', 'Philippides Homer', 'phoenix',
|
||||||
|
|
|
@ -223,7 +223,7 @@ def associate_magnet_links(overwrite=False):
|
||||||
gconf_client = gconf.client_get_default()
|
gconf_client = gconf.client_get_default()
|
||||||
if (gconf_client.get(key) and overwrite) or not gconf_client.get(key):
|
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
|
# 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'"):
|
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/needs_terminal', False)
|
||||||
gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True)
|
gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True)
|
||||||
log.info('Deluge registered as default magnet uri handler!')
|
log.info('Deluge registered as default magnet uri handler!')
|
||||||
|
|
|
@ -334,7 +334,7 @@ class ConnectionManager(component.Component):
|
||||||
self.__update_buttons()
|
self.__update_buttons()
|
||||||
|
|
||||||
row[HOSTLIST_COL_STATUS] = 'Connected'
|
row[HOSTLIST_COL_STATUS] = 'Connected'
|
||||||
log.debug("Query daemon's info")
|
log.debug('Query daemon info')
|
||||||
client.daemon.info().addCallback(on_info, row)
|
client.daemon.info().addCallback(on_info, row)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
@ -455,9 +455,9 @@ class ConnectionManager(component.Component):
|
||||||
if ex.errno == ENOENT:
|
if ex.errno == ENOENT:
|
||||||
ErrorDialog(
|
ErrorDialog(
|
||||||
_('Unable to start daemon!'),
|
_('Unable to start daemon!'),
|
||||||
_("Deluge cannot find the 'deluged' executable, it is "
|
_('Deluge cannot find the `deluged` executable, check that '
|
||||||
'likely that you forgot to install the deluged package '
|
'the deluged package is installed, or added to your PATH.')).run()
|
||||||
"or it's not in your PATH.")).run()
|
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
raise ex
|
raise ex
|
||||||
|
|
|
@ -325,7 +325,7 @@ class FilesTab(Tab):
|
||||||
for select in selected:
|
for select in selected:
|
||||||
path = self.get_file_path(select).split('/')
|
path = self.get_file_path(select).split('/')
|
||||||
filepath = os.path.join(status['download_location'], *path)
|
filepath = os.path.join(status['download_location'], *path)
|
||||||
log.debug("Open file '%s'", filepath)
|
log.debug('Open file: %s', filepath)
|
||||||
timestamp = gtk.get_current_event_time()
|
timestamp = gtk.get_current_event_time()
|
||||||
open_file(filepath, timestamp=timestamp)
|
open_file(filepath, timestamp=timestamp)
|
||||||
|
|
||||||
|
@ -338,7 +338,7 @@ class FilesTab(Tab):
|
||||||
for select in selected:
|
for select in selected:
|
||||||
path = self.get_file_path(select).split('/')
|
path = self.get_file_path(select).split('/')
|
||||||
filepath = os.path.join(status['download_location'], *path)
|
filepath = os.path.join(status['download_location'], *path)
|
||||||
log.debug("Show file '%s'", filepath)
|
log.debug('Show file: %s', filepath)
|
||||||
timestamp = gtk.get_current_event_time()
|
timestamp = gtk.get_current_event_time()
|
||||||
show_file(filepath, timestamp=timestamp)
|
show_file(filepath, timestamp=timestamp)
|
||||||
|
|
||||||
|
|
|
@ -143,18 +143,18 @@ class GtkUI(object):
|
||||||
|
|
||||||
# Setup signals
|
# Setup signals
|
||||||
def on_die(*args):
|
def on_die(*args):
|
||||||
log.debug("OS signal 'die' caught with args: %s", args)
|
log.debug('OS signal "die" caught with args: %s', args)
|
||||||
reactor.stop()
|
reactor.stop()
|
||||||
|
|
||||||
if windows_check():
|
if windows_check():
|
||||||
from win32api import SetConsoleCtrlHandler
|
from win32api import SetConsoleCtrlHandler
|
||||||
SetConsoleCtrlHandler(on_die, True)
|
SetConsoleCtrlHandler(on_die, True)
|
||||||
log.debug("Win32 'die' handler registered")
|
log.debug('Win32 "die" handler registered')
|
||||||
elif osx_check() and WINDOWING == 'quartz':
|
elif osx_check() and WINDOWING == 'quartz':
|
||||||
import gtkosx_application
|
import gtkosx_application
|
||||||
self.osxapp = gtkosx_application.gtkosx_application_get()
|
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")
|
log.debug('OSX quartz "die" handler registered')
|
||||||
|
|
||||||
# Set process name again to fix gtk issue
|
# Set process name again to fix gtk issue
|
||||||
setproctitle(getproctitle())
|
setproctitle(getproctitle())
|
||||||
|
@ -227,7 +227,7 @@ class GtkUI(object):
|
||||||
reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)
|
reactor.addSystemEventTrigger('before', 'gtkui_close', self.close)
|
||||||
|
|
||||||
def gtkui_sigint_handler(num, frame):
|
def gtkui_sigint_handler(num, frame):
|
||||||
log.debug("SIGINT signal caught - firing event: 'gtkui_close'")
|
log.debug('SIGINT signal caught, firing event: gtkui_close')
|
||||||
reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')
|
reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close')
|
||||||
|
|
||||||
signal.signal(signal.SIGINT, gtkui_sigint_handler)
|
signal.signal(signal.SIGINT, gtkui_sigint_handler)
|
||||||
|
|
|
@ -117,7 +117,7 @@ class IPCInterface(component.Component):
|
||||||
log.debug('Checking if lockfile exists: %s', lockfile)
|
log.debug('Checking if lockfile exists: %s', lockfile)
|
||||||
if os.path.lexists(lockfile):
|
if os.path.lexists(lockfile):
|
||||||
def delete_lockfile():
|
def delete_lockfile():
|
||||||
log.debug("Removing lockfile since it's stale.")
|
log.debug('Delete stale lockfile.')
|
||||||
try:
|
try:
|
||||||
os.remove(lockfile)
|
os.remove(lockfile)
|
||||||
os.remove(socket)
|
os.remove(socket)
|
||||||
|
|
|
@ -71,7 +71,7 @@ class MainWindow(component.Component):
|
||||||
|
|
||||||
def patched_connect_signals(*a, **k):
|
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()'")
|
'"component.get(\'MainWindow\').connect_signals()"')
|
||||||
self.main_builder.connect_signals = patched_connect_signals
|
self.main_builder.connect_signals = patched_connect_signals
|
||||||
|
|
||||||
# Get Gtk Builder files Main Window, New release dialog, and Tabs.
|
# Get Gtk Builder files Main Window, New release dialog, and Tabs.
|
||||||
|
|
|
@ -69,7 +69,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
|
||||||
try:
|
try:
|
||||||
self.enable_plugin(name)
|
self.enable_plugin(name)
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
log.warn("Failed to enable plugin '%s': ex: %s", name, ex)
|
log.warn('Failed to enable plugin "%s": ex: %s', name, ex)
|
||||||
|
|
||||||
self.run_on_show_prefs()
|
self.run_on_show_prefs()
|
||||||
|
|
||||||
|
|
|
@ -862,7 +862,7 @@ class Preferences(component.Component):
|
||||||
|
|
||||||
def on_plugin_action(arg):
|
def on_plugin_action(arg):
|
||||||
if not value and arg is False:
|
if not value and arg is False:
|
||||||
log.warn("Failed to enable plugin '%s'", name)
|
log.warn('Failed to enable plugin: %s', name)
|
||||||
self.plugin_liststore.set_value(row, 1, False)
|
self.plugin_liststore.set_value(row, 1, False)
|
||||||
|
|
||||||
d.addBoth(on_plugin_action)
|
d.addBoth(on_plugin_action)
|
||||||
|
|
|
@ -566,7 +566,7 @@ class TorrentView(ListView, component.Component):
|
||||||
def mark_dirty(self, torrent_id=None):
|
def mark_dirty(self, torrent_id=None):
|
||||||
for row in self.liststore:
|
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)
|
# 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:
|
if torrent_id:
|
||||||
break
|
break
|
||||||
|
|
|
@ -289,7 +289,7 @@ class TrackerIcons(Component):
|
||||||
try:
|
try:
|
||||||
os.remove(page)
|
os.remove(page)
|
||||||
except OSError as ex:
|
except OSError as ex:
|
||||||
log.warning("Couldn't remove temp file: %s", ex)
|
log.warning('Could not remove temp file: %s', ex)
|
||||||
|
|
||||||
return parser.get_icons()
|
return parser.get_icons()
|
||||||
|
|
||||||
|
|
|
@ -99,16 +99,16 @@ def start_ui():
|
||||||
try:
|
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:
|
except KeyError as ex:
|
||||||
log.error("Unable to find chosen UI: '%s'. Please choose a different UI "
|
log.error('Unable to find chosen UI: "%s". Please choose a different UI '
|
||||||
"or use '--set-default-ui' to change default UI.", selected_ui)
|
'or use "--set-default-ui" to change default UI.', selected_ui)
|
||||||
except ImportError as ex:
|
except ImportError as ex:
|
||||||
import traceback
|
import traceback
|
||||||
error_type, error_value, tb = sys.exc_info()
|
error_type, error_value, tb = sys.exc_info()
|
||||||
stack = traceback.extract_tb(tb)
|
stack = traceback.extract_tb(tb)
|
||||||
last_frame = stack[-1]
|
last_frame = stack[-1]
|
||||||
if last_frame[0] == __file__:
|
if last_frame[0] == __file__:
|
||||||
log.error("Unable to find chosen UI: '%s'. Please choose a different UI "
|
log.error('Unable to find chosen UI: "%s". Please choose a different UI '
|
||||||
"or use '--set-default-ui' to change default UI.", selected_ui)
|
'or use "--set-default-ui" to change default UI.', selected_ui)
|
||||||
else:
|
else:
|
||||||
log.exception(ex)
|
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)
|
||||||
|
|
|
@ -24,7 +24,7 @@ def set_dummy_trans(warn_msg=None):
|
||||||
|
|
||||||
def _func(*txt):
|
def _func(*txt):
|
||||||
if warn_msg:
|
if warn_msg:
|
||||||
log.warn("'%s' has been marked for translation, but translation is unavailable.", txt[0])
|
log.warn('"%s" has been marked for translation, but translation is unavailable.', txt[0])
|
||||||
return txt[0]
|
return txt[0]
|
||||||
__builtin__.__dict__['_'] = _func
|
__builtin__.__dict__['_'] = _func
|
||||||
__builtin__.__dict__['_n'] = _func
|
__builtin__.__dict__['_n'] = _func
|
||||||
|
|
|
@ -798,7 +798,7 @@ class WebApi(JSONComponent):
|
||||||
main_deferred = Deferred()
|
main_deferred = Deferred()
|
||||||
host = self._get_host(host_id)
|
host = self._get_host(host_id)
|
||||||
if not host:
|
if not host:
|
||||||
main_deferred.callback((False, _("Daemon doesn't exist")))
|
main_deferred.callback((False, _('Daemon does not exist')))
|
||||||
return main_deferred
|
return main_deferred
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
@ -895,7 +895,7 @@ class WebApi(JSONComponent):
|
||||||
web_config = component.get('DelugeWeb').config
|
web_config = component.get('DelugeWeb').config
|
||||||
for key in config.keys():
|
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)
|
log.warn('Ignored attempt to overwrite web config key: %s', key)
|
||||||
continue
|
continue
|
||||||
if isinstance(config[key], basestring):
|
if isinstance(config[key], basestring):
|
||||||
config[key] = config[key].encode('utf8')
|
config[key] = config[key].encode('utf8')
|
||||||
|
|
|
@ -59,7 +59,7 @@ class PluginManager(PluginManagerBase, component.Component):
|
||||||
try:
|
try:
|
||||||
plugin = component.get('WebPlugin.' + name)
|
plugin = component.get('WebPlugin.' + name)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
log.debug("'%s' plugin contains no WebUI code, ignoring WebUI disable call.", name)
|
log.debug('%s plugin contains no WebUI code, ignoring WebUI disable call.', name)
|
||||||
return
|
return
|
||||||
|
|
||||||
info = gather_info(plugin)
|
info = gather_info(plugin)
|
||||||
|
@ -81,7 +81,7 @@ class PluginManager(PluginManagerBase, component.Component):
|
||||||
try:
|
try:
|
||||||
plugin = component.get('WebPlugin.' + name)
|
plugin = component.get('WebPlugin.' + name)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
log.info("'%s' plugin contains no WebUI code, ignoring WebUI enable call.", name)
|
log.info('%s plugin contains no WebUI code, ignoring WebUI enable call.', name)
|
||||||
return
|
return
|
||||||
|
|
||||||
info = gather_info(plugin)
|
info = gather_info(plugin)
|
||||||
|
|
|
@ -219,7 +219,7 @@ class LookupResource(resource.Resource, component.Component):
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def render(self, request):
|
def render(self, request):
|
||||||
log.debug("Requested path: '%s'", request.lookup_path)
|
log.debug('Requested path: %s', request.lookup_path)
|
||||||
path = os.path.dirname(request.lookup_path)
|
path = os.path.dirname(request.lookup_path)
|
||||||
|
|
||||||
if path not in self.__paths:
|
if path not in self.__paths:
|
||||||
|
@ -230,7 +230,7 @@ class LookupResource(resource.Resource, component.Component):
|
||||||
for directory in self.__paths[path]:
|
for directory in self.__paths[path]:
|
||||||
if os.path.join(directory, filename):
|
if os.path.join(directory, filename):
|
||||||
path = os.path.join(directory, filename)
|
path = os.path.join(directory, filename)
|
||||||
log.debug("Serving path: '%s'", path)
|
log.debug('Serving path: %s', path)
|
||||||
mime_type = mimetypes.guess_type(path)
|
mime_type = mimetypes.guess_type(path)
|
||||||
request.setHeader('content-type', mime_type[0])
|
request.setHeader('content-type', mime_type[0])
|
||||||
with open(path, 'rb') as _file:
|
with open(path, 'rb') as _file:
|
||||||
|
@ -373,7 +373,7 @@ class ScriptResource(resource.Resource, component.Component):
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def render(self, request):
|
def render(self, request):
|
||||||
log.debug("Requested path: '%s'", request.lookup_path)
|
log.debug('Requested path: %s', request.lookup_path)
|
||||||
|
|
||||||
for script_type in ('dev', 'debug', 'normal'):
|
for script_type in ('dev', 'debug', 'normal'):
|
||||||
scripts = self.__scripts[script_type]['scripts']
|
scripts = self.__scripts[script_type]['scripts']
|
||||||
|
@ -390,7 +390,7 @@ class ScriptResource(resource.Resource, component.Component):
|
||||||
if not os.path.isfile(path):
|
if not os.path.isfile(path):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
log.debug("Serving path: '%s'", path)
|
log.debug('Serving path: %s', path)
|
||||||
mime_type = mimetypes.guess_type(path)
|
mime_type = mimetypes.guess_type(path)
|
||||||
request.setHeader('content-type', mime_type[0])
|
request.setHeader('content-type', mime_type[0])
|
||||||
with open(path, 'rb') as _file:
|
with open(path, 'rb') as _file:
|
||||||
|
@ -517,13 +517,13 @@ class TopLevel(resource.Resource):
|
||||||
|
|
||||||
if not self.js.has_script_type_files(script_type):
|
if not self.js.has_script_type_files(script_type):
|
||||||
if not dev_ver:
|
if not dev_ver:
|
||||||
log.warning("Failed to enable WebUI '%s' mode, script files are missing!", script_type)
|
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.
|
# 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):
|
if self.js.has_script_type_files(alt_script_type):
|
||||||
script_type = alt_script_type
|
script_type = alt_script_type
|
||||||
if not dev_ver:
|
if not dev_ver:
|
||||||
log.warning("WebUI falling back to '%s' mode.", script_type)
|
log.warning('WebUI falling back to "%s" mode.', script_type)
|
||||||
break
|
break
|
||||||
|
|
||||||
scripts = component.get('Scripts').get_scripts(script_type)
|
scripts = component.get('Scripts').get_scripts(script_type)
|
||||||
|
@ -592,7 +592,7 @@ class DelugeWeb(component.Component):
|
||||||
self.plugins = PluginManager()
|
self.plugins = PluginManager()
|
||||||
|
|
||||||
def _on_language_changed(self, key, value):
|
def _on_language_changed(self, key, value):
|
||||||
log.debug("Setting UI language '%s'", value)
|
log.debug('Setting UI language %s', value)
|
||||||
lang.set_language(value)
|
lang.set_language(value)
|
||||||
|
|
||||||
def install_signal_handlers(self):
|
def install_signal_handlers(self):
|
||||||
|
|
|
@ -58,7 +58,7 @@ def check_missing_markup(js_dir):
|
||||||
for match in string_re.finditer(line):
|
for match in string_re.finditer(line):
|
||||||
for string in match.groups():
|
for string in match.groups():
|
||||||
# Ignore string that contains only digits or specificied strings in skip.
|
# Ignore string that contains only digits or specificied strings in skip.
|
||||||
if not string or string.split("'")[1].isdigit() or any(x in string for x in skip):
|
if not string or string.split('\'')[1].isdigit() or any(x in string for x in skip):
|
||||||
continue
|
continue
|
||||||
locations = strings.get(string, [])
|
locations = strings.get(string, [])
|
||||||
locations.append((os.path.join(root, filename), str(lineno + 1)))
|
locations.append((os.path.join(root, filename), str(lineno + 1)))
|
||||||
|
@ -97,7 +97,7 @@ def create_gettext_js(js_dir):
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
gettext_fname = create_gettext_js(WEBUI_JS_DIR)
|
gettext_fname = create_gettext_js(WEBUI_JS_DIR)
|
||||||
print("Created '%s'" % gettext_fname)
|
print('Created: %s' % gettext_fname)
|
||||||
missed_markup = check_missing_markup(WEBUI_JS_DIR)
|
missed_markup = check_missing_markup(WEBUI_JS_DIR)
|
||||||
if missed_markup:
|
if missed_markup:
|
||||||
print('Possible missed text for translation markup:')
|
print('Possible missed text for translation markup:')
|
||||||
|
|
|
@ -209,7 +209,7 @@ def main():
|
||||||
# do it
|
# do it
|
||||||
if not args:
|
if not args:
|
||||||
print('No input file given', file=sys.stderr)
|
print('No input file given', file=sys.stderr)
|
||||||
print("Try `msgfmt --help' for more information.", file=sys.stderr)
|
print('Try `msgfmt --help` for more information.', file=sys.stderr)
|
||||||
return
|
return
|
||||||
|
|
||||||
for filename in args:
|
for filename in args:
|
||||||
|
|
6
setup.py
6
setup.py
|
@ -237,7 +237,7 @@ class Build(_build):
|
||||||
|
|
||||||
|
|
||||||
class InstallData(_install_data):
|
class InstallData(_install_data):
|
||||||
"""Custom class to fix 'setup install' copying data files to incorrect location. (Bug #1389)"""
|
"""Custom class to fix `setup install` copying data files to incorrect location. (Bug #1389)"""
|
||||||
|
|
||||||
def finalize_options(self):
|
def finalize_options(self):
|
||||||
self.install_dir = None
|
self.install_dir = None
|
||||||
|
@ -274,12 +274,12 @@ class CleanPlugins(cmd.Command):
|
||||||
|
|
||||||
# Delete the .eggs
|
# Delete the .eggs
|
||||||
if path[-4:] == '.egg':
|
if path[-4:] == '.egg':
|
||||||
print("Deleting egg file '%s'" % path)
|
print('Deleting egg file "%s"' % path)
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
# Delete the .egg-link
|
# Delete the .egg-link
|
||||||
if path[-9:] == '.egg-link':
|
if path[-9:] == '.egg-link':
|
||||||
print("Deleting egg link '%s'" % path)
|
print('Deleting egg link "%s"' % path)
|
||||||
os.remove(path)
|
os.remove(path)
|
||||||
|
|
||||||
egg_info_dir_path = 'deluge/plugins/*/*.egg-info'
|
egg_info_dir_path = 'deluge/plugins/*/*.egg-info'
|
||||||
|
|
Loading…
Reference in New Issue