deluge.core package

Submodules

deluge.core.alertmanager module

The AlertManager handles all the libtorrent alerts.

This should typically only be used by the Core. Plugins should utilize the :mod:EventManager for similar functionality.

class deluge.core.alertmanager.AlertManager

Bases: deluge.component.Component

AlertManager fetches and processes libtorrent alerts

deregister_handler(handler)

De-registers the :param:handler function from all alert types.

Parameters

handler – func, the handler function to deregister

handle_alerts()

Pops all libtorrent alerts in the session queue and handles them appropriately.

register_handler(alert_type, handler)

Registers a function that will be called when ‘alert_type’ is pop’d in handle_alerts. The handler function should look like: handler(alert) Where ‘alert’ is the actual alert object from libtorrent.

Parameters
  • alert_type – str, this is string representation of the alert name

  • handler – func(alert), the function to be called when the alert is raised

set_alert_queue_size(queue_size)

Sets the maximum size of the libtorrent alert queue

stop()
update()

deluge.core.authmanager module

class deluge.core.authmanager.Account(username, password, authlevel)

Bases: object

authlevel
data()
password
username
class deluge.core.authmanager.AuthManager

Bases: deluge.component.Component

authorize(username, password)

Authorizes users based on username and password.

Parameters
  • username (str) – Username

  • password (str) – Password

Returns

int – The auth level for this user.

Raises
create_account(username, password, authlevel)
get_known_accounts()

Returns a list of known deluge usernames.

has_account(username)
remove_account(username)
shutdown()
start()
stop()
update()
update_account(username, password, authlevel)
write_auth_file()

deluge.core.core module

class deluge.core.core.Core(listen_interface=None, outgoing_interface=None, read_only_config_keys=None)

Bases: deluge.component.Component

add_torrent_file(filename, filedump, options)

Adds a torrent file to the session.

Parameters
  • filename (str) – The filename of the torrent.

  • filedump (str) – A base64 encoded string of the torrent file contents.

  • options (dict) – The options to apply to the torrent upon adding.

Returns

str – The torrent_id or None.

RPC exported method (Auth level: 5)

add_torrent_file_async(filename, filedump, options, save_state=True)

Adds a torrent file to the session asynchonously.

Parameters
  • filename (str) – The filename of the torrent.

  • filedump (str) – A base64 encoded string of torrent file contents.

  • options (dict) – The options to apply to the torrent upon adding.

  • save_state (bool) – If the state should be saved after adding the file.

Returns

Deferred – The torrent ID or None.

RPC exported method (Auth level: 5)

add_torrent_files(torrent_files)

Adds multiple torrent files to the session asynchonously.

Parameters

torrent_files (list of tuples) – Torrent files as tuple of (filename, filedump, options).

Returns

Deferred

RPC exported method (Auth level: 5)

add_torrent_magnet(uri, options)

Adds a torrent from a magnet link.

Parameters
  • uri (string) – the magnet link

  • options (dict) – the options to apply to the torrent on add

Returns

the torrent_id

Return type

string

RPC exported method (Auth level: 5)

add_torrent_url(url, options, headers=None)

Adds a torrent from a url. Deluge will attempt to fetch the torrent from url prior to adding it to the session.

Parameters
  • url (string) – the url pointing to the torrent file

  • options (dict) – the options to apply to the torrent on add

  • headers (dict) – any optional headers to send

Returns

a Deferred which returns the torrent_id as a str or None

RPC exported method (Auth level: 5)

apply_session_setting(key, value)
apply_session_settings(settings)

Apply libtorrent session settings.

Parameters

settings (dict) – A dict of lt session settings to apply.

check_new_release()
connect_peer(torrent_id, ip, port)

RPC exported method (Auth level: 5)

create_account(username, password, authlevel)

RPC exported method (Auth level: 10)

create_torrent(path, tracker, piece_length, comment, target, webseeds, private, created_by, trackers, add_to_session)

RPC exported method (Auth level: 5)

create_torrent_status(torrent_id, torrent_keys, plugin_keys, diff=False, update=False, all_keys=False)
disable_plugin(plugin)

RPC exported method (Auth level: 5)

enable_plugin(plugin)

RPC exported method (Auth level: 5)

force_reannounce(torrent_ids)

RPC exported method (Auth level: 5)

force_recheck(torrent_ids)

Forces a data recheck on torrent_ids

RPC exported method (Auth level: 5)

get_auth_levels_mappings()

RPC exported method (Auth level: 0)

get_available_plugins()

Returns a list of plugins available in the core

RPC exported method (Auth level: 5)

get_completion_paths(args)

Returns the available path completions for the input value.

RPC exported method (Auth level: 5)

get_config()

Get all the preferences as a dictionary

RPC exported method (Auth level: 5)

get_config_value(key)

Get the config value for key

RPC exported method (Auth level: 5)

get_config_values(keys)

Get the config values for the entered keys

RPC exported method (Auth level: 5)

get_enabled_plugins()

Returns a list of enabled plugins in the core

RPC exported method (Auth level: 5)

get_external_ip()

Returns the external ip address recieved from libtorrent.

RPC exported method (Auth level: 5)

get_filter_tree(show_zero_hits=True, hide_cat=None)

returns {field: [(value,count)] } for use in sidebar(s)

RPC exported method (Auth level: 5)

get_free_space(path=None)

Returns the number of free bytes at path

Parameters

path (string) – the path to check free space at, if None, use the default download location

Returns

the number of free bytes at path

Return type

int

Raises

InvalidPathError – if the path is invalid

RPC exported method (Auth level: 5)

get_known_accounts()

RPC exported method (Auth level: 10)

get_libtorrent_version()

Returns the libtorrent version.

Returns

the version

Return type

string

RPC exported method (Auth level: 5)

get_listen_port()

Returns the active listen port

RPC exported method (Auth level: 5)

get_new_release()
get_path_size(path)
Returns the size of the file or folder ‘path’ and -1 if the path is

unaccessible (non-existent or insufficient privs)

RPC exported method (Auth level: 5)

get_proxy()

Returns the proxy settings

Returns

dict – Contains proxy settings.

Notes

Proxy type names:

0: None, 1: Socks4, 2: Socks5, 3: Socks5 w Auth, 4: HTTP, 5: HTTP w Auth, 6: I2P

RPC exported method (Auth level: 5)

get_session_state()

Returns a list of torrent_ids in the session.

RPC exported method (Auth level: 5)

get_session_status(keys)

Gets the session status values for ‘keys’, these keys are taking from libtorrent’s session status.

See: http://www.rasterbar.com/products/libtorrent/manual.html#status

Parameters

keys (list) – the keys for which we want values

Returns

a dictionary of {key: value, …}

Return type

dict

RPC exported method (Auth level: 5)

get_torrent_status(torrent_id, keys, diff=False)

RPC exported method (Auth level: 5)

get_torrents_status(filter_dict, keys, diff=False)

returns all torrents , optionally filtered by filter_dict.

RPC exported method (Auth level: 5)

glob(path)

RPC exported method (Auth level: 5)

is_session_paused()

Returns the activity of the session

RPC exported method (Auth level: 5)

move_storage(torrent_ids, dest)

RPC exported method (Auth level: 5)

pause_session()

Pause the entire session

RPC exported method (Auth level: 5)

pause_torrent(torrent_id)

Pauses a torrent

RPC exported method (Auth level: 5)

pause_torrents(torrent_ids=None)

Pauses a list of torrents

RPC exported method (Auth level: 5)

prefetch_magnet_metadata(magnet, timeout=30)

Download magnet metadata without adding to Deluge session.

Used by UIs to get magnet files for selection before adding to session.

Parameters
  • magnet (str) – The magnet uri.

  • timeout (int) – Number of seconds to wait before cancelling request.

Returns

Deferred – A tuple of (torrent_id (str), metadata (dict)) for the magnet.

RPC exported method (Auth level: 5)

queue_bottom(torrent_ids)

RPC exported method (Auth level: 5)

queue_down(torrent_ids)

RPC exported method (Auth level: 5)

queue_top(torrent_ids)

RPC exported method (Auth level: 5)

queue_up(torrent_ids)

RPC exported method (Auth level: 5)

remove_account(username)

RPC exported method (Auth level: 10)

remove_torrent(torrent_id, remove_data)

Removes a single torrent from the session.

Parameters
  • torrent_id (str) – The torrent ID to remove.

  • remove_data (bool) – If True, also remove the downloaded data.

Returns

bool – True if removed successfully.

Raises

InvalidTorrentError – If the torrent ID does not exist in the session.

RPC exported method (Auth level: 5)

remove_torrents(torrent_ids, remove_data)

Remove multiple torrents from the session.

Parameters
  • torrent_ids (list) – The torrent IDs to remove.

  • remove_data (bool) – If True, also remove the downloaded data.

Returns

list

An empty list if no errors occurred otherwise the list contains

tuples of strings, a torrent ID and an error message. For example:

[(‘<torrent_id>’, ‘Error removing torrent’)]

RPC exported method (Auth level: 5)

rename_files(torrent_id, filenames)

Rename files in torrent_id. Since this is an asynchronous operation by libtorrent, watch for the TorrentFileRenamedEvent to know when the files have been renamed.

Parameters
  • torrent_id (string) – the torrent_id to rename files

  • filenames (((index, filename), ..)) – a list of index, filename pairs

Raises

InvalidTorrentError – if torrent_id is invalid

RPC exported method (Auth level: 5)

rename_folder(torrent_id, folder, new_folder)

Renames the ‘folder’ to ‘new_folder’ in ‘torrent_id’. Watch for the TorrentFolderRenamedEvent which is emitted when the folder has been renamed successfully.

Parameters
  • torrent_id (string) – the torrent to rename folder in

  • folder (string) – the folder to rename

  • new_folder (string) – the new folder name

Raises

InvalidTorrentError – if the torrent_id is invalid

RPC exported method (Auth level: 5)

rescan_plugins()

Rescans the plugin folders for new plugins

RPC exported method (Auth level: 5)

resume_session()

Resume the entire session

RPC exported method (Auth level: 5)

resume_torrent(torrent_id)

Resumes a torrent

RPC exported method (Auth level: 5)

resume_torrents(torrent_ids=None)

Resumes a list of torrents

RPC exported method (Auth level: 5)

set_config(config)

Set the config with values from dictionary

RPC exported method (Auth level: 5)

set_torrent_auto_managed(torrent_id, value)

Deprecated: Use set_torrent_options with ‘auto_managed’

RPC exported method (Auth level: 5)

set_torrent_file_priorities(torrent_id, priorities)

Deprecated: Use set_torrent_options with ‘file_priorities’

RPC exported method (Auth level: 5)

set_torrent_max_connections(torrent_id, value)

Deprecated: Use set_torrent_options with ‘max_connections’

RPC exported method (Auth level: 5)

set_torrent_max_download_speed(torrent_id, value)

Deprecated: Use set_torrent_options with ‘max_download_speed’

RPC exported method (Auth level: 5)

set_torrent_max_upload_slots(torrent_id, value)

Deprecated: Use set_torrent_options with ‘max_upload_slots’

RPC exported method (Auth level: 5)

set_torrent_max_upload_speed(torrent_id, value)

Deprecated: Use set_torrent_options with ‘max_upload_speed’

RPC exported method (Auth level: 5)

set_torrent_move_completed(torrent_id, value)

Deprecated: Use set_torrent_options with ‘move_completed’

RPC exported method (Auth level: 5)

set_torrent_move_completed_path(torrent_id, value)

Deprecated: Use set_torrent_options with ‘move_completed_path’

RPC exported method (Auth level: 5)

set_torrent_options(torrent_ids, options)

Sets the torrent options for torrent_ids

Parameters
  • torrent_ids (list) – A list of torrent_ids to set the options for.

  • options (dict) – A dict of torrent options to set. See torrent.TorrentOptions class for valid keys.

RPC exported method (Auth level: 5)

set_torrent_prioritize_first_last(torrent_id, value)

Deprecated: Use set_torrent_options with ‘prioritize_first_last’

RPC exported method (Auth level: 5)

set_torrent_remove_at_ratio(torrent_id, value)

Deprecated: Use set_torrent_options with ‘remove_at_ratio’

RPC exported method (Auth level: 5)

set_torrent_stop_at_ratio(torrent_id, value)

Deprecated: Use set_torrent_options with ‘stop_at_ratio’

RPC exported method (Auth level: 5)

set_torrent_stop_ratio(torrent_id, value)

Deprecated: Use set_torrent_options with ‘stop_ratio’

RPC exported method (Auth level: 5)

set_torrent_trackers(torrent_id, trackers)

Sets a torrents tracker list. trackers will be [{“url”, “tier”}]

RPC exported method (Auth level: 5)

shutdown()
start()

Starts the core

stop()
test_listen_port()

Checks if the active port is open

Returns

True if the port is open, False if not

Return type

bool

RPC exported method (Auth level: 5)

update_account(username, password, authlevel)

RPC exported method (Auth level: 10)

upload_plugin(filename, filedump)
This method is used to upload new plugins to the daemon. It is used

when connecting to the daemon remotely and installing a new plugin on the client side. ‘plugin_data’ is a xmlrpc.Binary object of the file data, ie, plugin_file.read()

RPC exported method (Auth level: 5)

deluge.core.daemon module

The Deluge daemon

class deluge.core.daemon.Daemon(listen_interface=None, outgoing_interface=None, interface=None, port=None, standalone=False, read_only_config_keys=None)

Bases: object

The Deluge Daemon class

__init__(listen_interface=None, outgoing_interface=None, interface=None, port=None, standalone=False, read_only_config_keys=None)
Parameters
  • listen_interface (str, optional) – The IP address to listen to BitTorrent connections on.

  • outgoing_interface (str, optional) – The network interface name or IP address to open outgoing BitTorrent connections on.

  • interface (str, optional) – The IP address the daemon will listen for UI connections on.

  • port (int, optional) – The port the daemon will listen for UI connections on.

  • standalone (bool, optional) – If True the client is in Standalone mode otherwise, if False, start the daemon as separate process.

  • read_only_config_keys (list of str, optional) – A list of config keys that will not be altered by core.set_config() RPC method.

authorized_call(rpc)

Determines if session auth_level is authorized to call RPC.

Parameters

rpc (str) – A RPC, e.g. core.get_torrents_status

Returns

bool – True if authorized to call RPC, otherwise False.

RPC exported method (Auth level: 1)

get_method_list()

Returns a list of the exported methods.

RPC exported method (Auth level: 5)

get_version()

Returns the daemon version

RPC exported method (Auth level: 5)

shutdown(*args, **kwargs)

RPC exported method (Auth level: 5)

start()
deluge.core.daemon.is_daemon_running(pid_file)

Check for another running instance of the daemon using the same pid file.

Parameters

pid_file – The location of the file with pid, port values.

Returns

bool – True is daemon is running, False otherwise.

deluge.core.daemon_entry module

deluge.core.daemon_entry.add_daemon_options(parser)
deluge.core.daemon_entry.start_daemon(skip_start=False)

Entry point for daemon script

Parameters

skip_start (bool) – If starting daemon should be skipped.

Returns

deluge.core.daemon.Daemon – A new daemon object

deluge.core.eventmanager module

class deluge.core.eventmanager.EventManager

Bases: deluge.component.Component

deregister_event_handler(event, handler)

Deregisters an event handler function.

Parameters
  • event – str, the event name

  • handler – function, currently registered to handle :param:event

emit(event)

Emits the event to interested clients.

Parameters

event – DelugeEvent

register_event_handler(event, handler)

Registers a function to be called when a :param:event is emitted.

Parameters
  • event – str, the event name

  • handler – function, to be called when :param:event is emitted

deluge.core.filtermanager module

class deluge.core.filtermanager.FilterManager(core)

Bases: deluge.component.Component

deregister_filter(filter_id)
deregister_tree_field(field)
filter_state_active(torrent_ids)
filter_torrent_ids(filter_dict)

returns a list of torrent_id’s matching filter_dict. core filter method

get_filter_tree(show_zero_hits=True, hide_cat=None)

returns {field: [(value,count)] } for use in sidebar.

register_filter(filter_id, filter_func, filter_value=None)
register_tree_field(field, init_func=<function FilterManager.<lambda>>)
deluge.core.filtermanager.filter_by_name(torrent_ids, search_string)
deluge.core.filtermanager.filter_keywords(torrent_ids, values)
deluge.core.filtermanager.filter_one_keyword(torrent_ids, keyword)

search torrent on keyword. searches title,state,tracker-status,tracker,files

deluge.core.filtermanager.tracker_error_filter(torrent_ids, values)

deluge.core.pluginmanager module

PluginManager for Core

class deluge.core.pluginmanager.PluginManager(core)

Bases: deluge.pluginmanagerbase.PluginManagerBase, deluge.component.Component

PluginManager handles the loading of plugins and provides plugins with functions to access parts of the core.

deregister_status_field(field)

Deregisters a status field

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.

enable_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.

get_status(torrent_id, fields)

Return the value of status fields for the selected torrent_id.

register_status_field(field, function)

Register a new status field. This can be used in the same way the client requests other status information from core.

shutdown()
start()
stop()
update_plugins()

deluge.core.preferencesmanager module

class deluge.core.preferencesmanager.PreferencesManager

Bases: deluge.component.Component

do_config_set_func(key, value)
start()
stop()

deluge.core.rpcserver module

RPCServer Module

class deluge.core.rpcserver.DelugeRPCProtocol

Bases: deluge.transfer.DelugeTransferProtocol

connectionLost(reason=twisted.internet.protocol.connectionDone)

This method is called when the client is disconnected.

Parameters

reason (str) – the reason the client disconnected.

connectionMade()

This method is called when a new client connects.

dispatch(request_id, method, args, kwargs)

This method is run when a RPC Request is made. It will run the local method and will send either a RPC Response or RPC Error back to the client.

Parameters
  • request_id (int) – the request_id from the client (sent in the RPC Request)

  • method (str) – the local method to call. It must be registered with the RPCServer.

  • args (list) – the arguments to pass to method

  • kwargs (dict) – the keyword-arguments to pass to method

message_received(request)

This method is called whenever a message is received from a client. The only message that a client sends to the server is a RPC Request message. If the RPC Request message is valid, then the method is called in dispatch().

Parameters

request – the request from the client.

sendData(data)

Sends the data to the client.

Parameters

data (object) – the object that is to be sent to the client. This should be one of the RPC message types.

valid_session()
class deluge.core.rpcserver.RPCServer(port=58846, interface='', allow_remote=False, listen=True)

Bases: deluge.component.Component

This class is used to handle rpc requests from the client. Objects are registered with this class and their methods are exported using the export decorator.

Parameters
  • port (int) – the port the RPCServer will listen on

  • interface (str) – the interface to listen on, this may override the allow_remote setting

  • allow_remote (bool) – set True if the server should allow remote connections

  • listen (bool) – if False, will not start listening.. This is only useful in Classic Mode

deregister_object(obj)

Deregisters an objects exported rpc methods.

Parameters

obj – the object that was previously registered

emit_event(event)

Emits the event to interested clients.

Parameters

event (deluge.event.DelugeEvent) – the event to emit

emit_event_for_session_id(session_id, event)

Emits the event to specified session_id.

Parameters
get_method_list()

Returns a list of the exported methods.

Returns

the exported methods

Return type

list

get_object_method(name)

Returns a registered method.

Parameters

name (str) – the name of the method, usually in the form of ‘object.method’

Returns

method

Raises

KeyError – if name is not registered

get_rpc_auth_level(rpc)

Returns the auth level requirement for an exported rpc.

Returns

the auth level

Return type

int

get_session_auth_level()

Returns the auth level of the user calling the current RPC.

Returns

the auth level

Return type

int

get_session_id()

Returns the session id of the current RPC.

Returns

the session id, this will be -1 if no connections have been made

Return type

int

get_session_user()

Returns the username calling the current RPC.

Returns

the username of the user calling the current RPC

Return type

string

is_session_valid(session_id)

Checks if the session is still valid, eg, if the client is still connected.

Parameters

session_id (int) – the session id

Returns

True if the session is valid

Return type

bool

register_object(obj, name=None)

Registers an object to export it’s rpc methods. These methods should be exported with the export decorator prior to registering the object.

Parameters
  • obj (object) – the object that we want to export

  • name (str) – the name to use, if None, it will be the class name of the object

stop()
deluge.core.rpcserver.check_ssl_keys()

Check for SSL cert/key and create them if necessary

deluge.core.rpcserver.export(auth_level=5)

Decorator function to register an object’s method as an RPC. The object will need to be registered with an RPCServer to be effective.

Parameters
  • func (function) – the function to export

  • auth_level (int) – the auth level required to call this method

deluge.core.rpcserver.format_request(call)

Format the RPCRequest message for debug printing

Parameters

call (a RPCRequest) – the request

Returns

a formatted string for printing

Return type

str

deluge.core.rpcserver.generate_ssl_keys()

This method generates a new SSL key/cert.

deluge.core.torrent module

Internal Torrent class

deluge.core.torrent.LT_TORRENT_STATE_MAP

Maps the torrent state from libtorrent to Deluge state.

Type

dict

class deluge.core.torrent.Torrent(handle, options, state=None, filename=None, magnet=None)

Bases: object

Torrent holds information about torrents added to the libtorrent session.

Parameters
  • handle – The libtorrent torrent handle.

  • options (dict) – The torrent options.

  • state (TorrentState) – The torrent state.

  • filename (str) – The filename of the torrent file.

  • magnet (str) – The magnet uri.

torrent_id

The torrent_id for this torrent

Type

str

handle

Holds the libtorrent torrent handle

magnet

The magnet uri used to add this torrent (if available).

Type

str

status

Holds status info so that we don”t need to keep getting it from libtorrent.

torrent_info

store the torrent info.

has_metadata

True if the metadata for the torrent is available, False otherwise.

Type

bool

status_funcs

The function mappings to get torrent status

Type

dict

prev_status

Previous status dicts returned for this torrent. We use this to return dicts that only contain changes from the previous. {session_id: status_dict, …}

Type

dict

waiting_on_folder_rename

A list of Deferreds for file indexes we’re waiting for file_rename alerts on. This is so we can send one folder_renamed signal instead of multiple file_renamed signals. [{index: Deferred, …}, …]

Type

list of dict

options

The torrent options.

Type

dict

filename

The filename of the torrent file in case it is required.

Type

str

is_finished

Keep track if torrent is finished to prevent some weird things on state load.

Type

bool

statusmsg

Status message holds error/extra info about the torrent.

Type

str

state

The torrent’s state

Type

str

trackers

The torrent’s trackers

Type

list of dict

tracker_status

Status message of currently connected tracker

Type

str

tracker_host

Hostname of the currently connected tracker

Type

str

forcing_recheck

Keep track if we’re forcing a recheck of the torrent

Type

bool

forcing_recheck_paused

Keep track if we’re forcing a recheck of the torrent so that we can re-pause it after its done if necessary

Type

bool

forced_error

Keep track if we have forced this torrent to be in Error state.

Type

TorrentError

cleanup_prev_status()

Checks the validity of the keys in the prev_status dict.

If the key is no longer valid, the dict will be deleted.

clear_forced_error_state(update_state=True)
connect_peer(peer_ip, peer_port)

Manually add a peer to the torrent

Parameters
  • peer_ip (str) – Peer IP Address

  • peer_port (int) – Peer Port

Returns

bool – True is successful, otherwise False

delete_torrentfile(delete_copies=False)

Deletes the .torrent file in the state directory in config

force_error_state(message, restart_to_resume=True)

Forces the torrent into an error state.

For setting an error state not covered by libtorrent.

Parameters
  • message (str) – The error status message.

  • restart_to_resume (bool, optional) – Prevent resuming clearing the error, only restarting session can resume.

force_reannounce()

Force a tracker reannounce

force_recheck()

Forces a recheck of the torrent’s pieces

get_eta()

Get the ETA for this torrent.

Returns

int – The ETA in seconds.

get_file_priorities()

Return the file priorities

get_file_progress()

Calculates the file progress as a percentage.

Returns

list of floats – The file progress (0.0 -> 1.0), empty list if n/a.

get_files()

Get the files this torrent contains.

Returns

list of dict – The files.

get_magnet_uri()

Returns a magnet uri for this torrent

get_name()

The name of the torrent (distinct from the filenames).

Note

Can be manually set in options through name key. If the key is reset to empty string “” it will return the original torrent name.

Returns

str – the name of the torrent.

get_options()

Get the torrent options.

Returns

dict – the torrent options.

get_orig_files()

Get the original filenames of files in this torrent.

Returns

list of dict – The files with original filenames.

get_peers()

Get the peers for this torrent.

A list of peers and various information about them.

Returns

list of dict – The peers.

The format for the peer dict:

{
    "client": str,
    "country": str,
    "down_speed": int,
    "ip": str,
    "progress": float,
    "seed": bool,
    "up_speed": int
}

get_progress()

The progress of this torrent’s current task.

Returns

float – The progress percentage (0 to 100).

get_queue_position()

Get the torrents queue position

Returns

int – queue position

get_ratio()

Get the ratio of upload/download for this torrent.

Returns

float – The ratio or -1.0 (for infinity).

get_status(keys, diff=False, update=False, all_keys=False)

Returns the status of the torrent based on the keys provided

Parameters
  • keys (list of str) – the keys to get the status on

  • diff (bool) – Will return a diff of the changes since the last call to get_status based on the session_id

  • update (bool) – If True the status will be updated from libtorrent if False, the cached values will be returned

Returns

dict – a dictionary of the status keys and their values

get_time_since_transfer()

The time since either upload/download from peers

get_tracker_host()

Get the hostname of the currently connected tracker.

If no tracker is connected, it uses the 1st tracker.

Returns

str – The tracker host

merge_trackers(torrent_info)

Merges new trackers in torrent_info into torrent

move_storage(dest)

Move a torrent’s storage location

Parameters

dest (str) – The destination folder for the torrent data

Returns

bool – True if successful, otherwise False

on_metadata_received()

Process the metadata received alert for this torrent

pause()

Pause this torrent.

Returns

bool – True is successful, otherwise False.

remove_empty_folders(folder)

Recursively removes folders but only if they are empty.

This cleans up after libtorrent folder renames.

Parameters

folder (str) – The folder to recursively check

rename_files(filenames)

Renames files in the torrent.

Parameters

filenames (list) – A list of (index, filename) pairs.

rename_folder(folder, new_folder)

Renames a folder within a torrent.

This basically does a file rename on all of the folders children.

Parameters
  • folder (str) – The orignal folder name

  • new_folder (str) – The new folder name

Returns

twisted.internet.defer.Deferred – A deferred which fires when the rename is complete

resume()

Resumes this torrent.

save_resume_data(flush_disk_cache=False)

Signals libtorrent to build resume data for this torrent.

Parameters

flush_disk_cache (bool) – Avoids potential issue with file timestamps and is only needed when stopping the session.

Returns

None – The response with resume data is returned in a libtorrent save_resume_data_alert.

scrape_tracker()

Scrape the tracker

A scrape request queries the tracker for statistics such as total number of incomplete peers, complete peers, number of downloads etc.

set_auto_managed(auto_managed)

Set auto managed mode, i.e. will be started or queued automatically.

Parameters

auto_managed (bool) – Enable auto managed.

set_download_location(download_location)

The location for downloading torrent data.

set_file_priorities(file_priorities)

Sets the file priotities.

Parameters

file_priorities (list of int) – List of file priorities.

set_max_connections(max_connections)

Sets maximum number of connections this torrent will open.

Parameters

max_connections (int) – Maximum number of connections

Note

The minimum value for handle.max_connections is 2 (or -1 for unlimited connections). This is enforced by libtorrent and values 0 or 1 raise an assert with lt debug builds.

set_max_download_speed(m_down_speed)

Sets maximum download speed for this torrent.

Parameters

m_up_speed (float) – Maximum download speed in KiB/s.

set_max_upload_slots(max_slots)

Sets maximum number of upload slots for this torrent.

Parameters

max_slots (int) – Maximum upload slots

set_max_upload_speed(m_up_speed)

Sets maximum upload speed for this torrent.

Parameters

m_up_speed (float) – Maximum upload speed in KiB/s.

set_move_completed(move_completed)

Set whether to move the torrent when downloading has finished.

Parameters

move_completed (bool) – Move the torrent.

set_move_completed_path(move_completed_path)

Set the path to move torrent to when downloading has finished.

Parameters

move_completed_path (str) – The move path.

set_options(options)

Set the torrent options.

Parameters

options (dict) – Torrent options, see TorrentOptions class for valid keys.

set_owner(account)

Sets the owner of this torrent.

Parameters

account (str) – The new owner account name.

Notes

Only a user with admin level auth can change this value.

set_prioritize_first_last(prioritize)

Deprecated: Use set_prioritize_first_last_pieces.

set_prioritize_first_last_pieces(prioritize)

Prioritize the first and last pieces in the torrent.

Parameters

prioritize (bool) – Prioritize the first and last pieces.

set_remove_at_ratio(remove_at_ratio)

Remove the torrent when it has reached the stop_ratio.

Parameters

remove_at_ratio (bool) – Remove the torrent.

set_save_path(download_location)

Deprecated: Use set_download_location.

set_sequential_download(set_sequencial)

Sets whether to download the pieces of the torrent in order.

Parameters

set_sequencial (bool) – Enable sequencial downloading.

set_status_message(message=None)

Sets the torrent status message.

Calling method without a message will reset the message to ‘OK’.

Parameters

message (str, optional) – The status message.

set_stop_at_ratio(stop_at_ratio)

Stop the torrent when it has reached stop_ratio.

Parameters

stop_at_ratio (bool) – Stop the torrent.

set_stop_ratio(stop_ratio)

The seeding ratio to stop (or remove) the torrent at.

Parameters

stop_ratio (float) – The seeding ratio.

set_super_seeding(super_seeding)

Set super seeding/initial seeding.

Parameters

super_seeding (bool) – Enable super seeding.

set_tracker_status(status)

Sets the tracker status.

Parameters

status (str) – The tracker status.

Emits:

TorrentTrackerStatusEvent upon tracker status change.

set_trackers(trackers=None)

Sets the trackers for this torrent.

Parameters

trackers (list of dicts) – A list of trackers.

update_state()

Updates the state, based on libtorrent’s torrent state

update_status(status)

Updates the cached status.

Parameters

status (libtorrent.torrent_status) – a libtorrent torrent status

write_torrentfile(filedump=None)

Writes the torrent file to the state dir and optional ‘copy of’ dir.

Parameters

filedump (str, optional) – bencoded filedump of a torrent file.

class deluge.core.torrent.TorrentError(error_message, was_paused=False, restart_to_resume=False)

Bases: object

class deluge.core.torrent.TorrentOptions

Bases: dict

TorrentOptions create a dict of the torrent options.

add_paused

Add the torrrent in a paused state.

Type

bool

auto_managed

Set torrent to auto managed mode, i.e. will be started or queued automatically.

Type

bool

download_location

The path for the torrent data to be stored while downloading.

Type

str

file_priorities

The priority for files in torrent, range is [0..7] however only [0, 1, 4, 7] are normally used and correspond to [Skip, Low, Normal, High]

Type

list of int

mapped_files

A mapping of the renamed filenames in ‘index:filename’ pairs.

Type

dict

max_connections

Sets maximum number of connections this torrent will open. This must be at least 2. The default is unlimited (-1).

Type

int

max_download_speed

Will limit the download bandwidth used by this torrent to the limit you set.The default is unlimited (-1) but will not exceed global limit.

Type

float

max_upload_slots

Sets the maximum number of peers that are unchoked at the same time on this torrent. This defaults to infinite (-1).

Type

int

max_upload_speed

Will limit the upload bandwidth used by this torrent to the limit you set. The default is unlimited (-1) but will not exceed global limit.

Type

float

move_completed

Move the torrent when downloading has finished.

Type

bool

move_completed_path

The path to move torrent to when downloading has finished.

Type

str

name

The display name of the torrent.

Type

str

owner

The user this torrent belongs to.

Type

str

pre_allocate_storage

When adding the torrent should all files be pre-allocated.

Type

bool

prioritize_first_last_pieces

Prioritize the first and last pieces in the torrent.

Type

bool

remove_at_ratio

Remove the torrent when it has reached the stop_ratio.

Type

bool

seed_mode

Assume that all files are present for this torrent (Only used when adding a torent).

Type

bool

sequential_download

Download the pieces of the torrent in order.

Type

bool

shared

Enable the torrent to be seen by other Deluge users.

Type

bool

stop_at_ratio

Stop the torrent when it has reached stop_ratio.

Type

bool

stop_ratio

The seeding ratio to stop (or remove) the torrent at.

Type

float

super_seeding

Enable super seeding/initial seeding.

Type

bool

deluge.core.torrent.convert_lt_files(files)

Indexes and decodes files from libtorrent get_files().

Parameters

files (list) – The libtorrent torrent files.

Returns

list of dict – The files.

The format for the file dict:

{
    "index": int,
    "path": str,
    "size": int,
    "offset": int
}

deluge.core.torrent.sanitize_filepath(filepath, folder=False)

Returns a sanitized filepath to pass to libtorrent rename_file().

The filepath will have backslashes substituted along with whitespace padding and duplicate slashes stripped.

Parameters

folder (bool) – A trailing slash is appended to the returned filepath.

deluge.core.torrentmanager module

TorrentManager handles Torrent objects

class deluge.core.torrentmanager.TorrentManager

Bases: deluge.component.Component

TorrentManager contains a list of torrents in the current libtorrent session.

This object is also responsible for saving the state of the session for use on restart.

add(torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None)

Adds a torrent to the torrent manager.

Parameters
  • torrent_info (lt.torrent_info, optional) – A libtorrent torrent_info object.

  • state (TorrentState, optional) – The torrent state.

  • options (dict, optional) – The options to apply to the torrent on adding.

  • save_state (bool, optional) – If True save the session state after adding torrent, defaults to True.

  • filedump (str, optional) – bencoded filedump of a torrent file.

  • filename (str, optional) – The filename of the torrent file.

  • magnet (str, optional) – The magnet uri.

  • resume_data (lt.entry, optional) – libtorrent fast resume data.

Returns

str – If successful the torrent_id of the added torrent, None if adding the torrent failed.

Emits:

TorrentAddedEvent: Torrent with torrent_id added to session.

add_async(torrent_info=None, state=None, options=None, save_state=True, filedump=None, filename=None, magnet=None, resume_data=None)

Adds a torrent to the torrent manager using libtorrent async add torrent method.

Parameters
  • torrent_info (lt.torrent_info, optional) – A libtorrent torrent_info object.

  • state (TorrentState, optional) – The torrent state.

  • options (dict, optional) – The options to apply to the torrent on adding.

  • save_state (bool, optional) – If True save the session state after adding torrent, defaults to True.

  • filedump (str, optional) – bencoded filedump of a torrent file.

  • filename (str, optional) – The filename of the torrent file.

  • magnet (str, optional) – The magnet uri.

  • resume_data (lt.entry, optional) – libtorrent fast resume data.

Returns

Deferred – If successful the torrent_id of the added torrent, None if adding the torrent failed.

Emits:

TorrentAddedEvent: Torrent with torrent_id added to session.

add_async_callback(handle, d, options, state, filename, magnet, resume_data, filedump, save_state)
archive_state(message)
callLater
cleanup_torrents_prev_status()

Run cleanup_prev_status for each registered torrent

create_state()

Create a state of all the torrents in TorrentManager.

Returns

TorrentManagerState – The TorrentManager state.

fixup_state(state)

Fixup an old state by adding missing TorrentState options and assigning default values.

Parameters

state (TorrentManagerState) – A torrentmanager state containing torrent details.

Returns

TorrentManagerState – A fixedup TorrentManager state.

get_queue_position(torrent_id)

Get queue position of torrent

get_torrent_info_from_file(filepath)

Retrieves torrent_info from the file specified.

Parameters

filepath (str) – The filepath to extract torrent info from.

Returns

lt.torrent_info – A libtorrent torrent_info dict or None if invalid file or data.

get_torrent_list()

Creates a list of torrent_ids, owned by current user and any marked shared.

Returns

list – A list of torrent_ids.

handle_torrents_status_callback(status_request)

Build the status dictionary with torrent values

load_resume_data_file()

Load the resume data from file for all torrents.

Returns

dict – A dict of torrents and their resume_data.

load_state()

Load all the torrents from TorrentManager state into session.

Emits:

SessionStartedEvent: Emitted after all torrents are added to the session.

on_alert_add_torrent(alert)

Alert handler for libtorrent add_torrent_alert

on_alert_external_ip(alert)

Alert handler for libtorrent external_ip_alert

Note

The alert.message IPv4 address format is:

‘external IP received: 0.0.0.0’

and IPv6 address format is:

‘external IP received: 0:0:0:0:0:0:0:0’

on_alert_fastresume_rejected(alert)

Alert handler for libtorrent fastresume_rejected_alert

on_alert_file_completed(alert)

Alert handler for libtorrent file_completed_alert

Emits:

TorrentFileCompletedEvent: When an individual file completes downloading.

on_alert_file_error(alert)

Alert handler for libtorrent file_error_alert

on_alert_file_renamed(alert)

Alert handler for libtorrent file_renamed_alert.

Emits:

TorrentFileRenamedEvent: Files in the torrent have been renamed.

on_alert_metadata_received(alert)

Alert handler for libtorrent metadata_received_alert

on_alert_performance(alert)

Alert handler for libtorrent performance_alert

on_alert_save_resume_data(alert)

Alert handler for libtorrent save_resume_data_alert

on_alert_save_resume_data_failed(alert)

Alert handler for libtorrent save_resume_data_failed_alert

on_alert_state_changed(alert)

Alert handler for libtorrent state_changed_alert.

Emits:

TorrentStateChangedEvent: The state has changed.

on_alert_state_update(alert)

Alert handler for libtorrent state_update_alert

Result of a session.post_torrent_updates() call and contains the torrent status of all torrents that changed since last time this was posted.

on_alert_storage_moved(alert)

Alert handler for libtorrent storage_moved_alert

on_alert_storage_moved_failed(alert)

Alert handler for libtorrent storage_moved_failed_alert

on_alert_torrent_checked(alert)

Alert handler for libtorrent torrent_checked_alert

on_alert_torrent_finished(alert)

Alert handler for libtorrent torrent_finished_alert

on_alert_torrent_paused(alert)

Alert handler for libtorrent torrent_paused_alert

on_alert_torrent_resumed(alert)

Alert handler for libtorrent torrent_resumed_alert

on_alert_tracker_announce(alert)

Alert handler for libtorrent tracker_announce_alert

on_alert_tracker_error(alert)

Alert handler for libtorrent tracker_error_alert

on_alert_tracker_reply(alert)

Alert handler for libtorrent tracker_reply_alert

on_alert_tracker_warning(alert)

Alert handler for libtorrent tracker_warning_alert

on_prefetch_metadata(torrent_info, torrent_id, defer_timeout)
on_set_max_connections_per_torrent(key, value)

Sets the per-torrent connection limit

on_set_max_download_speed_per_torrent(key, value)

Sets the per-torrent download speed limit

on_set_max_upload_slots_per_torrent(key, value)

Sets the per-torrent upload slot limit

on_set_max_upload_speed_per_torrent(key, value)

Sets the per-torrent upload speed limit

open_state()

Open the torrents.state file containing a TorrentManager state with session torrents.

Returns

TorrentManagerState – The TorrentManager state.

prefetch_metadata(magnet, timeout)

Download the metadata for a magnet uri.

Parameters
  • magnet (str) – A magnet uri to download the metadata for.

  • timeout (int) – Number of seconds to wait before cancelling.

Returns

Deferred – A tuple of (torrent_id (str), metadata (dict))

queue_bottom(torrent_id)

Queue torrent to bottom

queue_down(torrent_id)

Queue torrent down one position

queue_top(torrent_id)

Queue torrent to top

queue_up(torrent_id)

Queue torrent up one position

remove(torrent_id, remove_data=False, save_state=True)

Remove a torrent from the session.

Parameters
  • torrent_id (str) – The torrent ID to remove.

  • remove_data (bool, optional) – If True, remove the downloaded data, defaults to False.

  • save_state (bool, optional) – If True, save the session state after removal, defaults to True.

Returns

bool – True if removed successfully, False if not.

Emits:

PreTorrentRemovedEvent: Torrent is about to be removed from session. TorrentRemovedEvent: Torrent with torrent_id removed from session.

Raises

InvalidTorrentError – If the torrent_id is not in the session.

save_resume_data(torrent_ids=None, flush_disk_cache=False)

Saves torrents resume data.

Parameters
  • torrent_ids (list of str) – A list of torrents to save the resume data for, defaults to None which saves all torrents resume data.

  • flush_disk_cache (bool, optional) – If True flushes the disk cache which avoids potential issue with file timestamps, defaults to False. This is only needed when stopping the session.

Returns

t.i.d.DeferredList – A list of twisted Deferred callbacks to be invoked when save is complete.

save_resume_data_file(queue_task=False)

Save resume data to file in a separate thread to avoid blocking main thread.

Parameters

queue_task (bool) – If True and a save task is already running then queue this save task to run next. Default is to not queue save tasks.

Returns

Deferred

Fires with arg, True if save task was successful, False if

not and None if task was not performed.

save_state()

Run the save state task in a separate thread to avoid blocking main thread.

Note

If a save task is already running, this call is ignored.

separate_keys(keys, torrent_ids)

Separates the input keys into torrent class keys and plugins keys

start()
stop()
torrents_status_update(torrent_ids, keys, diff=False)

Returns status dict for the supplied torrent_ids async.

Note

If torrent states was updated recently post_torrent_updates is not called and instead cached state is used.

Parameters
  • torrent_ids (list of str) – The torrent IDs to get the status of.

  • keys (list of str) – The keys to get the status on.

  • diff (bool, optional) – If True, will return a diff of the changes since the last call to get_status based on the session_id, defaults to False.

Returns

dict – A status dictionary for the requested torrents.

update()
class deluge.core.torrentmanager.TorrentManagerState

Bases: object

TorrentManagerState holds a list of TorrentState objects.

Note

This must be old style class to avoid breaking torrent.state file.

class deluge.core.torrentmanager.TorrentState(torrent_id=None, filename=None, trackers=None, storage_mode='sparse', paused=False, save_path=None, max_connections=-1, max_upload_slots=-1, max_upload_speed=-1.0, max_download_speed=-1.0, prioritize_first_last=False, sequential_download=False, file_priorities=None, queue=None, auto_managed=True, is_finished=False, stop_ratio=2.0, stop_at_ratio=False, remove_at_ratio=False, move_completed=False, move_completed_path=None, magnet=None, owner=None, shared=False, super_seeding=False, name=None)

Bases: object

Create a torrent state.

Note

This must be old style class to avoid breaking torrent.state file.

Module contents