tribler.core.libtorrent.download_manager.download

A wrapper around a libtorrent download.

Author(s): Arno Bakker, Egbert Bouman

Attributes

Getter

logger

Exceptions

SaveResumeDataError

This error is used when the resume data of a download fails to save.

Classes

PeerDict

Information of another peer, connected through libtorrent.

PeerDictHave

Extended peer info that includes the "have" field.

TrackerStatusDict

Information about the state of a tracker.

AlertHandlerDict

Alert handler dictionary.

Download

Download subclass that represents a libtorrent download.

Functions

cached_read(→ list[str])

Keep one cache for one tracker file at a time (by default: for a max of 120 seconds, see caller).

Module Contents

tribler.core.libtorrent.download_manager.download.Getter
tribler.core.libtorrent.download_manager.download.logger
exception tribler.core.libtorrent.download_manager.download.SaveResumeDataError

Bases: Exception

This error is used when the resume data of a download fails to save.

class tribler.core.libtorrent.download_manager.download.PeerDict

Bases: TypedDict

Information of another peer, connected through libtorrent.

id: str
extended_version: str
ip: str
port: int
pex_received: bool
optimistic: bool
direction: str
uprate: float
uinterested: bool
uchoked: bool
uhasqueries: bool
uflushed: bool
downrate: float
dinterested: bool
dchoked: bool
snubbed: bool
utotal: float
dtotal: float
completed: float
speed: float
class tribler.core.libtorrent.download_manager.download.PeerDictHave

Bases: PeerDict

Extended peer info that includes the “have” field.

have: list[bool]
class tribler.core.libtorrent.download_manager.download.TrackerStatusDict

Bases: TypedDict

Information about the state of a tracker.

url: str
peers: int
seeds: int
leeches: int
status: str
class tribler.core.libtorrent.download_manager.download.AlertHandlerDict

Bases: TypedDict

Alert handler dictionary.

tracker_reply_alert: list[collections.abc.Callable[[libtorrent.tracker_reply_alert], None]]
tracker_error_alert: list[collections.abc.Callable[[libtorrent.tracker_error_alert], None]]
tracker_warning_alert: list[collections.abc.Callable[[libtorrent.tracker_warning_alert], None]]
metadata_received_alert: list[collections.abc.Callable[[libtorrent.metadata_received_alert], None]]
performance_alert: list[collections.abc.Callable[[libtorrent.performance_alert], None]]
torrent_checked_alert: list[collections.abc.Callable[[libtorrent.torrent_checked_alert], None]]
torrent_finished_alert: list[collections.abc.Callable[[libtorrent.torrent_finished_alert], None]]
save_resume_data_alert: list[collections.abc.Callable[[libtorrent.save_resume_data_alert], None]]
state_changed_alert: list[collections.abc.Callable[[libtorrent.state_changed_alert], None]]
torrent_error_alert: list[collections.abc.Callable[[libtorrent.torrent_error_alert], None]]
add_torrent_alert: list[collections.abc.Callable[[libtorrent.add_torrent_alert], None]]
torrent_removed_alert: list[collections.abc.Callable[[libtorrent.torrent_removed_alert], None]]
read_piece_alert: list[collections.abc.Callable[[libtorrent.read_piece_alert], None]]
tribler.core.libtorrent.download_manager.download.cached_read(tracker_file: str, _: int) list[str]

Keep one cache for one tracker file at a time (by default: for a max of 120 seconds, see caller).

When adding X torrents at once, this avoids reading the same file X times.

class tribler.core.libtorrent.download_manager.download.Download(tdef: tribler.core.libtorrent.torrentdef.TorrentDef, download_manager: tribler.core.libtorrent.download_manager.download_manager.DownloadManager, config: tribler.core.libtorrent.download_manager.download_config.DownloadConfig | None = None, notifier: tribler.core.notifier.Notifier | None = None, state_dir: pathlib.Path | None = None, checkpoint_disabled: bool = False, hidden: bool = False)

Bases: ipv8.taskmanager.TaskManager

Download subclass that represents a libtorrent download.

_logger
tdef
handle: libtorrent.torrent_handle | None = None
state_dir = None
download_manager
notifier = None
lt_status: libtorrent.torrent_status | None = None
error = None
pause_after_next_hashcheck = False
checkpoint_after_next_hashcheck = False
tracker_status: dict[str, tuple[int, str]]
piece_hashes_v2: list[bytes | None] = []
futures: dict[str, list[tuple[asyncio.Future, collections.abc.Callable, Getter | None]]]
alert_handlers: dict[str, list[collections.abc.Callable[[libtorrent.torrent_alert], None]]]
future_added
future_removed
future_finished
future_metainfo
stream: tribler.core.libtorrent.download_manager.stream.Stream | None = None
hidden = False
checkpoint_disabled = False
config: tribler.core.libtorrent.download_manager.download_config.DownloadConfig
__str__() str

Convert this download to a human-readable string.

__repr__() str

Convert this download to a print-safe human-readable string.

async _recheck_after_finish() None

Wait for the torrent to finish downloading, then recheck.

Note: a finished recheck causes a torrent_finished_alert: hooking into that causes an infinite loop! Note2: our own self.lt_status is too old. Note3: the state flip-flops too much to be reliable so we use completed_time instead.

async stop_after_metainfo() None

Wait for the metadata to be received, then stop.

add_stream() None

Initialize a stream for this download.

on_read_piece_alert(alert: libtorrent.read_piece_alert) None

Callback with piece contents in response to a handle.read_piece call.

Currently, this is only used to construct v2 piece hashes when exporting v2-only torrents.

async get_torrent_data() dict[bytes, Any] | None

Return torrent data, if the handle is valid and metadata is available.

_get_default_trackers() list[str]

Get the default trackers from the configured tracker file.

Tracker file format is “(<TRACKER><NEWLINE><NEWLINE>)*”. We assume “<TRACKER>” does not include newlines.

async write_backup_torrent_file() None

Write a torrent file to the backup “.torrent”-file folder.

In contrast to the individual torrent export, which sends torrent data to the client, this method saves a torrent to the server’s “torrent_folder”.

async perform_post_handle_ops() None

Look at the outstanding requested operations and run them.

schedule_post_handle_ops() None

There should be at most one task to perform the configured post-handle operations.

register_alert_handler(alert_type: str, handler: collections.abc.Callable[[libtorrent.torrent_alert], None]) None

Add (no replace) a callback for a given alert type.

wait_for_alert(success_type: str, success_getter: Getter | None = None, fail_type: str | None = None, fail_getter: Getter | None = None) asyncio.Future

Create a future that fires when a certain alert is received.

async wait_for_status(*status: tribler.core.libtorrent.download_manager.download_state.DownloadStatus) None

Wait for a given download status to occur.

get_def() tribler.core.libtorrent.torrentdef.TorrentDef

Get the torrent def belonging to this download.

get_handle() asyncio.Future[libtorrent.torrent_handle]

Returns a deferred that fires with a valid libtorrent download handle.

on_add_torrent_alert(alert: libtorrent.add_torrent_alert) None

Handle an add torrent alert.

get_anon_mode() bool

Get whether this torrent is anonymized.

get_pieces_base64(handle: libtorrent.torrent_handle) bytes

Returns a base64 encoded bitmask of the pieces that we have.

post_alert(alert_type: str, alert_dict: dict | None = None) None

Manually post an alert.

process_alert(alert: libtorrent.torrent_alert, alert_type: str) None

Dispatch an alert to the appriopriate registered handlers.

on_torrent_error_alert(alert: libtorrent.torrent_error_alert) None

Handle a torrent error alert.

on_state_changed_alert(alert: libtorrent.state_changed_alert) None

Handle a state change alert.

on_save_resume_data_alert(alert: libtorrent.save_resume_data_alert) None

Callback for the alert that contains the resume data of a specific download. This resume data will be written to a file on disk.

on_tracker_reply_alert(alert: libtorrent.tracker_reply_alert) None

Handle a tracker reply alert.

on_tracker_error_alert(alert: libtorrent.tracker_error_alert) None

This alert is generated on tracker timeouts, premature disconnects, invalid response or an HTTP response other than “200 OK”. - From Libtorrent documentation.

on_tracker_warning_alert(alert: libtorrent.tracker_warning_alert) None

Handle a tracker warning alert.

on_metadata_received_alert(handle: libtorrent.torrent_handle, alert: libtorrent.metadata_received_alert) None

Handle a metadata received alert.

on_performance_alert(alert: libtorrent.performance_alert) None

Handle a performance alert.

on_torrent_removed_alert(alert: libtorrent.torrent_removed_alert) None

Handle a torrent removed alert.

on_torrent_checked_alert(alert: libtorrent.torrent_checked_alert) None

Handle a torrent checked alert.

on_torrent_finished_alert(handle: libtorrent.torrent_handle, alert: libtorrent.torrent_finished_alert) None

Handle a torrent finished alert.

get_seeding_ratio() float

Get the actual seeding ratio of this download (the user config may be None).

update_lt_status(lt_status: libtorrent.torrent_status) None

Update libtorrent stats and check if the download should be stopped.

set_selected_files(handle: libtorrent.torrent_handle, selected_files: list[int] | None = None, prio: int = 4, force: bool = False) None

Set the selected files. If the selected files is None or empty, all files will be selected.

move_storage(handle: libtorrent.torrent_handle, new_dir: pathlib.Path) bool

Move the output files to a different location.

force_recheck(handle: libtorrent.torrent_handle) None

Force libtorrent to validate the files.

get_state() tribler.core.libtorrent.download_manager.download_state.DownloadState

Returns a snapshot of the current state of the download.

async save_resume_data(timeout: int = 10) None

Save the resume data of a download. This method returns when the resume data is available. Note that this method only calls save_resume_data once on subsequent calls.

get_peer_list(include_have: bool = True) list[PeerDict | PeerDictHave]

Returns a list of dictionaries, one for each connected peer containing the statistics for that peer. In particular, the dictionary contains the keys.

get_num_connected_seeds_peers() tuple[int, int]

Return the number of connected seeders and leechers.

get_torrent() dict[bytes, Any] | None

Create the raw torrent data from this download.

get_tracker_status(handle: libtorrent.torrent_handle) list[TrackerStatusDict]

Retrieve an overview of the trackers and their statuses.

async shutdown() None

Shut down the download.

stop(user_stopped: bool | None = None) collections.abc.Awaitable[None]

Stop downloading the download.

resume() None

Resume downloading the download.

get_content_dest() pathlib.Path

Returns the file to which the downloaded content is saved.

checkpoint() collections.abc.Awaitable[None]

Checkpoint this download. Returns when the checkpointing is completed.

add_trackers(handle: libtorrent.torrent_handle, trackers: list[str]) None

Add the given trackers to the handle.

Generate a magnet link for our download.

add_peer(handle: libtorrent.torrent_handle, addr: tuple[str, int]) None

Add a peer address from 3rd source (not tracker, not DHT) to this download.

Parameters:
  • handle – the valid torrent handle.

  • addr – The (hostname_ip,port) tuple to connect to

add_url_seed(handle: libtorrent.torrent_handle, addr: str) None

Add a URL seed to this download.

Parameters:
  • handle – the valid torrent handle.

  • addr – The URL address to connect to

set_priority(handle: libtorrent.torrent_handle, priority: int) None

Set the priority of this download.

set_max_upload_rate(handle: libtorrent.torrent_handle, value: int) None

Set the maximum upload rate of this download.

set_max_download_rate(handle: libtorrent.torrent_handle, value: int) None

Set the maximum download rate of this download.

get_share_mode() bool

Get whether this download is in sharing mode.

set_share_mode(handle: libtorrent.torrent_handle, share_mode: bool) None

Set whether this download is in sharing mode.

get_upload_mode() bool

Get whether this download is in upload mode.

set_upload_mode(handle: libtorrent.torrent_handle, upload_mode: bool) None

Set whether this download is in upload mode.

force_dht_announce(handle: libtorrent.torrent_handle) None

Force announce thid download on the DHT.

set_sequential_download(handle: libtorrent.torrent_handle, enable: bool) None

Set this download to sequential download mode.

set_piece_priorities(handle: libtorrent.torrent_handle, piece_priorities: list[int]) None

Set the priority for all pieces in the download.

get_piece_priorities(handle: libtorrent.torrent_handle) list[int]

Get the priorities of all pieces in the download.

set_file_priorities(handle: libtorrent.torrent_handle, file_priorities: list[int]) None

Set the priority for all files in the download.

set_file_priority(handle: libtorrent.torrent_handle, file_index: int, prio: int = 4) None

Set the priority for a particular file in the download.

reset_piece_deadline(handle: libtorrent.torrent_handle, piece: int) None

Reset the deadline for the given piece.

set_piece_deadline(handle: libtorrent.torrent_handle, piece: int, deadline: int, flags: int = 0) None

Set the deadline for a given piece.

get_file_priorities(handle: libtorrent.torrent_handle) list[int]

Get the priorities of all files in the download.

file_piece_range(file_path: pathlib.Path) list[int]

Get the piece range of a given file, specified by the path.

Calling this method with anything but a file path will return an empty list.

get_file_completion(handle: libtorrent.torrent_handle, path: pathlib.Path) float

Calculate the completion of a given file or directory.

get_file_length(path: pathlib.Path) int

Get the length of a file or directory in bytes. Returns 0 if the given path does not point to an existing path.

get_file_index(path: pathlib.Path) int | None

Get the index of a file or directory in a torrent, or None if it does not exist.

set_selected_file_or_dir(handle: libtorrent.torrent_handle, path: pathlib.Path, selected: bool) None

Set a single file or directory to be selected or not.

is_file_selected(file_path: pathlib.Path) bool

Check if the given file path is selected.

Calling this method with anything but a file path will lead to undefined behavior!

async set_upload_limit(value: int) None

Set the upload bandwidth limit for this torrent.

get_upload_limit() int

Get the upload bandwidth limit for this torrent.

async set_download_limit(value: int) None

Set the download bandwidth limit for this torrent.

get_download_limit() int

Get the download bandwidth limit for this torrent.

queue_position_up(handle: libtorrent.torrent_handle) None

Move download up in the download queue.

queue_position_top(handle: libtorrent.torrent_handle) None

Move download to the top of the download queue.

queue_position_down(handle: libtorrent.torrent_handle) None

Move download down in the download queue.

queue_position_bottom(handle: libtorrent.torrent_handle) None

Move download to the bottom of the download queue.

get_queue_position(handle: libtorrent.torrent_handle) int

Returns the position in the download queue. If the torrent is a seed or finished, -1 is returned.

set_auto_managed(handle: libtorrent.torrent_handle, value: bool) None

Set the auto managed flag.