deluge package
Subpackages
- deluge.core package
- Submodules
- deluge.core.alertmanager module
- deluge.core.authmanager module
- deluge.core.core module
- deluge.core.daemon module
- deluge.core.daemon_entry module
- deluge.core.eventmanager module
- deluge.core.filtermanager module
- deluge.core.pluginmanager module
- deluge.core.preferencesmanager module
- deluge.core.rpcserver module
- deluge.core.torrent module
- deluge.core.torrentmanager module
- Module contents
- deluge.i18n package
- deluge.ui package
- Subpackages
- deluge.ui.console package
- deluge.ui.gtk3 package
- Submodules
- deluge.ui.gtk3.aboutdialog module
- deluge.ui.gtk3.addtorrentdialog module
- deluge.ui.gtk3.common module
- deluge.ui.gtk3.connectionmanager module
- deluge.ui.gtk3.createtorrentdialog module
- deluge.ui.gtk3.details_tab module
- deluge.ui.gtk3.dialogs module
- deluge.ui.gtk3.edittrackersdialog module
- deluge.ui.gtk3.files_tab module
- deluge.ui.gtk3.filtertreeview module
- deluge.ui.gtk3.gtkui module
- deluge.ui.gtk3.ipcinterface module
- deluge.ui.gtk3.listview module
- deluge.ui.gtk3.mainwindow module
- deluge.ui.gtk3.menubar module
- deluge.ui.gtk3.menubar_osx module
- deluge.ui.gtk3.new_release_dialog module
- deluge.ui.gtk3.options_tab module
- deluge.ui.gtk3.path_chooser module
- deluge.ui.gtk3.path_combo_chooser module
- deluge.ui.gtk3.peers_tab module
- deluge.ui.gtk3.piecesbar module
- deluge.ui.gtk3.pluginmanager module
- deluge.ui.gtk3.preferences module
- deluge.ui.gtk3.queuedtorrents module
- deluge.ui.gtk3.removetorrentdialog module
- deluge.ui.gtk3.sidebar module
- deluge.ui.gtk3.status_tab module
- deluge.ui.gtk3.statusbar module
- deluge.ui.gtk3.systemtray module
- deluge.ui.gtk3.tab_data_funcs module
- deluge.ui.gtk3.toolbar module
- deluge.ui.gtk3.torrentdetails module
- deluge.ui.gtk3.torrentview module
- deluge.ui.gtk3.torrentview_data_funcs module
- deluge.ui.gtk3.trackers_tab module
- Module contents
- deluge.ui.web package
- Submodules
- deluge.ui.client module
- deluge.ui.common module
- deluge.ui.coreconfig module
- deluge.ui.countries module
- deluge.ui.hostlist module
- deluge.ui.sessionproxy module
- deluge.ui.tracker_icons module
- deluge.ui.ui module
- deluge.ui.ui_entry module
- Module contents
- Subpackages
Submodules
deluge.argparserbase module
- class deluge.argparserbase.ArgParserBase(*args, **kwargs)
Bases:
argparse.ArgumentParser
- add_process_arg_group()
Adds a grouping of common process args to control a daemon to the parser
- parse_args(args=None)
Parse UI arguments and handle common and process group options.
Notes
Unknown arguments results in usage text printed and system exit.
- Parameters
args (list, optional) – The arguments to parse.
- Returns
argparse.Namespace – The parsed arguments.
- parse_known_ui_args(args, withhold=None)
Parse UI arguments and handle common and process group options without error.
- Parameters
args (list) – The arguments to parse.
withhold (list) – Values to ignore in the args list.
- Returns
argparse.Namespace – The parsed arguments.
- class deluge.argparserbase.DelugeTextHelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)
Bases:
argparse.RawDescriptionHelpFormatter
Help message formatter which retains formatting of all help text.
- class deluge.argparserbase.HelpAction(option_strings, dest='==SUPPRESS==', default='==SUPPRESS==', help=None)
Bases:
argparse._HelpAction
- deluge.argparserbase.find_subcommand(self, args=None, sys_argv=True)
Find if a subcommand has been supplied.
- Parameters
args (list, optional) – The argument list to search through.
sys_argv (bool) – Use sys.argv[1:] if args is None.
- Returns
int – Index of the subcommand or ‘-1’ if none found.
- deluge.argparserbase.set_default_subparser(self, name, abort_opts=None)
Sets the default argparse subparser.
- Parameters
name (str) – The name of the default subparser.
abort_opts (list) – The arguments to test for in case no subcommand is found. If any of the values are found, the default subparser will not be inserted into sys.argv.
- Returns
list – The arguments found in sys.argv if no subcommand found, else None
deluge.bencode module
- exception deluge.bencode.BTFailure
Bases:
Exception
- deluge.bencode.bdecode(x)
- deluge.bencode.bencode(x)
- deluge.bencode.decode_dict(x, f)
- deluge.bencode.decode_int(x, f)
- deluge.bencode.decode_list(x, f)
- deluge.bencode.decode_string(x, f)
- deluge.bencode.encode_bencached(x, r)
- deluge.bencode.encode_bool(x, r)
- deluge.bencode.encode_bytes(x, r)
- deluge.bencode.encode_dict(x, r)
- deluge.bencode.encode_int(x, r)
- deluge.bencode.encode_list(x, r)
- deluge.bencode.encode_string(x, r)
deluge.common module
Common functions for various parts of Deluge to use.
- exception deluge.common.InvalidSize
Bases:
Exception
- class deluge.common.VersionSplit(ver)
Bases:
object
Used for comparing version numbers.
- Parameters
ver (string) – the version
- get_comparable_versions(other)
Returns a 2-tuple of lists for use in the comparison methods.
- deluge.common.archive_files(arc_name, filepaths, message=None, rotate=10)
Compress a list of filepaths into timestamped tarball in config dir.
The archiving config directory is ‘archive’.
- Parameters
arc_name (str) – The archive output filename (appended with timestamp).
filepaths (list) – A list of the files to be archived into tarball.
- Returns
str – The full archive filepath.
- deluge.common.create_auth_file()
- deluge.common.create_localclient_account(append=False)
- deluge.common.create_magnet_uri(infohash, name=None, trackers=None)
Creates a magnet URI
- Parameters
infohash (str) – The info-hash of the torrent.
name (str, optional) – The name of the torrent.
trackers (list or dict, optional) – A list of trackers or a dict or some {tracker: tier} pairs.
- Returns
str – A magnet URI string.
- deluge.common.decode_bytes(byte_str, encoding='utf8')
Decodes a byte string and return unicode.
If it cannot decode using encoding then it will try latin1, and if that fails, try to detect the string encoding. If that fails, decode with ignore.
- Parameters
byte_str (bytes) – The byte string to decode.
encoding (str) – The encoding to try first when decoding.
- Returns
str – A unicode string.
- deluge.common.decode_string(byte_str, encoding='utf8')
Deprecated: Use decode_bytes
- deluge.common.fdate(seconds, date_only=False, precision_secs=False)
Formats a date time string in the locale’s date representation based on the system’s timezone.
- Parameters
seconds (float) – Time in seconds since the Epoch.
date_only (bool) – Whether to include only the date, False by default.
precision_secs (bool) – Include seconds in time format, False by default.
- Returns
str – A string in the locale’s datetime representation or “” if seconds < 0
- deluge.common.fpcnt(dec, precision=2)
Formats a string to display a percentage with <precision> places.
- Parameters
dec (float) – The ratio in the range [0.0, 1.0].
precision (int) – The output float precision, 2 by default.
- Returns
str – A formatted string representing a percentage.
Examples
>>> fpcnt(0.9311) '93.11%' >>> fpcnt(0.9311, precision=0) '93%'
- deluge.common.fpeer(num_peers, total_peers)
Formats a string to show ‘num_peers’ (‘total_peers’).
- Parameters
num_peers (int) – The number of connected peers.
total_peers (int) – The total number of peers.
- Returns
str – A formatted string ‘num_peers (total_peers)’ or if total_peers < 0, just ‘num_peers’.
Examples
>>> fpeer(10, 20) '10 (20)' >>> fpeer(10, -1) '10'
- deluge.common.free_space(path)
Gets the free space available at ‘path’
- Parameters
path (string) – the path to check
- Returns
the free space at path in bytes
- Return type
int
- Raises
InvalidPathError – if the path is not valid
- deluge.common.fsize(fsize_b, precision=1, shortform=False)
Formats the bytes value into a string with KiB, MiB, GiB or TiB units.
- Parameters
fsize_b (int) – The filesize in bytes.
precision (int) – The output float precision, 1 by default.
shortform (bool) – The output short|long form, False (long form) by default.
- Returns
str – A formatted string in KiB, MiB, GiB or TiB units.
Examples
>>> fsize(112245) '109.6 KiB' >>> fsize(112245, precision=0) '110 KiB' >>> fsize(112245, shortform=True) '109.6 K'
Note
This function has been refactored for performance with the fsize units being translated outside the function.
Notice that short forms K|M|G|T are synonymous here with KiB|MiB|GiB|TiB. They are powers of 1024, not 1000.
- deluge.common.fspeed(bps, precision=1, shortform=False)
Formats a string to display a transfer speed.
- Parameters
bps (int) – The speed in bytes per second.
precision (int) – The output float precision, 1 by default.
shortform (bool) – The output short|long form, False (long form) by default.
- Returns
str – A formatted string representing transfer speed.
Examples
>>> fspeed(43134) '42.1 KiB/s'
Note
Notice that short forms K|M|G|T are synonymous here with KiB|MiB|GiB|TiB. They are powers of 1024, not 1000.
- deluge.common.ftime(secs)
Formats a string to show time in a human readable form.
- Parameters
secs (int or float) – The number of seconds.
- Returns
str – A formatted time string or empty string if value is 0.
Examples
>>> ftime(23011) '6h 23m'
Note
This function has been refactored for performance.
- deluge.common.get_default_config_dir(filename=None)
- Parameters
filename (string) – if None, only the config path is returned, if provided, a path including the filename will be returned
- Returns
a file path to the config directory and optional filename
- Return type
string
- deluge.common.get_default_download_dir()
- Returns
the default download directory
- Return type
string
- deluge.common.get_localhost_auth()
Grabs the localclient auth line from the ‘auth’ file and creates a localhost URI.
- Returns
tuple – With the username and password to login as.
- deluge.common.get_magnet_info(uri)
Parse torrent information from magnet link.
- Parameters
uri (str) – The magnet link.
- Returns
dict – Information about the magnet link.
Format of the magnet dict:
{ "name": the torrent name, "info_hash": the torrents info_hash, "files_tree": empty value for magnet links }
- deluge.common.get_os_version()
Parse and return the os version information.
Converts the platform ver tuple to a string.
- Returns
str – The os version info.
- deluge.common.get_path_size(path)
Gets the size in bytes of ‘path’
- Parameters
path (string) – the path to check for size
- Returns
the size in bytes of the path or -1 if the path does not exist
- Return type
int
- deluge.common.get_pixmap(fname)
Provides easy access to files in the deluge/ui/data/pixmaps folder within the Deluge egg
- Parameters
fname (string) – the filename to look for
- Returns
a path to a pixmap file included with Deluge
- Return type
string
- deluge.common.get_version()
The program version from the egg metadata.
- Returns
str – The version of Deluge.
- deluge.common.is_infohash(infohash)
A check to determine if a string is a valid infohash.
- Parameters
infohash (str) – The string to check.
- Returns
bool – True if valid infohash, False otherwise.
- deluge.common.is_interface(interface)
Check if interface is a valid IP or network adapter.
- Parameters
interface (str) – The IP or interface name to test.
- Returns
bool – Whether interface is valid is not.
Examples
Windows: >>> is_interface(‘{7A30AE62-23ZA-3744-Z844-A5B042524871}’) >>> is_interface(‘127.0.0.1’) True Linux: >>> is_interface(‘lo’) >>> is_interface(‘127.0.0.1’) True
- deluge.common.is_interface_name(name)
Returns True if an interface name exists.
- Parameters
name (str) – The Interface to test. eg. eth0 linux. GUID on Windows.
- Returns
bool – Whether name is valid or not.
Examples
>>> is_interface_name("eth0") True >>> is_interface_name("{7A30AE62-23ZA-3744-Z844-A5B042524871}") True
- deluge.common.is_ip(ip)
A test to see if ‘ip’ is a valid IPv4 or IPv6 address.
- Parameters
ip (str) – The IP to test.
- Returns
bool – Whether IP is valid is not.
Examples
>>> is_ip("192.0.2.0") True >>> is_ip("2001:db8::") True
- deluge.common.is_ipv4(ip)
A test to see if ‘ip’ is a valid IPv4 address.
- Parameters
ip (str) – The IP to test.
- Returns
bool – Whether IP is valid is not.
Examples
>>> is_ipv4("192.0.2.0") True
- deluge.common.is_ipv6(ip)
A test to see if ‘ip’ is a valid IPv6 address.
- Parameters
ip (str) – The IP to test.
- Returns
bool – Whether IP is valid is not.
Examples
>>> is_ipv6("2001:db8::") True
- deluge.common.is_magnet(uri)
A check to determine if a URI is a valid bittorrent magnet URI
- Parameters
uri (string) – the URI to check
- Returns
True or False
- Return type
bool
- Example
>>> is_magnet('magnet:?xt=urn:btih:SU5225URMTUEQLDXQWRB2EQWN6KLTYKN') True
- deluge.common.is_process_running(pid)
Verify if the supplied pid is a running process.
- Parameters
pid (int) – The pid to check.
- Returns
bool – True if pid is a running process, False otherwise.
- deluge.common.is_url(url)
A simple test to check if the URL is valid
- Parameters
url (string) – the URL to test
- Returns
True or False
- Return type
bool
- Example
>>> is_url('http://deluge-torrent.org') True
- deluge.common.linux_check()
Checks if the current platform is Linux
- Returns
True or False
- Return type
bool
- deluge.common.open_file(path, timestamp=None)
Opens a file or folder using the system configured program.
- Parameters
path (str) – The path to the file or folder to open.
timestamp (int, optional) – An event request timestamp.
- deluge.common.open_url_in_browser(url)
Opens a URL in the desktop’s default browser
- Parameters
url (string) – the URL to open
- deluge.common.osx_check()
Checks if the current platform is Mac OS X
- Returns
True or False
- Return type
bool
- deluge.common.parse_human_size(size)
Parse a human readable data size and return the number of bytes.
- Parameters
size (str) – The human readable file size to parse (a string).
- Returns
int – The corresponding size in bytes.
- Raises
InvalidSize – when the input can’t be parsed.
- deluge.common.resource_filename(module, path)
Get filesystem path for a non-python resource.
Abstracts getting module resource files. Originally created to workaround pkg_resources.resource_filename limitations with multiple Deluge packages installed.
- Return type
str
- deluge.common.run_profiled(func, *args, **kwargs)
Profile a function with cProfile
- Parameters
func (func) – The function to profile
*args (tuple) – The arguments to pass to the function
do_profile (bool, optional) – If profiling should be performed. Defaults to True.
output_file (str, optional) – Filename to save profile results. If None, print to stdout. Defaults to None.
- deluge.common.set_env_variable(name, value)
- Parameters
name – environment variable name
value – environment variable value
This function ensures that changes to an environment variable are applied to each copy of the environment variables used by a process. Starting from Python 2.4, os.environ changes only apply to the copy Python keeps (os.environ) and are no longer automatically applied to the other copies for the process.
On Microsoft Windows, each process has multiple copies of the environment variables, one managed by the OS and one managed by the C library. We also need to take care of the fact that the C library used by Python is not necessarily the same as the C library used by pygtk and friends. This because the latest releases of pygtk and friends are built with mingw32 and are thus linked against msvcrt.dll. The official gtk+ binaries have always been built in this way.
Basen on _putenv in TransUtils.py from sourceforge project gramps http://sourceforge.net/p/gramps/code/HEAD/tree/branches/maintenance/gramps32/src/TransUtils.py
- deluge.common.show_file(path, timestamp=None)
Shows (highlights) a file or folder using the system configured file manager.
- Parameters
path (str) – The path to the file or folder to show.
timestamp (int, optional) – An event request timestamp.
- deluge.common.tokenize(text)
Tokenize a text into numbers and strings.
- Parameters
text (str) – The text to tokenize (a string).
- Returns
list – A list of strings and/or numbers.
Note
This function is used to implement robust tokenization of user input It automatically coerces integer and floating point numbers, ignores whitespace and knows how to separate numbers from strings even without whitespace.
Possible optimization: move the 2 regexes outside of function.
- deluge.common.translate_size_units()
For performance reasons these units are translated outside the function
- deluge.common.utf8_encode_structure(data)
Recursively convert all unicode keys and values in a data structure to utf8.
e.g. converting keys and values for a dict with nested dicts and lists etc.
- Parameters
data (any) – This can be any structure, dict, list or tuple.
- Returns
input type – The data with unicode keys and values converted to utf8.
- deluge.common.utf8_encoded(str_, encoding='utf8')
Deprecated: Use encode or decode_bytes if needed
- deluge.common.vista_check()
Checks if the current platform is Windows Vista
- Returns
True or False
- Return type
bool
- deluge.common.windows_check()
Checks if the current platform is Windows
- Returns
True or False
- Return type
bool
deluge.component module
- class deluge.component.Component(name, interval=1, depend=None)
Bases:
object
Component objects are singletons managed by the
ComponentRegistry
.When a new Component object is instantiated, it will be automatically registered with the
ComponentRegistry
.The ComponentRegistry has the ability to start, stop, pause and shutdown the components registered with it.
Events:
- start() - This method is called when the client has connected to a
Deluge core.
- stop() - This method is called when the client has disconnected from a
Deluge core.
- update() - This method is called every 1 second by default while the
Component is in a Started state. The interval can be specified during instantiation. The update() timer can be paused by instructing the
ComponentRegistry
to pause this Component.
pause() - This method is called when the component is being paused.
- resume() - This method is called when the component resumes from a Paused
state.
- shutdown() - This method is called when the client is exiting. If the
Component is in a “Started” state when this is called, a call to stop() will be issued prior to shutdown().
States:
A Component can be in one of these 5 states.
- Started - The Component has been started by the
ComponentRegistry
and will have it’s update timer started.
- Starting - The Component has had it’s start method called, but it hasn’t
fully started yet.
Stopped - The Component has either been stopped or has yet to be started.
- Stopping - The Component has had its stop method called, but it hasn’t
fully stopped yet.
- Paused - The Component has had its update timer stopped, but will
still be considered in a Started state.
- __init__(name, interval=1, depend=None)
Initialize component.
- Parameters
name (str) – Name of component.
interval (int, optional) – The interval in seconds to call the update function.
depend (list, optional) – The names of components this component depends on.
- get_state()
- pause()
- resume()
- shutdown()
- start()
- stop()
- update()
- exception deluge.component.ComponentAlreadyRegistered
Bases:
Exception
- exception deluge.component.ComponentException(message, tb)
Bases:
Exception
- class deluge.component.ComponentRegistry
Bases:
object
The ComponentRegistry holds a list of currently registered
Component
objects.It is used to manage the Components by starting, stopping, pausing and shutting them down.
- deregister(obj)
Deregister a component from the registry. A stop will be issued to the component prior to deregistering it.
- Parameters
obj (Component) – a component object to deregister
- Returns
Deferred –
- a deferred object that will fire once the Component has been
successfully deregistered
- pause(names=None)
Pause Components that are currently in a Started state.
Note
If no names are specified then all registered components will be paused.
- Parameters
names (list) – A list of Components to pause.
- Returns
Deferred – Fired once all Components have been successfully paused.
- register(obj)
Register a component object with the registry.
Note
This is done automatically when a Component object is instantiated.
- Parameters
obj (Component) – A component object to register.
- Raises
ComponentAlreadyRegistered – If a component with the same name is already registered.
- resume(names=None)
Resume Components that are currently in a Paused state.
Note
If no names are specified then all registered components will be resumed.
- Parameters
names (list) – A list of Components to to resume.
- Returns
Deferred – Fired once all Components have been successfully resumed.
- shutdown()
Shutdown all Components regardless of state.
This will call stop() on all the components prior to shutting down. This should be called when the program is exiting to ensure all Components have a chance to properly shutdown.
- Returns
Deferred – Fired once all Components have been successfully shut down.
- start(names=None)
Start Components, and their dependencies, that are currently in a Stopped state.
Note
If no names are specified then all registered components will be started.
- Parameters
names (list) – A list of Components to start and their dependencies.
- Returns
Deferred – Fired once all Components have been successfully started.
- stop(names=None)
Stop Components that are currently not in a Stopped state.
Note
If no names are specified then all registered components will be stopped.
- Parameters
names (list) – A list of Components to stop.
- Returns
Deferred – Fired once all Components have been successfully stopped.
- update()
Update all Components that are in a Started state.
- deluge.component.deregister(obj)
Deregister a component from the registry. A stop will be issued to the component prior to deregistering it.
- Parameters
obj (Component) – a component object to deregister
- Returns
Deferred –
- a deferred object that will fire once the Component has been
successfully deregistered
- deluge.component.get(name)
Return a reference to a component.
- Parameters
name (str) – The Component name to get.
- Returns
Component – The Component object.
- Raises
KeyError – If the Component does not exist.
- deluge.component.pause(names=None)
Pause Components that are currently in a Started state.
Note
If no names are specified then all registered components will be paused.
- Parameters
names (list) – A list of Components to pause.
- Returns
Deferred – Fired once all Components have been successfully paused.
- deluge.component.resume(names=None)
Resume Components that are currently in a Paused state.
Note
If no names are specified then all registered components will be resumed.
- Parameters
names (list) – A list of Components to to resume.
- Returns
Deferred – Fired once all Components have been successfully resumed.
- deluge.component.shutdown()
Shutdown all Components regardless of state.
This will call stop() on all the components prior to shutting down. This should be called when the program is exiting to ensure all Components have a chance to properly shutdown.
- Returns
Deferred – Fired once all Components have been successfully shut down.
- deluge.component.start(names=None)
Start Components, and their dependencies, that are currently in a Stopped state.
Note
If no names are specified then all registered components will be started.
- Parameters
names (list) – A list of Components to start and their dependencies.
- Returns
Deferred – Fired once all Components have been successfully started.
- deluge.component.stop(names=None)
Stop Components that are currently not in a Stopped state.
Note
If no names are specified then all registered components will be stopped.
- Parameters
names (list) – A list of Components to stop.
- Returns
Deferred – Fired once all Components have been successfully stopped.
- deluge.component.update()
Update all Components that are in a Started state.
deluge.config module
Deluge Config Module
This module is used for loading and saving of configuration files.. or anything really.
The format of the config file is two json encoded dicts:
<version dict> <content dict>
The version dict contains two keys: file and format. The format version is controlled by the Config class. It should only be changed when anything below it is changed directly by the Config class. An example of this would be if we changed the serializer for the content to something different.
The config file version is changed by the ‘owner’ of the config file. This is to signify that there is a change in the naming of some config keys or something similar along those lines.
The content is simply the dict to be saved and will be serialized before being written.
Converting
Since the format of the config could change, there needs to be a way to have the Config object convert to newer formats. To do this, you will need to register conversion functions for various versions of the config file. Note that this can only be done for the ‘config file version’ and not for the ‘format’ version as this will be done internally.
- class deluge.config.Config(filename, defaults=None, config_dir=None, file_version=1, log_mask_funcs=None)
Bases:
object
This class is used to access/create/modify config files.
- Parameters
filename (str) – The config filename.
defaults (dict) – The default config values to insert before loading the config file.
config_dir (str) – the path to the config directory.
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 setup to convert old config files. (default: 1)
log_mask_funcs (dict) – A dict of key:function, used to mask sensitive key values (e.g. passwords) when logging is enabled.
- apply_all()
Calls all set functions.
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_set_function('test', cb, apply_now=False) >>> config.apply_all() test 5
- apply_set_functions(key)
Calls set functions for :param:key.
- Parameters
key (str) – the config key
- callLater(period, func, *args, **kwargs)
Wrapper around reactor.callLater for test purpose.
- property config
The config dictionary
- property config_file
- del_item(key)
Deletes item with a specific key from the configuration.
- Parameters
key (str) – The item which you wish to delete.
- Raises
ValueError – If ‘key’ is not in the config dictionary.
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> del config['test']
- get(key, default=None)
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 never raises a KeyError.
- Parameters
key (str) – the item for which you want it’s value
default (any) – the default value if key is missing
- Returns
any – The value of item ‘key’ or default.
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> config.get('test', 10) 5 >>> config.get('bad_key', 10) 10
- get_item(key)
Gets the value of item ‘key’.
- Parameters
key (str) – The item for which you want it’s value.
- Returns
any – The value of item ‘key’.
- Raises
ValueError – If ‘key’ is not in the config dictionary.
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> config['test'] 5
- load(filename=None)
Load a config file.
- Parameters
filename (str) – If None, uses filename set in object initialization
- register_change_callback(callback)
Registers a callback function for any changed value.
Will be called when any value is changed in the config dictionary.
- Parameters
callback (func) – The function to call with parameters: f(key, value).
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_change_callback(cb)
- register_set_function(key, function, apply_now=True)
Register a function to be called when a config value changes.
- Parameters
key (str) – The item to monitor for change.
function (func) – The function to call when the value changes, f(key, value).
apply_now (bool) – If True, the function will be called immediately after it’s registered.
Examples
>>> config = Config('test.conf', defaults={'test': 5}) >>> def cb(key, value): ... print key, value ... >>> config.register_set_function('test', cb, apply_now=True) test 5
- run_converter(input_range, output_version, func)
Runs a function that will convert file versions.
- Parameters
input_range (tuple) – (int, int) The range of input versions this function will accept.
output_version (int) – The version this function will convert to.
func (func) – The function that will do the conversion, it will take the config dict as an argument and return the augmented dict.
- Raises
ValueError – If output_version is less than the input_range.
- save(filename=None)
Save configuration to disk.
- Parameters
filename (str) – If None, uses filename set in object initialization
- Returns
bool – Whether or not the save succeeded.
- set_item(key, value, default=False)
Sets item ‘key’ to ‘value’ in the config dictionary.
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.
- Parameters
key (str) – Item to change to change.
value (any) – The value to change item to, must be same type as what is currently in the config.
default (optional, bool) – When setting a default value skip func or save callbacks.
- Raises
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.
Examples
>>> config = Config('test.conf') >>> config['test'] = 5 >>> config['test'] 5
- deluge.config.cast_to_existing_type(value, old_value)
Attempt to convert new value type to match old value type
- deluge.config.find_json_objects(text, decoder=<json.decoder.JSONDecoder object>)
Find json objects in text.
- Parameters
text (str) – The text to find json objects within.
- Returns
list –
- A list of tuples containing start and end locations of json
objects in the text. e.g. [(start, end), …]
deluge.configmanager module
- deluge.configmanager.ConfigManager(config, defaults=None, file_version=1)
- deluge.configmanager.close(config)
- deluge.configmanager.get_config_dir(filename=None)
- deluge.configmanager.set_config_dir(directory)
Sets the config directory, else just uses default
deluge.conftest module
deluge.crypto_utils module
- deluge.crypto_utils.check_ssl_keys()
Check for SSL cert/key and create them if necessary
- deluge.crypto_utils.generate_ssl_keys()
This method generates a new SSL key/cert.
- deluge.crypto_utils.get_context_factory(cert_path, pkey_path)
OpenSSL context factory.
Generates an OpenSSL context factory using Twisted’s CertificateOptions class. This will keep a server cipher order.
- Parameters
cert_path (string) – The path to the certificate file
pkey_path (string) – The path to the private key file
- Returns
twisted.internet.ssl.CertificateOptions – An OpenSSL context factory
deluge.decorators module
- class deluge.decorators.CoroutineDeferred(coro)
Bases:
twisted.internet.defer.Deferred
Wraps a coroutine in a Deferred. It will dynamically pass through the underlying coroutine without wrapping where apporpriate.
- activate()
If the result wasn’t awaited before the next context switch, we turn it into a deferred.
- addCallbacks(*args, **kwargs)
- deluge.decorators.deprecated(func)
This is a decorator which can be used to mark function as deprecated.
It will result in a warning being emitted when the function is used.
- deluge.decorators.maybe_coroutine(f)
Wraps a coroutine function to make it usable as a normal function that returns a Deferred.
- Return type
Callable
[...
,~_RetT
]
- deluge.decorators.overrides(*args)
Decorater function to specify when class methods override super class methods.
When used as @overrides def funcname
the argument will be the funcname function.
When used as @overrides(BaseClass) def funcname
the argument will be the BaseClass
- deluge.decorators.proxy(proxy_func)
Factory class which returns a decorator that passes the decorated function to a proxy function
- Parameters
proxy_func (function) – the proxy function
deluge.error module
- exception deluge.error.AddTorrentError(*args, **kwargs)
Bases:
deluge.error.DelugeError
- exception deluge.error.AuthManagerError(*args, **kwargs)
Bases:
deluge.error._UsernameBasedPasstroughError
- exception deluge.error.AuthenticationRequired(*args, **kwargs)
Bases:
deluge.error._UsernameBasedPasstroughError
- exception deluge.error.BadLoginError(*args, **kwargs)
Bases:
deluge.error._UsernameBasedPasstroughError
- exception deluge.error.DaemonRunningError(*args, **kwargs)
Bases:
deluge.error.DelugeError
- exception deluge.error.DelugeError(*args, **kwargs)
Bases:
Exception
- exception deluge.error.IncompatibleClient(*args, **kwargs)
Bases:
deluge.error._ClientSideRecreateError
- exception deluge.error.InvalidPathError(*args, **kwargs)
Bases:
deluge.error.DelugeError
- exception deluge.error.InvalidTorrentError(*args, **kwargs)
Bases:
deluge.error.DelugeError
- exception deluge.error.LibtorrentImportError
Bases:
ImportError
- exception deluge.error.NotAuthorizedError(*args, **kwargs)
Bases:
deluge.error._ClientSideRecreateError
- exception deluge.error.WrappedException(*args, **kwargs)
Bases:
deluge.error.DelugeError
deluge.event module
Event module.
This module describes the types of events that can be generated by the daemon and subsequently emitted to the clients.
- class deluge.event.ClientDisconnectedEvent(session_id)
Bases:
deluge.event.DelugeEvent
Emitted when a client disconnects.
- class deluge.event.ConfigValueChangedEvent(key, value)
Bases:
deluge.event.DelugeEvent
Emitted when a config value changes in the Core.
- __init__(key, value)
- Parameters
key (string) – the key that changed
value – the new value of the :param:key
- class deluge.event.CreateTorrentProgressEvent(piece_count, num_pieces)
Bases:
deluge.event.DelugeEvent
Emitted when creating a torrent file remotely.
- class deluge.event.DelugeEvent
Bases:
object
The base class for all events.
- Prop name
this is the name of the class which is in-turn the event name
- Prop args
a list of the attribute values
- property args
- property name
- class deluge.event.DelugeEventMetaClass(name, bases, dct)
Bases:
type
This metaclass simply keeps a list of all events classes created.
- class deluge.event.ExternalIPEvent(external_ip)
Bases:
deluge.event.DelugeEvent
Emitted when the external ip address is received from libtorrent.
- __init__(external_ip)
- Parameters
external_ip (str) – The IP address.
- class deluge.event.NewVersionAvailableEvent(new_release)
Bases:
deluge.event.DelugeEvent
Emitted when a more recent version of Deluge is available.
- __init__(new_release)
- Parameters
new_release (string) – the new version that is available
- class deluge.event.PluginDisabledEvent(plugin_name)
Bases:
deluge.event.DelugeEvent
Emitted when a plugin is disabled in the Core.
- class deluge.event.PluginEnabledEvent(plugin_name)
Bases:
deluge.event.DelugeEvent
Emitted when a plugin is enabled in the Core.
- class deluge.event.PreTorrentRemovedEvent(torrent_id)
Bases:
deluge.event.DelugeEvent
Emitted when a torrent is about to be removed from the session.
- __init__(torrent_id)
- Parameters
torrent_id (string) – the torrent_id
- class deluge.event.SessionPausedEvent
Bases:
deluge.event.DelugeEvent
Emitted when the session has been paused.
- class deluge.event.SessionResumedEvent
Bases:
deluge.event.DelugeEvent
Emitted when the session has been resumed.
- class deluge.event.SessionStartedEvent
Bases:
deluge.event.DelugeEvent
Emitted when a session has started. This typically only happens once when the daemon is initially started.
- class deluge.event.TorrentAddedEvent(torrent_id, from_state)
Bases:
deluge.event.DelugeEvent
Emitted when a new torrent is successfully added to the session.
- __init__(torrent_id, from_state)
- Parameters
torrent_id (string) – the torrent_id of the torrent that was added
from_state (bool) – was the torrent loaded from state? Or is it a new torrent.
- class deluge.event.TorrentFileCompletedEvent(torrent_id, index)
Bases:
deluge.event.DelugeEvent
Emitted when a file completes.
- __init__(torrent_id, index)
- Parameters
torrent_id (string) – the torrent_id
index (int) – the file index
- class deluge.event.TorrentFileRenamedEvent(torrent_id, index, name)
Bases:
deluge.event.DelugeEvent
Emitted when a file within a torrent has been renamed.
- __init__(torrent_id, index, name)
- Parameters
torrent_id (string) – the torrent_id
index (int) – the index of the file
name (string) – the new filename
- class deluge.event.TorrentFinishedEvent(torrent_id)
Bases:
deluge.event.DelugeEvent
Emitted when a torrent finishes downloading.
- __init__(torrent_id)
- Parameters
torrent_id (string) – the torrent_id
- class deluge.event.TorrentFolderRenamedEvent(torrent_id, old, new)
Bases:
deluge.event.DelugeEvent
Emitted when a folder within a torrent has been renamed.
- __init__(torrent_id, old, new)
- Parameters
torrent_id (string) – the torrent_id
old (string) – the old folder name
new (string) – the new folder name
- class deluge.event.TorrentQueueChangedEvent
Bases:
deluge.event.DelugeEvent
Emitted when the queue order has changed.
- class deluge.event.TorrentRemovedEvent(torrent_id)
Bases:
deluge.event.DelugeEvent
Emitted when a torrent has been removed from the session.
- __init__(torrent_id)
- Parameters
torrent_id (string) – the torrent_id
- class deluge.event.TorrentResumedEvent(torrent_id)
Bases:
deluge.event.DelugeEvent
Emitted when a torrent resumes from a paused state.
- __init__(torrent_id)
- Parameters
torrent_id (string) – the torrent_id
- class deluge.event.TorrentStateChangedEvent(torrent_id, state)
Bases:
deluge.event.DelugeEvent
Emitted when a torrent changes state.
- __init__(torrent_id, state)
- Parameters
torrent_id (string) – the torrent_id
state (string) – the new state
- class deluge.event.TorrentStorageMovedEvent(torrent_id, path)
Bases:
deluge.event.DelugeEvent
Emitted when the storage location for a torrent has been moved.
- __init__(torrent_id, path)
- Parameters
torrent_id (string) – the torrent_id
path (string) – the new location
- class deluge.event.TorrentTrackerStatusEvent(torrent_id, status)
Bases:
deluge.event.DelugeEvent
Emitted when a torrents tracker status changes.
- __init__(torrent_id, status)
- Parameters
torrent_id (str) – the torrent_id
status (str) – the new status
deluge.httpdownloader module
- class deluge.httpdownloader.BodyHandler(*args: Any, **kwargs: Any)
Bases:
twisted.web._newclient.HTTPClientParser
An HTTP parser that saves the response to a file.
- __init__(request, finished, length, agent, encoding=None)
BodyHandler init.
- Parameters
request (t.w.i.IClientRequest) – The parser request.
finished (Deferred) – A Deferred to handle the finished response.
length (int) – The length of the response.
agent (t.w.i.IAgent) – The agent from which the request was sent.
- connectionLost(reason)
- dataReceived(data)
- class deluge.httpdownloader.CompressionDecoder(*args, **kwargs)
Bases:
twisted.web.client.GzipDecoder
A compression decoder for gzip, x-gzip and deflate.
- deliverBody(protocol)
- class deluge.httpdownloader.CompressionDecoderProtocol(*args: Any, **kwargs: Any)
Bases:
twisted.web.client._GzipProtocol
A compression decoder protocol for CompressionDecoder.
- class deluge.httpdownloader.HTTPDownloaderAgent(agent, filename, part_callback=None, force_filename=False, allow_compression=True, handle_redirect=True)
Bases:
object
A File Downloader Agent.
- __init__(agent, filename, part_callback=None, force_filename=False, allow_compression=True, handle_redirect=True)
HTTPDownloaderAgent init.
- Parameters
agent (t.w.c.Agent) – The agent which will send the requests.
filename (str) – The filename to save the file as.
force_filename (bool) – Forces use of the supplied filename, regardless of header content.
part_callback (func) –
A function to be called when a part of data is received, it’s signature should be:
func(data, current_length, total_length)
- request(method, uri, headers=None, body_producer=None)
Issue a new request to the wrapped agent.
- Parameters
method (bytes) – The HTTP method to use.
uri (bytes) – The url to download from.
headers (t.w.h.Headers, optional) – Any extra headers to send.
body_producer (t.w.i.IBodyProducer, optional) – Request body data.
- Returns
Deferred – The filename of the of the downloaded file.
- request_callback(response)
- deluge.httpdownloader.download_file(url, filename, callback=None, headers=None, force_filename=False, allow_compression=True, handle_redirects=True)
Downloads a file from a specific URL and returns a Deferred.
A callback function can be specified to be called as parts are received.
- Parameters
url (str) – The url to download from.
filename (str) – The filename to save the file as.
callback (func) – A function to be called when partial data is received, it’s signature should be: func(data, current_length, total_length).
headers (dict) – Any optional headers to send.
force_filename (bool) – Force the filename specified rather than one the server may suggest.
allow_compression (bool) – Allows gzip & deflate decoding.
handle_redirects (bool) – HTTP redirects handled automatically or not.
- Returns
Deferred – The filename of the downloaded file.
- Raises
t.w.e.PageRedirect – If handle_redirects is False.
t.w.e.Error – For all other HTTP response errors.
- deluge.httpdownloader.sanitise_filename(filename)
Sanitises a filename to use as a download destination file.
Logs any filenames that could be considered malicious.
filename (str): The filename to sanitise.
- Returns
str – The sanitised filename.
deluge.log module
Logging functions
- deluge.log.get_plugin_logger(logger_name)
- deluge.log.set_logger_level(level, logger_name=None)
Sets the logger level.
- Parameters
level – str, a string representing the desired level
logger_name – str, a string representing desired logger name for which the level should change. The default is “None” will tweak the root logger level.
- deluge.log.setup_logger(level='error', filename=None, filemode='w', logrotate=None, output_stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, twisted_observer=True)
Sets up the basic logger and if :param:filename is set, then it will log to that file instead of stdout.
- Parameters
level (str) – The log level to use (Default: ‘error’)
filename (str, optional) – The log filename. Default is None meaning log to terminal
filemode (str) – The filemode to use when opening the log file
logrotate (int, optional) – The size of the logfile in bytes when enabling log rotation (Default is None meaning disabled)
output_stream (file descriptor) – File descriptor to log to if not logging to file
twisted_observer (bool) – Whether to setup the custom twisted logging observer.
deluge.maketorrent module
- exception deluge.maketorrent.InvalidPath
Bases:
Exception
Raised when an invalid path is supplied.
- exception deluge.maketorrent.InvalidPieceSize
Bases:
Exception
Raised when an invalid piece size is set.
Note
Piece sizes must be multiples of 16KiB.
- class deluge.maketorrent.TorrentMetadata
Bases:
object
This class is used to create .torrent files.
Examples
>>> t = TorrentMetadata() >>> t.data_path = '/tmp/torrent' >>> t.comment = 'My Test Torrent' >>> t.trackers = [['http://tracker.openbittorent.com']] >>> t.save('/tmp/test.torrent')
- property comment
Get the torrent comment.
- Returns
str – An informational string about the torrent.
- property data_path
Get the path to the files that the torrent will contain.
Note
It can be either a file or a folder.
- Returns
str – The torrent data path, either a file or a folder.
- get_comment()
Get the torrent comment.
- Returns
str – An informational string about the torrent.
- get_data_path()
Get the path to the files that the torrent will contain.
Note
It can be either a file or a folder.
- Returns
str – The torrent data path, either a file or a folder.
- get_pad_files()
Get status of padding files for the torrent.
- Returns
bool – True if padding files have been enabled to align files on piece boundaries.
- get_piece_size()
The size of the pieces.
- Returns
int – The piece size in multiples of 16 KiBs.
- get_private()
Get the private flag of the torrent.
- Returns
bool – True if private flag has been set, else False.
- get_trackers()
Get the announce trackers.
- Returns
list of lists – A list containing a list of trackers.
- get_webseeds()
Get the webseeds.
Note
- The web seeds can either be:
Hoffman-style: http://bittorrent.org/beps/bep_0017.html GetRight-style: http://bittorrent.org/beps/bep_0019.html
If the url ends in ‘.php’ then it will be considered Hoffman-style, if not it will be considered GetRight-style.
- Returns
list – The webseeds.
- property pad_files
Get status of padding files for the torrent.
- Returns
bool – True if padding files have been enabled to align files on piece boundaries.
- property piece_size
The size of the pieces.
- Returns
int – The piece size in multiples of 16 KiBs.
- property private
Get the private flag of the torrent.
- Returns
bool – True if private flag has been set, else False.
- save(torrent_path, progress=None)
Creates and saves the torrent file to path.
- Parameters
torrent_path (str) – Location to save the torrent file.
progress (func, optional) – The function to be called when a piece is hashed. The provided function should be in the format func(num_completed, num_pieces).
- Raises
InvalidPath – If the data_path has not been set.
- set_comment(comment)
Set the comment for the torrent.
- Parameters
comment (str) – An informational string about the torrent.
- set_data_path(path)
Set the path to the files (data) that the torrent will contain.
Note
This property needs to be set before the torrent file can be created and saved.
- Parameters
path (str) – The path to the torrent data and can be either a file or a folder.
- Raises
InvalidPath – If the path is not found.
- set_pad_files(pad)
Enable padding files for the torrent.
- Parameters
private (bool) – True adds padding files to align files on piece boundaries.
- set_piece_size(size)
Set piece size.
Note
If no piece size is set, one will be automatically selected to produce a torrent with less than 1024 pieces or the smallest possible with a 8192KiB piece size.
- Parameters
size (int) – The desired piece size in multiples of 16 KiBs.
- Raises
InvalidPieceSize – If the piece size is not a valid multiple of 16 KiB.
- set_private(private)
Set the torrent private flag.
Note
Private torrents only announce to trackers and will not use DHT or Peer Exchange. See http://bittorrent.org/beps/bep_0027.html
- Parameters
private (bool) – True if the torrent is to be private.
- set_trackers(trackers)
Set the announce trackers.
- Parameters
private (list of lists) – A list containing lists of trackers as strings, each list is a tier.
- set_webseeds(webseeds)
Set webseeds.
Note
- The web seeds can either be:
Hoffman-style: http://bittorrent.org/beps/bep_0017.html GetRight-style: http://bittorrent.org/beps/bep_0019.html
If the url ends in ‘.php’ then it will be considered Hoffman-style, if not it will be considered GetRight-style.
- Parameters
private (list) – The webseeds URLs which can be either Hoffman or GetRight style.
- property trackers
Get the announce trackers.
- Returns
list of lists – A list containing a list of trackers.
- property webseeds
Get the webseeds.
Note
- The web seeds can either be:
Hoffman-style: http://bittorrent.org/beps/bep_0017.html GetRight-style: http://bittorrent.org/beps/bep_0019.html
If the url ends in ‘.php’ then it will be considered Hoffman-style, if not it will be considered GetRight-style.
- Returns
list – The webseeds.
deluge.metafile module
- class deluge.metafile.RemoteFileProgress(session_id)
Bases:
object
- class deluge.metafile.TorrentFormat(value)
Bases:
str
,enum.Enum
An enumeration.
- HYBRID = 'hybrid'
- V1 = 'v1'
- V2 = 'v2'
- includes_v1()
- includes_v2()
- to_lt_flag()
- deluge.metafile.calcsize(path)
- deluge.metafile.default_meta_file_path(content_path)
- deluge.metafile.dummy(*v)
- deluge.metafile.gmtime()
- deluge.metafile.make_meta_file(path, url, piece_length, progress=None, title=None, comment=None, safe=None, content_type=None, target=None, webseeds=None, name=None, private=False, created_by=None, trackers=None)
- deluge.metafile.make_meta_file_content(path, url, piece_length, progress=None, title=None, comment=None, safe=None, content_type=None, webseeds=None, name=None, private=False, created_by=None, trackers=None, torrent_format=TorrentFormat.V1)
- deluge.metafile.makeinfo(path, piece_length, progress, name=None, content_type=None, private=False, torrent_format=TorrentFormat.V1)
- deluge.metafile.makeinfo_lt(path, piece_length, name=None, private=False, torrent_format=TorrentFormat.V1)
Make info using via the libtorrent library.
- deluge.metafile.subfiles(d)
deluge.path_chooser_common module
- deluge.path_chooser_common.get_completion_paths(args)
Takes a path value and returns the available completions. If the path_value is a valid path, return all sub-directories. If the path_value is not a valid path, remove the basename from the path and return all sub-directories of path that start with basename.
- Parameters
args (dict) – options
- Returns
the args argument containing the available completions for the completion_text
- Return type
dict
deluge.pluginmanagerbase module
PluginManagerBase
- class deluge.pluginmanagerbase.PluginManagerBase(config_file, entry_name)
Bases:
object
PluginManagerBase is a base class for PluginManagers to inherit
- disable_plugin(name)
Disable a plugin.
- Parameters
plugin_name (str) – The plugin name.
- Returns
Deferred –
- A deferred with callback value True or False indicating
whether the plugin is disabled or not.
- disable_plugins()
Disable all plugins that are enabled
- enable_plugin(plugin_name)
Enable a plugin.
- Parameters
plugin_name (str) – The plugin name.
- Returns
Deferred –
- A deferred with callback value True or False indicating
whether the plugin is enabled or not.
- enable_plugins()
- get_available_plugins()
Returns a list of the available plugins name
- get_enabled_plugins()
Returns a list of enabled plugins
- get_plugin_info(name)
Returns a dictionary of plugin info from the metadata
- static parse_pkg_info(pkg_info)
- scan_for_plugins()
Scans for available plugins
deluge.transfer module
- class deluge.transfer.DelugeTransferProtocol
Bases:
twisted.internet.protocol.Protocol
Deluge RPC wire protocol.
Data messages are transferred with a header containing a protocol version and the length of the data to be transferred (payload).
The format is:
ubyte uint4 bytestring |.version.|..size..|.....body.....|
The version is an unsigned byte that indicates the protocol version. The size is a unsigned 32-bit integer that is equal to the length of the body bytestring. The body is the compressed rencoded byte string of the data object.
- dataReceived(data)
This method is called whenever data is received.
- Parameters
data – a message as transferred by transfer_message, or a part of such a message.
- Global variables:
_buffer - contains the data received _message_length - the length of the payload of the current message.
- get_bytes_recv()
Returns the number of bytes received.
- Returns
the number of bytes received
- Return type
int
- get_bytes_sent()
Returns the number of bytes sent.
- Returns
the number of bytes sent
- Return type
int
- message_received(message)
Override this method to receive the complete message
- transfer_message(data)
Transfer the data.
- Parameters
data – data to be transferred in a data structure serializable by rencode.
Module contents
Deluge