Skip to content

aria2p ¤

aria2p package.

Command-line tool and library to interact with an aria2c daemon process with JSON-RPC.

Modules:

  • api

    Aria2 API.

  • cli

    The CLI submodule.

  • client

    Client module.

  • debug

    Debugging utilities.

  • downloads

    This module defines the BitTorrent, File and Download classes.

  • interface

    This module contains all the code responsible for the HTOP-like interface.

  • options

    Module for aria2c options.

  • stats

    This module defines the Stats class.

  • utils

    Utils module.

Classes:

  • API

    A class providing high-level methods to interact with a remote aria2c process.

  • BitTorrent

    Information retrieved from a torrent file.

  • Client

    The JSON-RPC client class.

  • ClientException

    An exception specific to JSON-RPC errors.

  • Download

    Class containing all information about a download, as retrieved with the client.

  • File

    Information about a download's file.

  • Options

    This class holds information retrieved with the get_option or get_global_option methods of the client.

  • Stats

    This class holds information retrieved with the get_global_stat method of the client.

Functions:

API ¤

API(client: Client | None = None)

A class providing high-level methods to interact with a remote aria2c process.

This class is instantiated with a reference to a Client instance. It then uses this client to call remote procedures, or remote methods. While the client methods reflect exactly what aria2c is providing through JSON-RPC, this class's methods allow for easier / faster control of the remote process. It also wraps the information the client retrieves in Python object, like Download, allowing for even more Pythonic interactions, without worrying about payloads, responses, JSON, etc..

Parameters:

Methods:

  • add

    Add a download (guess its type).

  • add_magnet

    Add a download with a Magnet URI.

  • add_metalink

    Add a download with a Metalink file.

  • add_torrent

    Add a download with a torrent file (usually .torrent extension).

  • add_uris

    Add a download with a URL (or more).

  • autopurge

    Purge completed, removed or failed downloads from the queue.

  • copy_files

    Copy downloaded files to another directory.

  • get_download

    Get a Download object thanks to its GID.

  • get_downloads

    Get a list of Download object thanks to their GIDs.

  • get_global_options

    Get the global options.

  • get_options

    Get options for each of the given downloads.

  • get_stats

    Get the stats of the remote aria2c process.

  • listen_to_notifications

    Start listening to aria2 notifications via WebSocket.

  • move

    Move a download in the queue, relatively to its current position.

  • move_down

    Move a download down in the queue.

  • move_files

    Move downloaded files to another directory.

  • move_to

    Move a download in the queue, with absolute positioning.

  • move_to_bottom

    Move a download to the bottom of the queue.

  • move_to_top

    Move a download to the top of the queue.

  • move_up

    Move a download up in the queue.

  • parse_input_file

    Parse a file with URIs or an aria2c input file.

  • pause

    Pause the given (active) downloads.

  • pause_all

    Pause all (active) downloads.

  • purge

    Purge completed, removed or failed downloads from the queue.

  • remove

    Remove the given downloads from the list.

  • remove_all

    Remove all downloads from the list.

  • remove_files

    Remove downloaded files.

  • resume

    Resume (unpause) the given downloads.

  • resume_all

    Resume (unpause) all downloads.

  • retry_downloads

    Resume failed downloads from where they left off with new GIDs.

  • search

    Not implemented.

  • set_global_options

    Set global options.

  • set_options

    Set options for specific downloads.

  • split_input_file

    Helper to split downloads in an input file.

  • stop_listening

    Stop listening to notifications.

Source code in src/aria2p/api.py
43
44
45
46
47
48
49
50
def __init__(self, client: Client | None = None) -> None:
    """Initialize the object.

    Parameters:
        client: An instance of the [aria2p.client.Client][] class.
    """
    self.client = client or Client()
    self.listener: threading.Thread | None = None

add ¤

add(
    uri: str,
    options: OptionsType | None = None,
    position: int | None = None,
) -> list[Download]

Add a download (guess its type).

If the provided URI is in fact a file-path, and is neither a torrent or a metalink, then we read its lines and try to add each line as a download, recursively.

Parameters:

  • uri (str) –

    The URI or file-path to add.

  • options (OptionsType | None, default: None ) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • position (int | None, default: None ) –

    The position where to insert the new download in the queue. Start at 0 (top).

Returns:

Source code in src/aria2p/api.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def add(
    self,
    uri: str,
    options: OptionsType | None = None,
    position: int | None = None,
) -> list[Download]:
    """Add a download (guess its type).

    If the provided URI is in fact a file-path, and is neither a torrent or a metalink,
    then we read its lines and try to add each line as a download, recursively.

    Parameters:
        uri: The URI or file-path to add.
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.
        position: The position where to insert the new download in the queue. Start at 0 (top).

    Returns:
        The created downloads.
    """
    new_downloads = []
    path = Path(uri)

    # On Windows, path.exists() generates an OSError when path is an URI
    # See https://github.com/pawamoy/aria2p/issues/41
    try:
        path_exists = path.exists()
    except OSError:
        path_exists = False

    if path_exists:
        if path.suffix == ".torrent":
            new_downloads.append(self.add_torrent(path, options=options, position=position))
        elif path.suffix == ".metalink":
            new_downloads.extend(self.add_metalink(path, options=options, position=position))
        else:
            for uris, download_options in self.parse_input_file(path):
                # Add batch downloads in specified position in queue.
                new_downloads.append(self.add_uris(uris, options=download_options, position=position))
                if position is not None:
                    position += 1

    elif uri.startswith("magnet:?"):
        new_downloads.append(self.add_magnet(uri, options=options, position=position))
    else:
        new_downloads.append(self.add_uris([uri], options=options, position=position))

    return new_downloads

add_magnet ¤

add_magnet(
    magnet_uri: str,
    options: OptionsType | None = None,
    position: int | None = None,
) -> Download

Add a download with a Magnet URI.

Parameters:

  • magnet_uri (str) –

    The Magnet URI.

  • options (OptionsType | None, default: None ) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • position (int | None, default: None ) –

    The position where to insert the new download in the queue. Start at 0 (top).

Returns:

  • Download

    The newly created download object.

Source code in src/aria2p/api.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def add_magnet(self, magnet_uri: str, options: OptionsType | None = None, position: int | None = None) -> Download:
    """Add a download with a Magnet URI.

    Parameters:
        magnet_uri: The Magnet URI.
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.
        position: The position where to insert the new download in the queue. Start at 0 (top).

    Returns:
        The newly created download object.
    """
    if options is None:
        options = {}

    client_options = options.get_struct() if isinstance(options, Options) else options

    gid = self.client.add_uri([magnet_uri], client_options, position)

    return self.get_download(gid)
add_metalink(
    metalink_file_path: str | Path,
    options: OptionsType | None = None,
    position: int | None = None,
) -> list[Download]

Add a download with a Metalink file.

Parameters:

  • metalink_file_path (str | Path) –

    The path to the Metalink file.

  • options (OptionsType | None, default: None ) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • position (int | None, default: None ) –

    The position where to insert the new download in the queue. Start at 0 (top).

Returns:

Source code in src/aria2p/api.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def add_metalink(
    self,
    metalink_file_path: str | Path,
    options: OptionsType | None = None,
    position: int | None = None,
) -> list[Download]:
    """Add a download with a Metalink file.

    Parameters:
        metalink_file_path: The path to the Metalink file.
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.
        position: The position where to insert the new download in the queue. Start at 0 (top).

    Returns:
        The newly created download objects.
    """
    if options is None:
        options = {}

    client_options = options.get_struct() if isinstance(options, Options) else options

    with open(metalink_file_path, "rb") as stream:
        metalink_contents = stream.read()
    encoded_contents = b64encode(metalink_contents).decode("utf8")

    gids = self.client.add_metalink(encoded_contents, client_options, position)

    return self.get_downloads(gids)

add_torrent ¤

add_torrent(
    torrent_file_path: str | Path,
    uris: list[str] | None = None,
    options: OptionsType | None = None,
    position: int | None = None,
) -> Download

Add a download with a torrent file (usually .torrent extension).

Parameters:

  • torrent_file_path (str | Path) –

    The path to the torrent file.

  • uris (list[str] | None, default: None ) –

    A list of URIs used for Web-seeding.

  • options (OptionsType | None, default: None ) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • position (int | None, default: None ) –

    The position where to insert the new download in the queue. Start at 0 (top).

Returns:

  • Download

    The newly created download object.

Source code in src/aria2p/api.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def add_torrent(
    self,
    torrent_file_path: str | Path,
    uris: list[str] | None = None,
    options: OptionsType | None = None,
    position: int | None = None,
) -> Download:
    """Add a download with a torrent file (usually .torrent extension).

    Parameters:
        torrent_file_path: The path to the torrent file.
        uris: A list of URIs used for Web-seeding.
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.
        position: The position where to insert the new download in the queue. Start at 0 (top).

    Returns:
        The newly created download object.
    """
    if uris is None:
        uris = []

    if options is None:
        options = {}

    client_options = options.get_struct() if isinstance(options, Options) else options

    with open(torrent_file_path, "rb") as stream:
        torrent_contents = stream.read()
    encoded_contents = b64encode(torrent_contents).decode("utf8")

    try:
        gid = self.client.add_torrent(encoded_contents, uris, client_options, position)
    except ConnectionError:
        logger.error("Torrent too big? Try increasing max size with aria2c's --rpc-max-request-size option")
        raise

    return self.get_download(gid)

add_uris ¤

add_uris(
    uris: list[str],
    options: OptionsType | None = None,
    position: int | None = None,
) -> Download

Add a download with a URL (or more).

Parameters:

  • uris (list[str]) –

    A list of URIs that point to the same resource.

  • options (OptionsType | None, default: None ) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • position (int | None, default: None ) –

    The position where to insert the new download in the queue. Start at 0 (top).

Returns:

  • Download

    The newly created download object.

Source code in src/aria2p/api.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
def add_uris(
    self,
    uris: list[str],
    options: OptionsType | None = None,
    position: int | None = None,
) -> Download:
    """Add a download with a URL (or more).

    Parameters:
        uris: A list of URIs that point to the same resource.
        options: An instance of the `Options` class or a dictionary
            containing aria2c options to create the download with.
        position: The position where to insert the new download in the queue. Start at 0 (top).

    Returns:
        The newly created download object.

    """
    if options is None:
        options = {}

    client_options = options.get_struct() if isinstance(options, Options) else options

    gid = self.client.add_uri(uris, client_options, position)

    return self.get_download(gid)

autopurge ¤

autopurge() -> bool

Purge completed, removed or failed downloads from the queue.

Deprecated. Use purge instead.

Returns:

  • bool

    Success or failure of the operation.

Source code in src/aria2p/api.py
567
568
569
570
571
572
573
574
575
576
def autopurge(self) -> bool:
    """Purge completed, removed or failed downloads from the queue.

    Deprecated. Use [`purge`][aria2p.api.API.purge] instead.

    Returns:
        Success or failure of the operation.
    """
    logger.warning("Deprecation warning: API method 'autopurge' is deprecated, use 'purge' instead.")
    return self.purge()

copy_files staticmethod ¤

copy_files(
    downloads: list[Download],
    to_directory: str | Path,
    force: bool = False,
) -> list[bool]

Copy downloaded files to another directory.

Parameters:

  • downloads (list[Download]) –

    the list of downloads for which to move files.

  • to_directory (str | Path) –

    The target directory to copy files into.

  • force (bool, default: False ) –

    Whether to move files even if download is not complete.

Returns:

  • list[bool]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
@staticmethod
def copy_files(
    downloads: list[Download],
    to_directory: str | Path,
    force: bool = False,  # noqa: FBT001,FBT002
) -> list[bool]:
    """Copy downloaded files to another directory.

    Parameters:
        downloads:  the list of downloads for which to move files.
        to_directory: The target directory to copy files into.
        force: Whether to move files even if download is not complete.

    Returns:
        Success or failure of the operation for each given download.
    """
    if isinstance(to_directory, str):
        to_directory = Path(to_directory)

    # raises FileExistsError when target is already a file
    to_directory.mkdir(parents=True, exist_ok=True)

    results = []
    for download in downloads:
        if download.is_complete or force:
            for path in download.root_files_paths:
                if path.is_dir():
                    shutil.copytree(str(path), str(to_directory / path.name))
                elif path.is_file():
                    shutil.copy(str(path), str(to_directory))

            results.append(True)
        else:
            results.append(False)
    return results

get_download ¤

get_download(gid: str) -> Download

Get a Download object thanks to its GID.

Parameters:

  • gid (str) –

    The GID of the download to get.

Returns:

  • Download

    The retrieved download object.

Source code in src/aria2p/api.py
264
265
266
267
268
269
270
271
272
273
def get_download(self, gid: str) -> Download:
    """Get a [`Download`][aria2p.downloads.Download] object thanks to its GID.

    Parameters:
        gid: The GID of the download to get.

    Returns:
        The retrieved download object.
    """
    return Download(self, self.client.tell_status(gid))

get_downloads ¤

get_downloads(
    gids: list[str] | None = None,
) -> list[Download]

Get a list of Download object thanks to their GIDs.

Parameters:

  • gids (list[str] | None, default: None ) –

    The GIDs of the downloads to get. If None, return all the downloads.

Returns:

Source code in src/aria2p/api.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def get_downloads(self, gids: list[str] | None = None) -> list[Download]:
    """Get a list of [`Download`][aria2p.downloads.Download] object thanks to their GIDs.

    Parameters:
        gids: The GIDs of the downloads to get. If None, return all the downloads.

    Returns:
        The retrieved download objects.
    """
    downloads = []

    if gids:
        for gid in gids:
            downloads.append(Download(self, self.client.tell_status(gid)))
    else:
        structs = []
        structs.extend(self.client.tell_active())
        structs.extend(self.client.tell_waiting(0, 1000))
        structs.extend(self.client.tell_stopped(0, 1000))
        downloads = [Download(self, struct) for struct in structs]

    return downloads

get_global_options ¤

get_global_options() -> Options

Get the global options.

Returns:

  • Options

    The global aria2c options.

Source code in src/aria2p/api.py
593
594
595
596
597
598
599
def get_global_options(self) -> Options:
    """Get the global options.

    Returns:
        The global aria2c options.
    """
    return Options(self, self.client.get_global_option())

get_options ¤

get_options(downloads: list[Download]) -> list[Options]

Get options for each of the given downloads.

Parameters:

  • downloads (list[Download]) –

    The list of downloads to get the options of.

Returns:

  • list[Options]

    Options object for each given download.

Source code in src/aria2p/api.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def get_options(self, downloads: list[Download]) -> list[Options]:
    """Get options for each of the given downloads.

    Parameters:
        downloads: The list of downloads to get the options of.

    Returns:
        Options object for each given download.
    """
    # Note: batch/multicall candidate
    options = []
    for download in downloads:
        options.append(Options(self, self.client.get_option(download.gid), download))
    return options

get_stats ¤

get_stats() -> Stats

Get the stats of the remote aria2c process.

Returns:

  • Stats

    The global stats returned by the remote process.

Source code in src/aria2p/api.py
634
635
636
637
638
639
640
def get_stats(self) -> Stats:
    """Get the stats of the remote aria2c process.

    Returns:
        The global stats returned by the remote process.
    """
    return Stats(self.client.get_global_stat())

listen_to_notifications ¤

listen_to_notifications(
    threaded: bool = False,
    on_download_start: Callable | None = None,
    on_download_pause: Callable | None = None,
    on_download_stop: Callable | None = None,
    on_download_complete: Callable | None = None,
    on_download_error: Callable | None = None,
    on_bt_download_complete: Callable | None = None,
    timeout: int = 5,
    handle_signals: bool = True,
) -> None

Start listening to aria2 notifications via WebSocket.

This method differs from Client.listen_to_notifications in that it expects callbacks accepting two arguments, api and gid, instead of only gid. Accepting api allows to use the high-level methods of the API class.

Stop listening to notifications with the API.stop_listening method.

Parameters:

  • threaded (bool, default: False ) –

    Whether to start the listening loop in a thread or not (non-blocking or blocking).

  • on_download_start (Callable | None, default: None ) –

    Callback for the onDownloadStart event.

  • on_download_pause (Callable | None, default: None ) –

    Callback for the onDownloadPause event.

  • on_download_stop (Callable | None, default: None ) –

    Callback for the onDownloadStop event.

  • on_download_complete (Callable | None, default: None ) –

    Callback for the onDownloadComplete event.

  • on_download_error (Callable | None, default: None ) –

    Callback for the onDownloadError event.

  • on_bt_download_complete (Callable | None, default: None ) –

    Callback for the onBtDownloadComplete event.

  • timeout (int, default: 5 ) –

    Timeout when waiting for data to be received. Use a small value for faster reactivity when stopping to listen. Default is 5 seconds.

  • handle_signals (bool, default: True ) –

    Whether to add signal handlers to gracefully stop the loop on SIGTERM and SIGINT.

Source code in src/aria2p/api.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def listen_to_notifications(
    self,
    threaded: bool = False,  # noqa: FBT001,FBT002
    on_download_start: Callable | None = None,
    on_download_pause: Callable | None = None,
    on_download_stop: Callable | None = None,
    on_download_complete: Callable | None = None,
    on_download_error: Callable | None = None,
    on_bt_download_complete: Callable | None = None,
    timeout: int = 5,
    handle_signals: bool = True,  # noqa: FBT001,FBT002
) -> None:
    """Start listening to aria2 notifications via WebSocket.

    This method differs from [`Client.listen_to_notifications`][aria2p.client.Client.listen_to_notifications]
    in that it expects callbacks accepting two arguments, `api` and `gid`, instead of only `gid`.
    Accepting `api` allows to use the high-level methods of the [`API`][aria2p.api.API] class.

    Stop listening to notifications with the [`API.stop_listening`][aria2p.api.API.stop_listening] method.

    Parameters:
        threaded: Whether to start the listening loop in a thread or not (non-blocking or blocking).
        on_download_start: Callback for the `onDownloadStart` event.
        on_download_pause: Callback for the `onDownloadPause` event.
        on_download_stop: Callback for the `onDownloadStop` event.
        on_download_complete: Callback for the `onDownloadComplete` event.
        on_download_error: Callback for the `onDownloadError` event.
        on_bt_download_complete: Callback for the `onBtDownloadComplete` event.
        timeout: Timeout when waiting for data to be received. Use a small value for faster reactivity
            when stopping to listen. Default is 5 seconds.
        handle_signals: Whether to add signal handlers to gracefully stop the loop on SIGTERM and SIGINT.
    """

    def closure(callback: Callable | None) -> Callable | None:
        return functools.partial(callback, self) if callable(callback) else None

    kwargs = {
        "on_download_start": closure(on_download_start),
        "on_download_pause": closure(on_download_pause),
        "on_download_stop": closure(on_download_stop),
        "on_download_complete": closure(on_download_complete),
        "on_download_error": closure(on_download_error),
        "on_bt_download_complete": closure(on_bt_download_complete),
        "timeout": timeout,
        "handle_signals": handle_signals,
    }

    if threaded:
        kwargs["handle_signals"] = False
        self.listener = threading.Thread(target=self.client.listen_to_notifications, kwargs=kwargs)
        self.listener.start()
    else:
        self.client.listen_to_notifications(**kwargs)  # type: ignore[arg-type]

move ¤

move(download: Download, pos: int) -> int

Move a download in the queue, relatively to its current position.

Parameters:

  • download (Download) –

    The download object to move.

  • pos (int) –

    The relative position (1 to move down, -1 to move up, -2 to move up two times, etc.).

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
298
299
300
301
302
303
304
305
306
307
308
def move(self, download: Download, pos: int) -> int:
    """Move a download in the queue, relatively to its current position.

    Parameters:
        download: The download object to move.
        pos: The relative position (1 to move down, -1 to move up, -2 to move up two times, etc.).

    Returns:
        The new position of the download.
    """
    return self.client.change_position(download.gid, pos, "POS_CUR")

move_down ¤

move_down(download: Download, pos: int = 1) -> int

Move a download down in the queue.

Parameters:

  • download (Download) –

    The download object to move.

  • pos (int, default: 1 ) –

    Number of times to move down. With negative values, will move up (use move or move_up instead).

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
339
340
341
342
343
344
345
346
347
348
349
def move_down(self, download: Download, pos: int = 1) -> int:
    """Move a download down in the queue.

    Parameters:
        download: The download object to move.
        pos: Number of times to move down. With negative values, will move up (use move or move_up instead).

    Returns:
        The new position of the download.
    """
    return self.client.change_position(download.gid, pos, "POS_CUR")

move_files staticmethod ¤

move_files(
    downloads: list[Download],
    to_directory: str | Path,
    force: bool = False,
) -> list[bool]

Move downloaded files to another directory.

Parameters:

  • downloads (list[Download]) –

    the list of downloads for which to move files.

  • to_directory (str | Path) –

    The target directory to move files to.

  • force (bool, default: False ) –

    Whether to move files even if download is not complete.

Returns:

  • list[bool]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
@staticmethod
def move_files(
    downloads: list[Download],
    to_directory: str | Path,
    force: bool = False,  # noqa: FBT001,FBT002
) -> list[bool]:
    """Move downloaded files to another directory.

    Parameters:
        downloads:  the list of downloads for which to move files.
        to_directory: The target directory to move files to.
        force: Whether to move files even if download is not complete.

    Returns:
        Success or failure of the operation for each given download.
    """
    if isinstance(to_directory, str):
        to_directory = Path(to_directory)

    # raises FileExistsError when target is already a file
    to_directory.mkdir(parents=True, exist_ok=True)

    results = []
    for download in downloads:
        if download.is_complete or force:
            for path in download.root_files_paths:
                shutil.move(str(path), str(to_directory))
            results.append(True)
        else:
            results.append(False)
    return results

move_to ¤

move_to(download: Download, pos: int) -> int

Move a download in the queue, with absolute positioning.

Parameters:

  • download (Download) –

    The download object to move.

  • pos (int) –

    The absolute position in the queue where to move the download. 0 for top, -1 for bottom.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def move_to(self, download: Download, pos: int) -> int:
    """Move a download in the queue, with absolute positioning.

    Parameters:
        download: The download object to move.
        pos: The absolute position in the queue where to move the download. 0 for top, -1 for bottom.

    Returns:
        The new position of the download.
    """
    if pos < 0:
        how = "POS_END"
        pos = -pos
    else:
        how = "POS_SET"
    return self.client.change_position(download.gid, pos, how)

move_to_bottom ¤

move_to_bottom(download: Download) -> int

Move a download to the bottom of the queue.

Parameters:

  • download (Download) –

    The download object to move.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
362
363
364
365
366
367
368
369
370
371
def move_to_bottom(self, download: Download) -> int:
    """Move a download to the bottom of the queue.

    Parameters:
        download: The download object to move.

    Returns:
        The new position of the download.
    """
    return self.client.change_position(download.gid, 0, "POS_END")

move_to_top ¤

move_to_top(download: Download) -> int

Move a download to the top of the queue.

Parameters:

  • download (Download) –

    The download object to move.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
351
352
353
354
355
356
357
358
359
360
def move_to_top(self, download: Download) -> int:
    """Move a download to the top of the queue.

    Parameters:
        download: The download object to move.

    Returns:
        The new position of the download.
    """
    return self.client.change_position(download.gid, 0, "POS_SET")

move_up ¤

move_up(download: Download, pos: int = 1) -> int

Move a download up in the queue.

Parameters:

  • download (Download) –

    The download object to move.

  • pos (int, default: 1 ) –

    Number of times to move up. With negative values, will move down (use move or move_down instead).

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/api.py
327
328
329
330
331
332
333
334
335
336
337
def move_up(self, download: Download, pos: int = 1) -> int:
    """Move a download up in the queue.

    Parameters:
        download: The download object to move.
        pos: Number of times to move up. With negative values, will move down (use move or move_down instead).

    Returns:
        The new position of the download.
    """
    return self.client.change_position(download.gid, -pos, "POS_CUR")

parse_input_file ¤

parse_input_file(
    input_file: str | Path,
) -> InputFileContentsType

Parse a file with URIs or an aria2c input file.

Parameters:

  • input_file (str | Path) –

    Path to file with URIs or aria2c input file.

Returns:

  • InputFileContentsType

    List of tuples containing list of URIs and dictionary with aria2c options.

Source code in src/aria2p/api.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
def parse_input_file(self, input_file: str | Path) -> InputFileContentsType:
    """Parse a file with URIs or an aria2c input file.

    Parameters:
        input_file: Path to file with URIs or aria2c input file.

    Returns:
        List of tuples containing list of URIs and dictionary with aria2c options.
    """
    downloads = []
    with Path(input_file).open() as fd:
        for download_lines in self.split_input_file(fd):
            uris = download_lines[0].split("\t")
            options = {}
            try:
                for option_line in download_lines[1:]:
                    option_name, option_value = option_line.split("=", 1)
                    options[option_name.lstrip()] = option_value
                downloads.append((uris, options))
            except ValueError as error:
                logger.error(f"Skipping download because of invalid option line '{option_line}'")
                logger.opt(exception=True).trace(error)
    return downloads

pause ¤

pause(
    downloads: list[Download], force: bool = False
) -> list[OperationResult]

Pause the given (active) downloads.

Parameters:

  • downloads (list[Download]) –

    The list of downloads to pause.

  • force (bool, default: False ) –

    Whether to pause immediately without contacting servers or not.

Returns:

  • list[OperationResult]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def pause(self, downloads: list[Download], force: bool = False) -> list[OperationResult]:  # noqa: FBT001,FBT002
    """Pause the given (active) downloads.

    Parameters:
        downloads: The list of downloads to pause.
        force: Whether to pause immediately without contacting servers or not.

    Returns:
        Success or failure of the operation for each given download.
    """
    # Note: batch/multicall candidate
    pause_func = self.client.force_pause if force else self.client.pause

    result: list[OperationResult] = []

    for download in downloads:
        try:
            pause_func(download.gid)
        except ClientException as error:
            logger.debug(f"Failed to pause download {download.gid}")
            logger.opt(exception=True).trace(error)
            result.append(error)
        else:
            result.append(True)

    return result

pause_all ¤

pause_all(force: bool = False) -> bool

Pause all (active) downloads.

Parameters:

  • force (bool, default: False ) –

    Whether to pause immediately without contacting servers or not.

Returns:

  • bool

    Success or failure of the operation to pause all downloads.

Source code in src/aria2p/api.py
515
516
517
518
519
520
521
522
523
524
525
def pause_all(self, force: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Pause all (active) downloads.

    Parameters:
        force: Whether to pause immediately without contacting servers or not.

    Returns:
        Success or failure of the operation to pause all downloads.
    """
    pause_func = self.client.force_pause_all if force else self.client.pause_all
    return pause_func() == "OK"

purge ¤

purge() -> bool

Purge completed, removed or failed downloads from the queue.

Returns:

  • bool

    Success or failure of the operation.

Source code in src/aria2p/api.py
559
560
561
562
563
564
565
def purge(self) -> bool:
    """Purge completed, removed or failed downloads from the queue.

    Returns:
        Success or failure of the operation.
    """
    return self.client.purge_download_result() == "OK"

remove ¤

remove(
    downloads: list[Download],
    force: bool = False,
    files: bool = False,
    clean: bool = True,
) -> list[OperationResult]

Remove the given downloads from the list.

Parameters:

  • downloads (list[Download]) –

    The list of downloads to remove.

  • force (bool, default: False ) –

    Whether to force the removal or not.

  • files (bool, default: False ) –

    Whether to remove downloads files as well.

  • clean (bool, default: True ) –

    Whether to remove the aria2 control file as well.

Returns:

  • list[OperationResult]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def remove(
    self,
    downloads: list[Download],
    force: bool = False,  # noqa: FBT001,FBT002
    files: bool = False,  # noqa: FBT001,FBT002
    clean: bool = True,  # noqa: FBT001,FBT002
) -> list[OperationResult]:
    """Remove the given downloads from the list.

    Parameters:
        downloads: The list of downloads to remove.
        force: Whether to force the removal or not.
        files: Whether to remove downloads files as well.
        clean: Whether to remove the aria2 control file as well.

    Returns:
        Success or failure of the operation for each given download.
    """
    # Note: batch/multicall candidate
    remove_func = self.client.force_remove if force else self.client.remove

    result: list[OperationResult] = []

    for download in downloads:
        if download.is_complete or download.is_removed or download.has_failed:
            logger.debug(f"Try to remove download result {download.gid}")
            try:
                self.client.remove_download_result(download.gid)
            except ClientException as error:
                logger.exception(error)
                result.append(error)
            else:
                logger.success(f"Removed download result {download.gid}")
                result.append(True)
        else:
            logger.debug(f"Try to remove download {download.gid}")
            try:
                removed_gid = remove_func(download.gid)
            except ClientException as error:
                logger.exception(error)
                result.append(error)
            else:
                logger.success(f"Removed download {download.gid}")
                result.append(True)
                try:  # (nested try)
                    self.client.remove_download_result(download.gid)
                except ClientException as error:
                    logger.debug(f"Failed to remove download result {download.gid}")
                    logger.opt(exception=True).trace(error)
                if removed_gid != download.gid:
                    logger.debug(
                        f"Removed download GID#{removed_gid} is different than download GID#{download.gid}",
                    )
                    try:
                        self.client.remove_download_result(removed_gid)
                    except ClientException as error:
                        logger.debug(f"Failed to remove download result {removed_gid}")
                        logger.opt(exception=True).trace(error)

        if clean:
            download.control_file_path.unlink(missing_ok=True)
            logger.debug(f"Removed control file {download.control_file_path}")

        if files and result[-1]:
            self.remove_files([download], force=True)

    return result

remove_all ¤

remove_all(force: bool = False) -> bool

Remove all downloads from the list.

Parameters:

  • force (bool, default: False ) –

    Whether to force the removal or not.

Returns:

  • bool

    Success or failure of the operation to remove all downloads.

Source code in src/aria2p/api.py
477
478
479
480
481
482
483
484
485
486
def remove_all(self, force: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Remove all downloads from the list.

    Parameters:
        force: Whether to force the removal or not.

    Returns:
        Success or failure of the operation to remove all downloads.
    """
    return all(self.remove(self.get_downloads(), force=force))

remove_files staticmethod ¤

remove_files(
    downloads: list[Download], force: bool = False
) -> list[bool]

Remove downloaded files.

Parameters:

  • downloads (list[Download]) –

    the list of downloads for which to remove files.

  • force (bool, default: False ) –

    Whether to remove files even if download is not complete.

Returns:

  • list[bool]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
@staticmethod
def remove_files(
    downloads: list[Download],
    force: bool = False,  # noqa: FBT001,FBT002
) -> list[bool]:
    """Remove downloaded files.

    Parameters:
        downloads:  the list of downloads for which to remove files.
        force: Whether to remove files even if download is not complete.

    Returns:
        Success or failure of the operation for each given download.
    """
    results = []
    for download in downloads:
        if download.is_complete or force:
            for path in download.root_files_paths:
                if path.is_dir():
                    try:
                        shutil.rmtree(str(path))
                    except OSError as error:
                        logger.error(f"Could not delete directory '{path}'")
                        logger.opt(exception=True).trace(error)
                        results.append(False)
                    else:
                        results.append(True)
                else:
                    try:
                        path.unlink()
                    except FileNotFoundError as error:
                        logger.warning(f"File '{path}' did not exist when trying to delete it")
                        logger.opt(exception=True).trace(error)
                    results.append(True)
        else:
            results.append(False)
    return results

resume ¤

resume(downloads: list[Download]) -> list[OperationResult]

Resume (unpause) the given downloads.

Parameters:

  • downloads (list[Download]) –

    The list of downloads to resume.

Returns:

  • list[OperationResult]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def resume(self, downloads: list[Download]) -> list[OperationResult]:
    """Resume (unpause) the given downloads.

    Parameters:
        downloads: The list of downloads to resume.

    Returns:
        Success or failure of the operation for each given download.
    """
    # Note: batch/multicall candidate
    result: list[OperationResult] = []

    for download in downloads:
        try:
            self.client.unpause(download.gid)
        except ClientException as error:
            logger.debug(f"Failed to resume download {download.gid}")
            logger.opt(exception=True).trace(error)
            result.append(error)
        else:
            result.append(True)

    return result

resume_all ¤

resume_all() -> bool

Resume (unpause) all downloads.

Returns:

  • bool

    Success or failure of the operation to resume all downloads.

Source code in src/aria2p/api.py
551
552
553
554
555
556
557
def resume_all(self) -> bool:
    """Resume (unpause) all downloads.

    Returns:
        Success or failure of the operation to resume all downloads.
    """
    return self.client.unpause_all() == "OK"

retry_downloads ¤

retry_downloads(
    downloads: list[Download], clean: bool = False
) -> list[OperationResult]

Resume failed downloads from where they left off with new GIDs.

Parameters:

  • downloads (list[Download]) –

    The list of downloads to remove.

  • clean (bool, default: False ) –

    Whether to remove the aria2 control file as well.

Returns:

  • list[OperationResult]

    Success or failure of the operation for each given download.

Source code in src/aria2p/api.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def retry_downloads(
    self,
    downloads: list[Download],
    clean: bool = False,  # noqa: FBT001,FBT002
) -> list[OperationResult]:
    """Resume failed downloads from where they left off with new GIDs.

    Parameters:
        downloads: The list of downloads to remove.
        clean: Whether to remove the aria2 control file as well.

    Returns:
        Success or failure of the operation for each given download.
    """
    result: list[OperationResult] = []

    for download in downloads:
        if not download.has_failed:
            continue
        try:
            uri = download.files[0].uris[0]["uri"]
        except IndexError:
            continue
        try:
            new_download_gid = self.add_uris([uri], download.options)
        except ClientException as error:
            result.append(error)
        else:
            if not new_download_gid:
                continue

            self.remove([download], clean=clean)
            result.append(True)

    return result

search ¤

search(patterns: list[str]) -> list[Download]

Not implemented.

Search and return Download objects based on multiple patterns.

Parameters:

  • patterns (list[str]) –

    The patterns used to filter the download list.

Raises:

Source code in src/aria2p/api.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def search(self, patterns: list[str]) -> list[Download]:
    """Not implemented.

    Search and return [`Download`][aria2p.downloads.Download] objects based on multiple patterns.

    Parameters:
        patterns: The patterns used to filter the download list.

    Raises:
        NotImplementedError: This method is not implemented yet.
    """
    # gid
    # status
    # totalLength
    # completedLength
    # uploadLength
    # bitfield
    # downloadSpeed
    # uploadSpeed
    # infoHash
    # numSeeders
    # seeder
    # pieceLength
    # numPieces
    # connections
    # errorCode
    # errorMessage
    # followedBy
    # following
    # belongsTo
    # dir
    # files
    # bittorrent
    #        announceList
    #        comment
    #        creationDate
    #        mode
    #        info
    #               name
    # verifiedLength
    # verifyIntegrityPending
    raise NotImplementedError

set_global_options ¤

set_global_options(options: OptionsType) -> bool

Set global options.

Parameters:

  • options (OptionsType) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

Returns:

  • bool

    Success or failure of the operation for changing global options.

Source code in src/aria2p/api.py
620
621
622
623
624
625
626
627
628
629
630
631
632
def set_global_options(self, options: OptionsType) -> bool:
    """Set global options.

    Parameters:
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.

    Returns:
        Success or failure of the operation for changing global options.
    """
    client_options = options.get_struct() if isinstance(options, Options) else options

    return self.client.change_global_option(client_options) == "OK"

set_options ¤

set_options(
    options: OptionsType, downloads: list[Download]
) -> list[bool]

Set options for specific downloads.

Parameters:

  • options (OptionsType) –

    An instance of the Options class or a dictionary containing aria2c options to create the download with.

  • downloads (list[Download]) –

    The list of downloads to set the options for.

Returns:

  • list[bool]

    Success or failure of the operation for changing options for each given download.

Source code in src/aria2p/api.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def set_options(self, options: OptionsType, downloads: list[Download]) -> list[bool]:
    """Set options for specific downloads.

    Parameters:
        options: An instance of the [`Options`][aria2p.options.Options] class or a dictionary
            containing aria2c options to create the download with.
        downloads: The list of downloads to set the options for.

    Returns:
        Success or failure of the operation for changing options for each given download.
    """
    client_options = options.get_struct() if isinstance(options, Options) else options

    # Note: batch/multicall candidate
    results = []
    for download in downloads:
        results.append(self.client.change_option(download.gid, client_options) == "OK")
    return results

split_input_file ¤

split_input_file(
    lines: list[str] | TextIO,
) -> Iterator[list[str]]

Helper to split downloads in an input file.

Parameters:

Yields:

  • list[str]

    list[str]: Blocks of lines.

Source code in src/aria2p/api.py
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
def split_input_file(self, lines: list[str] | TextIO) -> Iterator[list[str]]:
    """Helper to split downloads in an input file.

    Parameters:
         lines: The lines of the input file.

    Yields:
        list[str]: Blocks of lines.
    """
    block: list[str] = []
    for line in lines:
        if line.lstrip().startswith("#"):  # Ignore Comments
            continue
        if not line.strip():  # Ignore empty line
            continue
        if not line.startswith(" ") and block:  # URIs line
            yield block
            block = []
        block.append(line.rstrip("\n"))
    if block:
        yield block

stop_listening ¤

stop_listening() -> None

Stop listening to notifications.

If the listening loop was threaded, this method will wait for the thread to finish. The time it takes for the thread to finish will depend on the timeout given while calling listen_to_notifications.

Source code in src/aria2p/api.py
802
803
804
805
806
807
808
809
810
811
812
def stop_listening(self) -> None:
    """Stop listening to notifications.

    If the listening loop was threaded, this method will wait for the thread to finish.
    The time it takes for the thread to finish will depend on the timeout given while calling
    [`listen_to_notifications`][aria2p.api.API.listen_to_notifications].
    """
    self.client.stop_listening()
    if self.listener:
        self.listener.join()
    self.listener = None

BitTorrent ¤

BitTorrent(struct: dict)

Information retrieved from a torrent file.

Parameters:

  • struct (dict) –

    A dictionary Python object returned by the JSON-RPC client.

Attributes:

Source code in src/aria2p/downloads.py
27
28
29
30
31
32
33
def __init__(self, struct: dict) -> None:
    """Initialize the object.

    Parameters:
        struct: A dictionary Python object returned by the JSON-RPC client.
    """
    self._struct = struct or {}

announce_list property ¤

announce_list: list[list[str]] | None

List of lists of announce URIs.

If the torrent contains announce and no announce-list, announce is converted to the announce-list format.

Returns:

comment property ¤

comment: str | None

Return the comment of the torrent.

comment.utf-8 is used if available.

Returns:

  • str | None

    The torrent's comment.

creation_date property ¤

creation_date: datetime

Return the creation time of the torrent.

The value is an integer since the epoch, measured in seconds.

Returns:

info property ¤

info: dict | None

Struct which contains data from Info dictionary.

It contains the name key: name in info dictionary. name.utf-8 is used if available.

Returns:

  • dict | None

    The torrent's info.

mode property ¤

mode: str | None

File mode of the torrent.

The value is either single or multi.

Returns:

  • str | None

    The file mode.

Client ¤

Client(
    host: str = DEFAULT_HOST,
    port: int = DEFAULT_PORT,
    secret: str = "",
    timeout: float = DEFAULT_TIMEOUT,
)

The JSON-RPC client class.

In this documentation, all the following terms refer to the same entity, the remote aria2c process: remote process, remote server, server, daemon process, background process, remote.

This class implements method to communicate with a daemon aria2c process through the JSON-RPC protocol. Each method offered by the aria2c process is implemented in this class, in snake_case instead of camelCase (example: add_uri instead of addUri).

The class defines a METHODS variable which contains the names of the available methods.

The class is instantiated using an address and port, and optionally a secret token. The token is never passed as a method argument.

The class provides utility methods:

  • call, which performs a JSON-RPC call for a single method;
  • batch_call, which performs a JSON-RPC call for a list of methods;
  • multicall2, which is an equivalent of multicall, but easier to use;
  • post, which is responsible for actually sending a payload to the remote process using a POST request;
  • get_payload, which is used to build payloads;
  • get_params, which is used to build list of parameters.

Parameters:

  • host (str, default: DEFAULT_HOST ) –

    The remote process address.

  • port (int, default: DEFAULT_PORT ) –

    The remote process port.

  • secret (str, default: '' ) –

    The secret token.

  • timeout (float, default: DEFAULT_TIMEOUT ) –

    The timeout to use for requests towards the remote server.

Methods:

Attributes:

  • server (str) –

    Return the full remote process / server address.

  • ws_server (str) –

    Return the full WebSocket remote server address.

Source code in src/aria2p/client.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def __init__(
    self,
    host: str = DEFAULT_HOST,
    port: int = DEFAULT_PORT,
    secret: str = "",
    timeout: float = DEFAULT_TIMEOUT,
) -> None:
    """Initialize the object.

    Parameters:
        host: The remote process address.
        port: The remote process port.
        secret: The secret token.
        timeout: The timeout to use for requests towards the remote server.
    """
    host = host.rstrip("/")

    self.host = host
    self.port = port
    self.secret = secret
    self.timeout = timeout
    self.listening = False

server property ¤

server: str

Return the full remote process / server address.

Returns:

  • str

    The server address.

ws_server property ¤

ws_server: str

Return the full WebSocket remote server address.

Returns:

  • str

    The WebSocket server address.

add_metalink(
    metalink: str,
    options: dict | None = None,
    position: int | None = None,
) -> list[str]

Add a Metalink download.

This method adds a Metalink download by uploading a ".metalink" file and returns an array of GIDs of newly registered downloads.

Original signature:

aria2.addMetalink([secret], metalink[, options[, position]])

If --rpc-save-upload-metadata is true, the uploaded data is saved as a file named hex string of SHA-1 hash of data plus ".metalink" in the directory specified by --dir option. E.g. a file name might be 0a3893293e27ac0490424c06de4d09242215f0a6.metalink. If a file with the same name already exists, it is overwritten! If the file cannot be saved successfully or --rpc-save-upload-metadata is false, the downloads added by this method are not saved by --save-session.

Parameters:

  • metalink (str) –

    metalink is a base64-encoded string which contains the contents of the ".metalink" file.

  • options (dict | None, default: None ) –

    options is a struct and its members are pairs of option name and value. See Options for more details.

  • position (int | None, default: None ) –

    If position is given, it must be an integer starting from 0. The new download will be inserted at position in the waiting queue. If position is omitted or position is larger than the current size of the queue, the new download is appended to the end of the queue.

Returns:

  • list[str]

    The GID of the created download.

Examples:

Original JSON-RPC Example

The following examples add local file file.meta4.

>>> import urllib2, json, base64
>>> metalink = base64.b64encode(open("file.meta4").read())
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.addMetalink",
...         "params": [metalink],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> c.read()
'{"id":"qwer","jsonrpc":"2.0","result":["0000000000000001"]}'
Source code in src/aria2p/client.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
def add_metalink(
    self,
    metalink: str,
    options: dict | None = None,
    position: int | None = None,
) -> list[str]:
    """Add a Metalink download.

    This method adds a Metalink download by uploading a ".metalink" file
    and returns an array of GIDs of newly registered downloads.

    Original signature:

        aria2.addMetalink([secret], metalink[, options[, position]])

    If [`--rpc-save-upload-metadata`][aria2p.options.Options.rpc_save_upload_metadata] is true,
    the uploaded data is saved as a file named hex string of SHA-1 hash of data plus ".metalink"
    in the directory specified by [`--dir`][aria2p.options.Options.dir] option.
    E.g. a file name might be 0a3893293e27ac0490424c06de4d09242215f0a6.metalink.
    If a file with the same name already exists, it is overwritten!
    If the file cannot be saved successfully
    or [`--rpc-save-upload-metadata`][aria2p.options.Options.rpc_save_upload_metadata] is false,
    the downloads added by this method are not saved by [`--save-session`][aria2p.options.Options.save_session].

    Parameters:
        metalink: `metalink` is a base64-encoded string which contains the contents of the ".metalink" file.
        options: `options` is a struct and its members are pairs of option name and value.
            See [Options][aria2p.options.Options] for more details.
        position: If `position` is given, it must be an integer starting from 0.
            The new download will be inserted at `position` in the waiting queue.
            If `position` is omitted or `position` is larger than the current size of the queue,
            the new download is appended to the end of the queue.

    Returns:
        The GID of the created download.

    Examples:
        **Original JSON-RPC Example**

        The following examples add local file file.meta4.

        >>> import urllib2, json, base64
        >>> metalink = base64.b64encode(open("file.meta4").read())
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.addMetalink",
        ...         "params": [metalink],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> c.read()
        '{"id":"qwer","jsonrpc":"2.0","result":["0000000000000001"]}'
    """
    return self.call(self.ADD_METALINK, [metalink, options, position])  # type: ignore

add_torrent ¤

add_torrent(
    torrent: str,
    uris: list[str],
    options: dict | None = None,
    position: int | None = None,
) -> str

Add a BitTorrent download.

This method adds a BitTorrent download by uploading a ".torrent" file and returns the GID of the newly registered download.

Original signature:

aria2.addTorrent([secret], torrent[, uris[, options[, position]]])

If you want to add a BitTorrent Magnet URI, use the add_uri() method instead.

If --rpc-save-upload-metadata is true, the uploaded data is saved as a file named as the hex string of SHA-1 hash of data plus ".torrent" in the directory specified by --dir option. E.g. a file name might be 0a3893293e27ac0490424c06de4d09242215f0a6.torrent. If a file with the same name already exists, it is overwritten! If the file cannot be saved successfully or --rpc-save-upload-metadata is false, the downloads added by this method are not saved by --save-session.

Parameters:

  • torrent (str) –

    torrent must be a base64-encoded string containing the contents of the ".torrent" file.

  • uris (list[str]) –

    uris is an array of URIs (string). uris is used for Web-seeding. For single file torrents, the URI can be a complete URI pointing to the resource; if URI ends with /, name in torrent file is added. For multi-file torrents, name and path in torrent are added to form a URI for each file.

  • options (dict | None, default: None ) –

    options is a struct and its members are pairs of option name and value. See Options for more details.

  • position (int | None, default: None ) –

    If position is given, it must be an integer starting from 0. The new download will be inserted at position in the waiting queue. If position is omitted or position is larger than the current size of the queue, the new download is appended to the end of the queue.

Returns:

  • str

    The GID of the created download.

Examples:

Original JSON-RPC Example

The following examples add local file file.torrent.

>>> import urllib2, json, base64
>>> torrent = base64.b64encode(open("file.torrent").read())
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "asdf",
...         "method": "aria2.addTorrent",
...         "params": [torrent],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> c.read()
'{"id":"asdf","jsonrpc":"2.0","result":"0000000000000001"}'
Source code in src/aria2p/client.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def add_torrent(
    self,
    torrent: str,
    uris: list[str],
    options: dict | None = None,
    position: int | None = None,
) -> str:
    """Add a BitTorrent download.

    This method adds a BitTorrent download by uploading a ".torrent" file and returns the GID of the
    newly registered download.

    Original signature:

        aria2.addTorrent([secret], torrent[, uris[, options[, position]]])

    If you want to add a BitTorrent Magnet URI, use the [`add_uri()`][aria2p.client.Client.add_uri] method instead.

    If [`--rpc-save-upload-metadata`][aria2p.options.Options.rpc_save_upload_metadata] is true,
    the uploaded data is saved as a file named as the hex string of SHA-1 hash of data plus ".torrent"
    in the directory specified by [`--dir`][aria2p.options.Options.dir] option.
    E.g. a file name might be 0a3893293e27ac0490424c06de4d09242215f0a6.torrent.
    If a file with the same name already exists, it is overwritten!
    If the file cannot be saved successfully
    or [`--rpc-save-upload-metadata`][aria2p.options.Options.rpc_save_upload_metadata] is false,
    the downloads added by this method are not saved by [`--save-session`][aria2p.options.Options.save_session].

    Parameters:
        torrent: `torrent` must be a base64-encoded string containing the contents of the ".torrent" file.
        uris: `uris` is an array of URIs (string). `uris` is used for Web-seeding.
            For single file torrents, the URI can be a complete URI pointing to the resource; if URI ends with /,
            name in torrent file is added. For multi-file torrents, name and path in torrent are added to form a URI
            for each file.
        options: `options` is a struct and its members are pairs of option name and value.
            See [Options][aria2p.options.Options] for more details.
        position: If `position` is given, it must be an integer starting from 0.
            The new download will be inserted at `position` in the waiting queue.
            If `position` is omitted or `position` is larger than the current size of the queue,
            the new download is appended to the end of the queue.

    Returns:
        The GID of the created download.

    Examples:
        **Original JSON-RPC Example**

        The following examples add local file file.torrent.

        >>> import urllib2, json, base64
        >>> torrent = base64.b64encode(open("file.torrent").read())
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "asdf",
        ...         "method": "aria2.addTorrent",
        ...         "params": [torrent],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> c.read()
        '{"id":"asdf","jsonrpc":"2.0","result":"0000000000000001"}'
    """
    return self.call(self.ADD_TORRENT, [torrent, uris, options, position])  # type: ignore

add_uri ¤

add_uri(
    uris: list[str],
    options: dict | None = None,
    position: int | None = None,
) -> str

Add a new download.

This method adds a new download and returns the GID of the newly registered download.

Original signature:

aria2.addUri([secret], uris[, options[, position]])

Parameters:

  • uris (list[str]) –

    uris is an array of HTTP/FTP/SFTP/BitTorrent URIs (strings) pointing to the same resource. If you mix URIs pointing to different resources, then the download may fail or be corrupted without aria2 complaining. When adding BitTorrent Magnet URIs, uris must have only one element and it should be BitTorrent Magnet URI.

  • options (dict | None, default: None ) –

    options is a struct and its members are pairs of option name and value. See Options for more details.

  • position (int | None, default: None ) –

    If position is given, it must be an integer starting from 0. The new download will be inserted at position in the waiting queue. If position is omitted or position is larger than the current size of the queue, the new download is appended to the end of the queue.

Returns:

  • str

    The GID of the created download.

Examples:

Original JSON-RPC Example

The following example adds http://example.org/file:

>>> import urllib2, json
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.addUri",
...         "params": [["http://example.org/file"]],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> c.read()
'{"id":"qwer","jsonrpc":"2.0","result":"0000000000000001"}'
Source code in src/aria2p/client.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def add_uri(
    self,
    uris: list[str],
    options: dict | None = None,
    position: int | None = None,
) -> str:
    """Add a new download.

    This method adds a new download and returns the GID of the newly registered download.

    Original signature:

        aria2.addUri([secret], uris[, options[, position]])

    Parameters:
        uris: `uris` is an array of HTTP/FTP/SFTP/BitTorrent URIs (strings) pointing to the same resource.
            If you mix URIs pointing to different resources,
            then the download may fail or be corrupted without aria2 complaining.
            When adding BitTorrent Magnet URIs,
            uris must have only one element and it should be BitTorrent Magnet URI.
        options: `options` is a struct and its members are pairs of option name and value.
            See [Options][aria2p.options.Options] for more details.
        position: If `position` is given, it must be an integer starting from 0.
            The new download will be inserted at `position` in the waiting queue.
            If `position` is omitted or `position` is larger than the current size of the queue,
            the new download is appended to the end of the queue.

    Returns:
        The GID of the created download.

    Examples:
        **Original JSON-RPC Example**

        The following example adds http://example.org/file:

        >>> import urllib2, json
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.addUri",
        ...         "params": [["http://example.org/file"]],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> c.read()
        '{"id":"qwer","jsonrpc":"2.0","result":"0000000000000001"}'
    """
    return self.call(self.ADD_URI, params=[uris, options, position])  # type: ignore

batch_call ¤

batch_call(
    calls: CallsType, insert_secret: bool = True
) -> list[CallReturnType]

Call multiple methods in one request.

A batch call is simply a list of full payloads, sent at once to the remote process. The differences with a multicall are:

  • multicall is a special "system" method, whereas batch_call is simply the concatenation of several methods
  • multicall payloads define the "jsonrpc" and "id" keys only once, whereas these keys are repeated in each part of the batch_call payload
  • as a result of the previous line, you must pass different IDs to the batch_call methods, whereas the ID in multicall is optional

Parameters:

  • calls (CallsType) –

    A list of tuples composed of method name, parameters and ID.

  • insert_secret (bool, default: True ) –

    Whether to insert the secret token in the parameters or not.

Returns:

  • list[CallReturnType]

    The results for each call in the batch.

Source code in src/aria2p/client.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def batch_call(
    self,
    calls: CallsType,
    insert_secret: bool = True,  # noqa: FBT001,FBT002
) -> list[CallReturnType]:
    """Call multiple methods in one request.

    A batch call is simply a list of full payloads, sent at once to the remote process. The differences with a
    multicall are:

    - multicall is a special "system" method, whereas batch_call is simply the concatenation of several methods
    - multicall payloads define the "jsonrpc" and "id" keys only once, whereas these keys are repeated in
      each part of the batch_call payload
    - as a result of the previous line, you must pass different IDs to the batch_call methods, whereas the
      ID in multicall is optional

    Parameters:
        calls: A list of tuples composed of method name, parameters and ID.
        insert_secret: Whether to insert the secret token in the parameters or not.

    Returns:
        The results for each call in the batch.
    """
    payloads = []

    for method, params, msg_id in calls:
        params = self.get_params(*params)  # noqa: PLW2901
        if insert_secret and self.secret and method.startswith("aria2."):
            params.insert(0, f"token:{self.secret}")
        payloads.append(self.get_payload(method, params, msg_id, as_json=False))

    payload: str = json.dumps(payloads)
    responses = self.post(payload)
    return [self.res_or_raise(resp) for resp in responses]

call ¤

call(
    method: str,
    params: list[Any] | None = None,
    msg_id: int | str | None = None,
    insert_secret: bool = True,
) -> CallReturnType

Call a single JSON-RPC method.

Parameters:

  • method (str) –

    The method name. You can use the constant defined in Client.

  • params (list[Any] | None, default: None ) –

    A list of parameters.

  • msg_id (int | str | None, default: None ) –

    The ID of the call, sent back with the server's answer.

  • insert_secret (bool, default: True ) –

    Whether to insert the secret token in the parameters or not.

Returns:

  • CallReturnType

    The answer from the server, as a Python object.

Source code in src/aria2p/client.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def call(
    self,
    method: str,
    params: list[Any] | None = None,
    msg_id: int | str | None = None,
    insert_secret: bool = True,  # noqa: FBT001,FBT002
) -> CallReturnType:
    """Call a single JSON-RPC method.

    Parameters:
        method: The method name. You can use the constant defined in [`Client`][aria2p.client.Client].
        params: A list of parameters.
        msg_id: The ID of the call, sent back with the server's answer.
        insert_secret: Whether to insert the secret token in the parameters or not.

    Returns:
        The answer from the server, as a Python object.
    """
    params = self.get_params(*(params or []))

    if insert_secret and self.secret:
        if method.startswith("aria2."):
            params.insert(0, f"token:{self.secret}")
        elif method == self.MULTICALL:
            for param in params[0]:
                param["params"].insert(0, f"token:{self.secret}")

    payload: str = self.get_payload(method, params, msg_id=msg_id)  # type: ignore
    return self.res_or_raise(self.post(payload))

change_global_option ¤

change_global_option(options: dict) -> str

Change the global options dynamically.

Original signature:

aria2.changeGlobalOption([secret], options)

Parameters:

  • options (dict) –

    The following options are available:

    • bt-max-open-files
    • download-result
    • keep-unfinished-download-result
    • log
    • log-level
    • max-concurrent-downloads
    • max-download-result
    • max-overall-download-limit
    • max-overall-upload-limit
    • optimize-concurrent-downloads
    • save-cookies
    • save-session
    • server-stat-of

    In addition, options listed in the Input File subsection are available, except for following options: checksum, index-out, out, pause and select-file.

    With the log option, you can dynamically start logging or change log file. To stop logging, specify an empty string ("") as the parameter value. Note that log file is always opened in append mode.

Returns:

  • str

    "OK" for success.

Source code in src/aria2p/client.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
def change_global_option(self, options: dict) -> str:
    """Change the global options dynamically.

    Original signature:

        aria2.changeGlobalOption([secret], options)

    Parameters:
        options: The following options are available:

            - `bt-max-open-files`
            - `download-result`
            - `keep-unfinished-download-result`
            - `log`
            - `log-level`
            - `max-concurrent-downloads`
            - `max-download-result`
            - `max-overall-download-limit`
            - `max-overall-upload-limit`
            - `optimize-concurrent-downloads`
            - `save-cookies`
            - `save-session`
            - `server-stat-of`

            In addition, options listed in the Input File subsection are available, except for following options:
            `checksum`, `index-out`, `out`, `pause` and `select-file`.

            With the log option, you can dynamically start logging or change log file. To stop logging, specify an
            empty string ("") as the parameter value. Note that log file is always opened in append mode.

    Returns:
        `"OK"` for success.
    """
    return self.call(self.CHANGE_GLOBAL_OPTION, [options])  # type: ignore

change_option ¤

change_option(gid: str, options: dict) -> str

Change a download options dynamically.

Original signature:

aria2.changeOption([secret], gid, options)

Parameters:

  • gid (str) –

    The download to change options of.

  • options (dict) –

    The options listed in Input File subsection are available, except for following options:

    • dry-run
    • metalink-base-uri
    • parameterized-uri
    • pause
    • piece-length
    • rpc-save-upload-metadata

    Except for the following options, changing the other options of active download makes it restart (restart itself is managed by aria2, and no user intervention is required):

    • bt-max-peers
    • bt-request-peer-speed-limit
    • bt-remove-unselected-file
    • force-save
    • max-download-limit
    • max-upload-limit

Returns:

  • str

    "OK" for success.

Examples:

Original JSON-RPC Example

The following examples set the max-download-limit option to 20K for the download GID#0000000000000001.

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.changeOption",
...         "params": ["0000000000000001", {"max-download-limit": "10K"}],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'OK'}
Source code in src/aria2p/client.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
def change_option(self, gid: str, options: dict) -> str:
    """Change a download options dynamically.

    Original signature:

        aria2.changeOption([secret], gid, options)

    Parameters:
        gid: The download to change options of.
        options: The options listed in Input File subsection are available, except for following options:

            - `dry-run`
            - `metalink-base-uri`
            - `parameterized-uri`
            - `pause`
            - `piece-length`
            - `rpc-save-upload-metadata`

            Except for the following options, changing the other options of active download makes it restart (restart
            itself is managed by aria2, and no user intervention is required):

            - `bt-max-peers`
            - `bt-request-peer-speed-limit`
            - `bt-remove-unselected-file`
            - `force-save`
            - `max-download-limit`
            - `max-upload-limit`

    Returns:
        `"OK"` for success.

    Examples:
        **Original JSON-RPC Example**

        The following examples set the max-download-limit option to 20K for the download GID#0000000000000001.

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.changeOption",
        ...         "params": ["0000000000000001", {"max-download-limit": "10K"}],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'OK'}
    """
    return self.call(self.CHANGE_OPTION, [gid, options])  # type: ignore

change_position ¤

change_position(gid: str, pos: int, how: str) -> int

Change position of a download.

This method changes the position of the download denoted by gid in the queue.

Original signature:

aria2.changePosition([secret], gid, pos, how)

Parameters:

  • gid (str) –

    The download to change the position of.

  • pos (int) –

    An integer.

  • how (str) –

    POS_SET, POS_CUR or POS_END.

    • If how is POS_SET, it moves the download to a position relative to the beginning of the queue.
    • If how is POS_CUR, it moves the download to a position relative to the current position.
    • If how is POS_END, it moves the download to a position relative to the end of the queue.
    • If the destination position is less than 0 or beyond the end of the queue, it moves the download to the beginning or the end of the queue respectively.

    For example, if GID#0000000000000001 is currently in position 3, change_position('0000000000000001', -1, 'POS_CUR') will change its position to 2. Additionally change_position('0000000000000001', 0, 'POS_SET') will change its position to 0 (the beginning of the queue).

Returns:

  • int

    An integer denoting the resulting position.

Examples:

Original JSON-RPC Example

The following examples move the download GID#0000000000000001 to the front of the queue.

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.changePosition",
...         "params": ["0000000000000001", 0, "POS_SET"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': 0}
Source code in src/aria2p/client.py
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
def change_position(self, gid: str, pos: int, how: str) -> int:
    """Change position of a download.

    This method changes the position of the download denoted by `gid` in the queue.

    Original signature:

        aria2.changePosition([secret], gid, pos, how)

    Parameters:
        gid: The download to change the position of.
        pos: An integer.
        how: `POS_SET`, `POS_CUR` or `POS_END`.

            - If `how` is `POS_SET`, it moves the download to a position relative to the beginning of the queue.
            - If `how` is `POS_CUR`, it moves the download to a position relative to the current position.
            - If `how` is `POS_END`, it moves the download to a position relative to the end of the queue.
            - If the destination position is less than 0 or beyond the end of the queue,
              it moves the download to the beginning or the end of the queue respectively.

            For example, if GID#0000000000000001 is currently in position 3,
            `change_position('0000000000000001', -1, 'POS_CUR')` will change its position to 2. Additionally
            `change_position('0000000000000001', 0, 'POS_SET')` will change its position to 0 (the beginning of the queue).

    Returns:
        An integer denoting the resulting position.

    Examples:
        **Original JSON-RPC Example**

        The following examples move the download GID#0000000000000001 to the front of the queue.

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.changePosition",
        ...         "params": ["0000000000000001", 0, "POS_SET"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer', u'jsonrpc': u'2.0', u'result': 0}
    """
    return self.call(self.CHANGE_POSITION, [gid, pos, how])  # type: ignore

change_uri ¤

change_uri(
    gid: str,
    file_index: int,
    del_uris: list[str],
    add_uris: list[str],
    position: int | None = None,
) -> list[int]

Remove the URIs in del_uris from and appends the URIs in add_uris to download denoted by gid.

Original signature:

aria2.changeUri([secret], gid, fileIndex, delUris, addUris[, position])

Parameters:

  • gid (str) –

    The download to change URIs of.

  • file_index (int) –

    Used to select which file to remove/attach given URIs. file_index is 1-based.

  • del_uris (list[str]) –

    List of strings.

  • add_uris (list[str]) –

    List of strings.

  • position (int | None, default: None ) –

    Used to specify where URIs are inserted in the existing waiting URI list. position is 0-based. When position is omitted, URIs are appended to the back of the list. This method first executes the removal and then the addition. position is the position after URIs are removed, not the position when this method is called.

A download can contain multiple files and URIs are attached to each file. When removing an URI, if the same URIs exist in download, only one of them is removed for each URI in del_uris. In other words, if there are three URIs http://example.org/aria2 and you want remove them all, you have to specify (at least) 3 http://example.org/aria2 in del_uris.

Returns:

  • list[int]

    A list which contains two integers.

  • list[int]

    The first integer is the number of URIs deleted.

  • list[int]

    The second integer is the number of URIs added.

Examples:

Original JSON-RPC Example

The following examples add the URI http://example.org/file to the file whose index is 1 and belongs to the download GID#0000000000000001.

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
...                       'method':'aria2.changeUri',
...                       'params':['0000000000000001', 1, [],
                                   ['http://example.org/file']]})
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': [0, 1]}
Source code in src/aria2p/client.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def change_uri(
    self,
    gid: str,
    file_index: int,
    del_uris: list[str],
    add_uris: list[str],
    position: int | None = None,
) -> list[int]:
    """Remove the URIs in `del_uris` from and appends the URIs in `add_uris` to download denoted by gid.

    Original signature:

        aria2.changeUri([secret], gid, fileIndex, delUris, addUris[, position])

    Parameters:
        gid: The download to change URIs of.
        file_index: Used to select which file to remove/attach given URIs. `file_index` is 1-based.
        del_uris: List of strings.
        add_uris: List of strings.
        position: Used to specify where URIs are inserted in the existing waiting URI list. `position` is 0-based.
            When position is omitted, URIs are appended to the back of the list.
            This method first executes the removal and then the addition.
            `position` is the position after URIs are removed, not the position when this
            method is called.

    A download can contain multiple files and URIs are attached to each file.
    When removing an URI, if the same URIs exist in download, only one of them is removed for
    each URI in `del_uris`. In other words, if there are three URIs http://example.org/aria2 and you want
    remove them all, you have to specify (at least) 3 http://example.org/aria2 in `del_uris`.

    Returns:
        A list which contains two integers.
        The first integer is the number of URIs deleted.
        The second integer is the number of URIs added.

    Examples:
        **Original JSON-RPC Example**

        The following examples add the URI http://example.org/file to the file whose index is 1 and belongs to the
        download GID#0000000000000001.

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
        ...                       'method':'aria2.changeUri',
        ...                       'params':['0000000000000001', 1, [],
                                           ['http://example.org/file']]})
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer', u'jsonrpc': u'2.0', u'result': [0, 1]}
    """
    return self.call(self.CHANGE_URI, [gid, file_index, del_uris, add_uris, position])  # type: ignore

force_pause ¤

force_pause(gid: str) -> str

Force pause a download.

This method pauses the download denoted by gid. This method behaves just like pause() except that this method pauses downloads without performing any actions which take time, such as contacting BitTorrent trackers to unregister the download first.

Original signature:

aria2.forcePause([secret], gid)

Parameters:

  • gid (str) –

    The download to force pause.

Returns:

  • str

    The GID of the paused download.

Source code in src/aria2p/client.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
def force_pause(self, gid: str) -> str:
    """Force pause a download.

    This method pauses the download denoted by gid.
    This method behaves just like [`pause()`][aria2p.client.Client.pause] except that
    this method pauses downloads without performing any actions which take time,
    such as contacting BitTorrent trackers to unregister the download first.

    Original signature:

        aria2.forcePause([secret], gid)

    Parameters:
        gid: The download to force pause.

    Returns:
        The GID of the paused download.
    """
    return self.call(self.FORCE_PAUSE, [gid])  # type: ignore

force_pause_all ¤

force_pause_all() -> str

Force pause all active/waiting downloads.

This method is equal to calling force_pause() for every active/waiting download.

Original signature:

aria2.forcePauseAll([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
710
711
712
713
714
715
716
717
718
719
720
721
722
def force_pause_all(self) -> str:
    """Force pause all active/waiting downloads.

    This method is equal to calling [`force_pause()`][aria2p.client.Client.force_pause] for every active/waiting download.

    Original signature:

        aria2.forcePauseAll([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.FORCE_PAUSE_ALL)  # type: ignore

force_remove ¤

force_remove(gid: str) -> str

Force remove a download.

This method removes the download denoted by gid. This method behaves just like remove() except that this method removes the download without performing any actions which take time, such as contacting BitTorrent trackers to unregister the download first.

Original signature:

aria2.forceRemove([secret], gid)

Parameters:

  • gid (str) –

    The download to force remove.

Returns:

  • str

    The GID of the removed download.

Source code in src/aria2p/client.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def force_remove(self, gid: str) -> str:
    """Force remove a download.

    This method removes the download denoted by gid.
    This method behaves just like [`remove()`][aria2p.client.Client.remove] except
    that this method removes the download without performing any actions which take time, such as contacting
    BitTorrent trackers to unregister the download first.

    Original signature:

        aria2.forceRemove([secret], gid)

    Parameters:
        gid: The download to force remove.

    Returns:
        The GID of the removed download.
    """
    return self.call(self.FORCE_REMOVE, [gid])  # type: ignore

force_shutdown ¤

force_shutdown() -> str

Force shutdown aria2.

This method shuts down aria2. This method behaves like shutdown() without performing any actions which take time, such as contacting BitTorrent trackers to unregister downloads first.

Original signature:

aria2.forceShutdown([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
def force_shutdown(self) -> str:
    """Force shutdown aria2.

    This method shuts down aria2. This method behaves like [`shutdown()`][aria2p.client.Client.shutdown] without performing any
    actions which take time, such as contacting BitTorrent trackers to unregister downloads first.

    Original signature:

        aria2.forceShutdown([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.FORCE_SHUTDOWN)  # type: ignore

get_files ¤

get_files(gid: str) -> dict

Return file list of a download.

This method returns the file list of the download denoted by gid (string). The response is an array of structs which contain following keys. Values are strings.

  • index: Index of the file, starting at 1, in the same order as files appear in the multi-file torrent.
  • path: File path.
  • length: File size in bytes.
  • completedLength: Completed length of this file in bytes. Please note that it is possible that sum of completedLength is less than the completedLength returned by the tell_status() method. This is because completedLength in get_files() only includes completed pieces. On the other hand, completedLength in tell_status() also includes partially completed pieces.
  • selected: true if this file is selected by --select-file option. If --select-file is not specified or this is single-file torrent or not a torrent download at all, this value is always true. Otherwise false.
  • uris Returns a list of URIs for this file. The element type is the same struct used in the get_uris() method.

Original signature:

aria2.getFiles([secret], gid)

Parameters:

  • gid (str) –

    The download to list files of.

Returns:

  • dict

    The file list of a download.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.getFiles",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [{u'index': u'1',
              u'length': u'34896138',
              u'completedLength': u'34896138',
              u'path': u'/downloads/file',
              u'selected': u'true',
              u'uris': [{u'status': u'used',
                         u'uri': u'http://example.org/file'}]}]}
Source code in src/aria2p/client.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
def get_files(self, gid: str) -> dict:
    """Return file list of a download.

    This method returns the file list of the download denoted by gid (string). The response is an array of
    structs which contain following keys. Values are strings.

    - `index`: Index of the file, starting at 1, in the same order as files appear in the multi-file torrent.
    - `path`: File path.
    - `length`: File size in bytes.
    - `completedLength`: Completed length of this file in bytes.
      Please note that it is possible that sum of `completedLength`
      is less than the `completedLength` returned by the [`tell_status()`][aria2p.client.Client.tell_status] method.
      This is because `completedLength` in [`get_files()`][aria2p.client.Client.get_files] only includes completed pieces.
      On the other hand, `completedLength` in [`tell_status()`][aria2p.client.Client.tell_status]
      also includes partially completed pieces.
    - `selected`: true if this file is selected by [`--select-file`][aria2p.options.Options.select_file] option.
      If [`--select-file`][aria2p.options.Options.select_file] is not specified
      or this is single-file torrent or not a torrent download at all, this value is always true. Otherwise false.
    - `uris` Returns a list of URIs for this file.
      The element type is the same struct used in the [`get_uris()`][aria2p.client.Client.get_uris] method.

    Original signature:

        aria2.getFiles([secret], gid)

    Parameters:
        gid: The download to list files of.

    Returns:
        The file list of a download.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.getFiles",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [{u'index': u'1',
                      u'length': u'34896138',
                      u'completedLength': u'34896138',
                      u'path': u'/downloads/file',
                      u'selected': u'true',
                      u'uris': [{u'status': u'used',
                                 u'uri': u'http://example.org/file'}]}]}
    """
    return self.call(self.GET_FILES, [gid])  # type: ignore

get_global_option ¤

get_global_option() -> dict

Return the global options.

Note that this method does not return options which have no default value and have not been set on the command-line, in configuration files or RPC methods. Because global options are used as a template for the options of newly added downloads, the response contains keys returned by the get_option() method.

Original signature:

aria2.getGlobalOption([secret])

Returns:

  • dict

    The global options. The response is a struct. Its keys are the names of options.

  • dict

    Values are strings.

Source code in src/aria2p/client.py
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
def get_global_option(self) -> dict:
    """Return the global options.

    Note that this method does not return options which have no default value and have not
    been set on the command-line, in configuration files or RPC methods. Because global options are used as a
    template for the options of newly added downloads, the response contains keys returned by the
    [`get_option()`][aria2p.client.Client.get_option] method.

    Original signature:

        aria2.getGlobalOption([secret])

    Returns:
        The global options. The response is a struct. Its keys are the names of options.
        Values are strings.
    """
    return self.call(self.GET_GLOBAL_OPTION)  # type: ignore

get_global_stat ¤

get_global_stat() -> dict

Return global statistics such as the overall download and upload speeds.

Original signature:

aria2.getGlobalStat([secret])

Returns:

  • dict

    A struct that contains the following keys (values are strings):

  • dict
    • downloadSpeed: Overall download speed (byte/sec).
  • dict
    • uploadSpeed: Overall upload speed(byte/sec).
  • dict
    • numActive: The number of active downloads.
  • dict
    • numWaiting: The number of waiting downloads.
  • dict
    • numStopped: The number of stopped downloads in the current session. This value is capped by the --max-download-result option.
  • dict
    • numStoppedTotal: The number of stopped downloads in the current session and not capped by the --max-download-result option.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getGlobalStat"}
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'downloadSpeed': u'21846',
             u'numActive': u'2',
             u'numStopped': u'0',
             u'numWaiting': u'0',
             u'uploadSpeed': u'0'}}
Source code in src/aria2p/client.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
def get_global_stat(self) -> dict:
    """Return global statistics such as the overall download and upload speeds.

    Original signature:

        aria2.getGlobalStat([secret])

    Returns:
        A struct that contains the following keys (values are strings):

        - `downloadSpeed`: Overall download speed (byte/sec).
        - `uploadSpeed`: Overall upload speed(byte/sec).
        - `numActive`: The number of active downloads.
        - `numWaiting`: The number of waiting downloads.
        - `numStopped`: The number of stopped downloads in the current session. This value is capped by the
            [`--max-download-result`][aria2p.options.Options.max_download_result] option.
        - `numStoppedTotal`: The number of stopped downloads in the current session and not capped by the
            [`--max-download-result`][aria2p.options.Options.max_download_result] option.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getGlobalStat"}
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'downloadSpeed': u'21846',
                     u'numActive': u'2',
                     u'numStopped': u'0',
                     u'numWaiting': u'0',
                     u'uploadSpeed': u'0'}}
    """
    return self.call(self.GET_GLOBAL_STAT)  # type: ignore

get_option ¤

get_option(gid: str) -> dict

Return options of a download.

Original signature:

aria2.getOption([secret], gid)

Parameters:

  • gid (str) –

    The download to get the options of.

Returns:

  • dict

    A struct where keys are the names of options. The values are strings.

  • dict

    Note that this method does not return options which have

  • dict

    no default value and have not been set on the command-line, in configuration files or RPC methods.

Examples:

Original JSON-RPC Example

The following examples get options of the download GID#0000000000000001.

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.getOption",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'allow-overwrite': u'false',
             u'allow-piece-length-change': u'false',
             u'always-resume': u'true',
             u'async-dns': u'true',
 ...
Source code in src/aria2p/client.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
def get_option(self, gid: str) -> dict:
    """Return options of a download.

    Original signature:

        aria2.getOption([secret], gid)

    Parameters:
        gid: The download to get the options of.

    Returns:
        A struct where keys are the names of options. The values are strings.
        Note that this method does not return options which have
        no default value and have not been set on the command-line, in configuration files or RPC methods.

    Examples:
        **Original JSON-RPC Example**

        The following examples get options of the download GID#0000000000000001.

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.getOption",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'allow-overwrite': u'false',
                     u'allow-piece-length-change': u'false',
                     u'always-resume': u'true',
                     u'async-dns': u'true',
         ...
    """
    return self.call(self.GET_OPTION, [gid])  # type: ignore

get_params staticmethod ¤

get_params(*args: Any) -> list

Build the list of parameters.

This method simply removes the None values from the given arguments.

Parameters:

  • *args (Any, default: () ) –

    List of parameters.

Returns:

  • list

    A new list, with None values filtered out.

Source code in src/aria2p/client.py
413
414
415
416
417
418
419
420
421
422
423
424
425
@staticmethod
def get_params(*args: Any) -> list:
    """Build the list of parameters.

    This method simply removes the `None` values from the given arguments.

    Parameters:
        *args: List of parameters.

    Returns:
        A new list, with `None` values filtered out.
    """
    return [_ for _ in args if _ is not None]

get_payload staticmethod ¤

get_payload(
    method: str,
    params: list[Any] | None = None,
    msg_id: int | str | None = None,
    as_json: bool = True,
) -> str | dict

Build a payload.

Parameters:

  • method (str) –

    The method name. You can use the constant defined in Client.

  • params (list[Any] | None, default: None ) –

    The list of parameters.

  • msg_id (int | str | None, default: None ) –

    The ID of the call, sent back with the server's answer.

  • as_json (bool, default: True ) –

    Whether to return the payload as a JSON-string or Python dictionary.

Returns:

  • str | dict

    The payload as a JSON string or as Python dictionary.

Source code in src/aria2p/client.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
@staticmethod
def get_payload(
    method: str,
    params: list[Any] | None = None,
    msg_id: int | str | None = None,
    as_json: bool = True,  # noqa: FBT001,FBT002
) -> str | dict:
    """Build a payload.

    Parameters:
        method: The method name. You can use the constant defined in [`Client`][aria2p.client.Client].
        params: The list of parameters.
        msg_id: The ID of the call, sent back with the server's answer.
        as_json: Whether to return the payload as a JSON-string or Python dictionary.

    Returns:
        The payload as a JSON string or as Python dictionary.
    """
    payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}

    if msg_id is None:
        payload["id"] = DEFAULT_ID
    else:
        payload["id"] = msg_id

    if params:
        payload["params"] = params

    return json.dumps(payload) if as_json else payload

get_peers ¤

get_peers(gid: str) -> dict

Return peers list of a download.

This method returns the list of peers of the download denoted by gid (string). This method is for BitTorrent only. The response is an array of structs and contains the following keys. Values are strings.

  • peerId: Percent-encoded peer ID.
  • ip: IP address of the peer.
  • port: Port number of the peer.
  • bitfield: Hexadecimal representation of the download progress of the peer. The highest bit corresponds to the piece at index 0. Set bits indicate the piece is available and unset bits indicate the piece is missing. Any spare bits at the end are set to zero.
  • amChoking: true if aria2 is choking the peer. Otherwise false.
  • peerChoking: true if the peer is choking aria2. Otherwise false.
  • downloadSpeed: Download speed (byte/sec) that this client obtains from the peer.
  • uploadSpeed: Upload speed(byte/sec) that this client uploads to the peer.
  • seeder: true if this peer is a seeder. Otherwise false.

Original signature:

aria2.getPeers([secret], gid)

Parameters:

  • gid (str) –

    The download to get peers from.

Returns:

  • dict

    The peers connected to a download.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.getPeers",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [{u'amChoking': u'true',
              u'bitfield': u'ffffffffffffffffffffffffffffffffffffffff',
              u'downloadSpeed': u'10602',
              u'ip': u'10.0.0.9',
              u'peerChoking': u'false',
              u'peerId': u'aria2%2F1%2E10%2E5%2D%87%2A%EDz%2F%F7%E6',
              u'port': u'6881',
              u'seeder': u'true',
              u'uploadSpeed': u'0'},
             {u'amChoking': u'false',
              u'bitfield': u'ffffeff0fffffffbfffffff9fffffcfff7f4ffff',
              u'downloadSpeed': u'8654',
              u'ip': u'10.0.0.30',
              u'peerChoking': u'false',
              u'peerId': u'bittorrent client758',
              u'port': u'37842',
              u'seeder': u'false',
              u'uploadSpeed': u'6890'}]}
Source code in src/aria2p/client.py
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
def get_peers(self, gid: str) -> dict:
    """Return peers list of a download.

    This method returns the list of peers of the download denoted by gid (string). This method is for BitTorrent
    only. The response is an array of structs and contains the following keys. Values are strings.

    - `peerId`: Percent-encoded peer ID.
    - `ip`: IP address of the peer.
    - `port`: Port number of the peer.
    - `bitfield`: Hexadecimal representation of the download progress of the peer. The highest bit corresponds to
      the piece at index 0. Set bits indicate the piece is available and unset bits indicate the piece is
      missing. Any spare bits at the end are set to zero.
    - `amChoking`: true if aria2 is choking the peer. Otherwise false.
    - `peerChoking`: true if the peer is choking aria2. Otherwise false.
    - `downloadSpeed`: Download speed (byte/sec) that this client obtains from the peer.
    - `uploadSpeed`: Upload speed(byte/sec) that this client uploads to the peer.
    - `seeder`: true if this peer is a seeder. Otherwise false.

    Original signature:

        aria2.getPeers([secret], gid)

    Parameters:
        gid: The download to get peers from.

    Returns:
        The peers connected to a download.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.getPeers",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [{u'amChoking': u'true',
                      u'bitfield': u'ffffffffffffffffffffffffffffffffffffffff',
                      u'downloadSpeed': u'10602',
                      u'ip': u'10.0.0.9',
                      u'peerChoking': u'false',
                      u'peerId': u'aria2%2F1%2E10%2E5%2D%87%2A%EDz%2F%F7%E6',
                      u'port': u'6881',
                      u'seeder': u'true',
                      u'uploadSpeed': u'0'},
                     {u'amChoking': u'false',
                      u'bitfield': u'ffffeff0fffffffbfffffff9fffffcfff7f4ffff',
                      u'downloadSpeed': u'8654',
                      u'ip': u'10.0.0.30',
                      u'peerChoking': u'false',
                      u'peerId': u'bittorrent client758',
                      u'port': u'37842',
                      u'seeder': u'false',
                      u'uploadSpeed': u'6890'}]}
    """
    return self.call(self.GET_PEERS, [gid])  # type: ignore

get_servers ¤

get_servers(gid: str) -> dict

Return servers currently connected for a download.

This method returns currently connected HTTP(S)/FTP/SFTP servers of the download denoted by gid (string). The response is an array of structs and contains the following keys. Values are strings.

  • index: Index of the file, starting at 1, in the same order as files appear in the multi-file metalink.
  • servers: A list of structs which contain the following keys.
    • uri: Original URI.
    • currentUri: This is the URI currently used for downloading. If redirection is involved, currentUri and uri may differ.
    • downloadSpeed: Download speed (byte/sec).

Original signature:

aria2.getServers([secret], gid)

Parameters:

  • gid (str) –

    The download to get servers from.

Returns:

  • dict

    The servers connected to a download.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.getServers",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [{u'index': u'1',
              u'servers': [{u'currentUri': u'http://example.org/file',
                            u'downloadSpeed': u'10467',
                            u'uri': u'http://example.org/file'}]}]}
Source code in src/aria2p/client.py
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
def get_servers(self, gid: str) -> dict:
    """Return servers currently connected for a download.

    This method returns currently connected HTTP(S)/FTP/SFTP servers of the download denoted by gid (string). The
    response is an array of structs and contains the following keys. Values are strings.

    - `index`: Index of the file, starting at 1, in the same order as files appear in the multi-file metalink.
    - `servers`: A list of structs which contain the following keys.
        - `uri`: Original URI.
        - `currentUri`: This is the URI currently used for downloading.
          If redirection is involved, currentUri and uri may differ.
        - `downloadSpeed`: Download speed (byte/sec).

    Original signature:

        aria2.getServers([secret], gid)

    Parameters:
        gid: The download to get servers from.

    Returns:
        The servers connected to a download.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.getServers",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [{u'index': u'1',
                      u'servers': [{u'currentUri': u'http://example.org/file',
                                    u'downloadSpeed': u'10467',
                                    u'uri': u'http://example.org/file'}]}]}
    """
    return self.call(self.GET_SERVERS, [gid])  # type: ignore

get_session_info ¤

get_session_info() -> dict

Return session information.

Returns:

  • dict

    A struct that contains the sessionId key, which is generated each time aria2 is invoked.

Original signature:

aria2.getSessionInfo([secret])

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getSessionInfo"}
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'sessionId': u'cd6a3bc6a1de28eb5bfa181e5f6b916d44af31a9'}}
Source code in src/aria2p/client.py
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
def get_session_info(self) -> dict:
    """Return session information.

    Returns:
        A struct that contains the `sessionId` key, which is generated each time aria2 is invoked.

    Original signature:

        aria2.getSessionInfo([secret])

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getSessionInfo"}
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'sessionId': u'cd6a3bc6a1de28eb5bfa181e5f6b916d44af31a9'}}
    """
    return self.call(self.GET_SESSION_INFO)  # type: ignore

get_uris ¤

get_uris(gid: str) -> dict

Return URIs used in a download.

This method returns the URIs used in the download denoted by gid (string). The response is an array of structs and it contains following keys. Values are string.

  • uri: URI
  • status: 'used' if the URI is in use. 'waiting' if the URI is still waiting in the queue.

Original signature:

aria2.getUris([secret], gid)

Parameters:

  • gid (str) –

    The download to list URIs of.

Returns:

  • dict

    The URIs used in a download.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.getUris",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [{u'status': u'used',
              u'uri': u'http://example.org/file'}]}
Source code in src/aria2p/client.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
def get_uris(self, gid: str) -> dict:
    """Return URIs used in a download.

    This method returns the URIs used in the download denoted by gid (string). The response is an array of
    structs and it contains following keys. Values are string.

    - `uri`: URI
    - `status`: 'used' if the URI is in use. 'waiting' if the URI is still waiting in the queue.

    Original signature:

        aria2.getUris([secret], gid)

    Parameters:
        gid: The download to list URIs of.

    Returns:
        The URIs used in a download.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.getUris",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [{u'status': u'used',
                      u'uri': u'http://example.org/file'}]}
    """
    return self.call(self.GET_URIS, [gid])  # type: ignore

get_version ¤

get_version() -> str

Return aria2 version and the list of enabled features.

Original signature:

aria2.getVersion([secret])

Returns:

  • str

    A struct that contains the following keys:

  • str
    • version: Version number of aria2 as a string.
  • str
    • enabledFeatures: List of enabled features. Each feature is given as a string.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getVersion"}
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'enabledFeatures': [u'Async DNS',
                                  u'BitTorrent',
                                  u'Firefox3 Cookie',
                                  u'GZip',
                                  u'HTTPS',
                                  u'Message Digest',
                                  u'Metalink',
                                  u'XML-RPC'],
             u'version': u'1.11.0'}}
Source code in src/aria2p/client.py
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
def get_version(self) -> str:
    """Return aria2 version and the list of enabled features.

    Original signature:

        aria2.getVersion([secret])

    Returns:
        A struct that contains the following keys:

        - `version`: Version number of aria2 as a string.
        - `enabledFeatures`: List of enabled features. Each feature is given as a string.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {"jsonrpc": "2.0", "id": "qwer", "method": "aria2.getVersion"}
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'enabledFeatures': [u'Async DNS',
                                          u'BitTorrent',
                                          u'Firefox3 Cookie',
                                          u'GZip',
                                          u'HTTPS',
                                          u'Message Digest',
                                          u'Metalink',
                                          u'XML-RPC'],
                     u'version': u'1.11.0'}}
    """
    return self.call(self.GET_VERSION)  # type: ignore

list_methods ¤

list_methods() -> list[str]

Return the available RPC methods.

This method returns all the available RPC methods in an array of string. Unlike other methods, this method does not require secret token. This is safe because this method just returns the available method names.

Original signature:

system.listMethods()

Returns:

  • list[str]

    The list of available RPC methods.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {"jsonrpc": "2.0", "id": "qwer", "method": "system.listMethods"}
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [u'aria2.addUri',
             u'aria2.addTorrent',
 ...
Source code in src/aria2p/client.py
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
def list_methods(self) -> list[str]:
    """Return the available RPC methods.

    This method returns all the available RPC methods in an array of string. Unlike other methods,
    this method does not require secret token. This is safe because this method just returns the available
    method names.

    Original signature:

        system.listMethods()

    Returns:
        The list of available RPC methods.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {"jsonrpc": "2.0", "id": "qwer", "method": "system.listMethods"}
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [u'aria2.addUri',
                     u'aria2.addTorrent',
         ...
    """
    return self.call(self.LIST_METHODS)  # type: ignore

list_notifications ¤

list_notifications() -> list[str]

Return all the available RPC notifications.

This method returns all the available RPC notifications in an array of string. Unlike other methods, this method does not require secret token. This is safe because this method just returns the available notifications names.

Original signature:

system.listNotifications()

Returns:

  • list[str]

    The list of available RPC notifications.

Examples:

Original JSON-RPC Example

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {"jsonrpc": "2.0", "id": "qwer", "method": "system.listNotifications"}
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': [u'aria2.onDownloadStart',
             u'aria2.onDownloadPause',
 ...
Source code in src/aria2p/client.py
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
def list_notifications(self) -> list[str]:
    """Return all the available RPC notifications.

    This method returns all the available RPC notifications in an array of string. Unlike other methods,
    this method does not require secret token. This is safe because this method just returns the available
    notifications names.

    Original signature:

        system.listNotifications()

    Returns:
        The list of available RPC notifications.

    Examples:
        **Original JSON-RPC Example**

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {"jsonrpc": "2.0", "id": "qwer", "method": "system.listNotifications"}
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': [u'aria2.onDownloadStart',
                     u'aria2.onDownloadPause',
         ...
    """
    return self.call(self.LIST_NOTIFICATIONS)  # type: ignore

listen_to_notifications ¤

listen_to_notifications(
    on_download_start: Callable | None = None,
    on_download_pause: Callable | None = None,
    on_download_stop: Callable | None = None,
    on_download_complete: Callable | None = None,
    on_download_error: Callable | None = None,
    on_bt_download_complete: Callable | None = None,
    timeout: int = 5,
    handle_signals: bool = True,
) -> None

Start listening to aria2 notifications via WebSocket.

This method opens a WebSocket connection to the server and wait for notifications (or events) to be received. It accepts callbacks as arguments, which are functions accepting one parameter called "gid", for each type of notification.

Stop listening to notifications with the stop_listening method.

Parameters:

  • on_download_start (Callable | None, default: None ) –

    Callback for the onDownloadStart event.

  • on_download_pause (Callable | None, default: None ) –

    Callback for the onDownloadPause event.

  • on_download_stop (Callable | None, default: None ) –

    Callback for the onDownloadStop event.

  • on_download_complete (Callable | None, default: None ) –

    Callback for the onDownloadComplete event.

  • on_download_error (Callable | None, default: None ) –

    Callback for the onDownloadError event.

  • on_bt_download_complete (Callable | None, default: None ) –

    Callback for the onBtDownloadComplete event.

  • timeout (int, default: 5 ) –

    Timeout when waiting for data to be received. Use a small value for faster reactivity when stopping to listen. Default is 5 seconds.

  • handle_signals (bool, default: True ) –

    Whether to add signal handlers to gracefully stop the loop on SIGTERM and SIGINT.

Source code in src/aria2p/client.py
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
def listen_to_notifications(
    self,
    on_download_start: Callable | None = None,
    on_download_pause: Callable | None = None,
    on_download_stop: Callable | None = None,
    on_download_complete: Callable | None = None,
    on_download_error: Callable | None = None,
    on_bt_download_complete: Callable | None = None,
    timeout: int = 5,
    handle_signals: bool = True,  # noqa: FBT001,FBT002
) -> None:
    """Start listening to aria2 notifications via WebSocket.

    This method opens a WebSocket connection to the server and wait for notifications (or events) to be received.
    It accepts callbacks as arguments, which are functions accepting one parameter called "gid", for each type
    of notification.

    Stop listening to notifications with the [`stop_listening`][aria2p.client.Client.stop_listening] method.

    Parameters:
        on_download_start: Callback for the `onDownloadStart` event.
        on_download_pause: Callback for the `onDownloadPause` event.
        on_download_stop: Callback for the `onDownloadStop` event.
        on_download_complete: Callback for the `onDownloadComplete` event.
        on_download_error: Callback for the `onDownloadError` event.
        on_bt_download_complete: Callback for the `onBtDownloadComplete` event.
        timeout: Timeout when waiting for data to be received. Use a small value for faster reactivity
            when stopping to listen. Default is 5 seconds.
        handle_signals: Whether to add signal handlers to gracefully stop the loop on SIGTERM and SIGINT.
    """
    self.listening = True
    ws_server = self.ws_server
    log_prefix = f"Notifications ({ws_server})"

    logger.debug(f"{log_prefix}: opening WebSocket with timeout={timeout}")
    try:
        socket = websocket.create_connection(ws_server, timeout=timeout)
    except (ConnectionRefusedError, ConnectionResetError):
        logger.error(f"{log_prefix}: connection refused. Is the server running?")
        return

    callbacks = {
        NOTIFICATION_START: on_download_start,
        NOTIFICATION_PAUSE: on_download_pause,
        NOTIFICATION_STOP: on_download_stop,
        NOTIFICATION_COMPLETE: on_download_complete,
        NOTIFICATION_ERROR: on_download_error,
        NOTIFICATION_BT_COMPLETE: on_bt_download_complete,
    }

    stopped = SignalHandler(["SIGTERM", "SIGINT"]) if handle_signals else False

    while not stopped:
        logger.debug(f"{log_prefix}: waiting for data over WebSocket")
        try:
            message = socket.recv()
        except websocket.WebSocketConnectionClosedException:
            logger.error(f"{log_prefix}: connection to server was closed. Is the server running?")
            break
        except websocket.WebSocketTimeoutException:
            logger.debug(f"{log_prefix}: reached timeout ({timeout}s)")
        else:
            notification = Notification.get_or_raise(json.loads(message))
            logger.info(
                f"{log_prefix}: received {notification.type} with gid={notification.gid}",
            )
            callback = callbacks.get(notification.type)
            if callable(callback):
                logger.debug(f"{log_prefix}: calling {callback} with gid={notification.gid}")
                callback(notification.gid)
            else:
                logger.debug(f"{log_prefix}: no callback given for type " + notification.type)

        if not self.listening:
            logger.debug(f"{log_prefix}: stopped listening")
            break

    if stopped:
        logger.debug(f"{log_prefix}: stopped listening after receiving a signal")
        self.listening = False

    logger.debug(f"{log_prefix}: closing WebSocket")
    socket.close()

multicall ¤

multicall(methods: list[dict]) -> list[CallReturnType]

Call multiple methods in a single request.

This methods encapsulates multiple method calls in a single request.

Original signature:

system.multicall(methods)

Parameters:

  • methods (list[dict]) –

    An array of structs. The structs contain two keys: methodName and params. - methodName is the method name to call and - params is array containing parameters to the method call.

Returns:

  • list[CallReturnType]

    An array of responses.

  • list[CallReturnType]

    The elements will be either a one-item array containing the return value of the method call or a struct of fault

  • list[CallReturnType]

    element if an encapsulated method call fails.

Examples:

Original JSON-RPC Example

In the following examples, we add 2 downloads. The first one is http://example.org/file and the second one is file.torrent.

>>> import urllib2, json, base64
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "system.multicall",
...         "params": [
...             [
...                 {
...                     "methodName": "aria2.addUri",
...                     "params": [["http://example.org"]],
...                 },
...                 {
...                     "methodName": "aria2.addTorrent",
...                     "params": [base64.b64encode(open("file.torrent").read())],
...                 },
...             ]
...         ],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': [[u'0000000000000001'], [u'd2703803b52216d1']]}

JSON-RPC additionally supports Batch requests as described in the JSON-RPC 2.0 Specification:

>>> jsonreq = json.dumps(
...     [
...         {
...             "jsonrpc": "2.0",
...             "id": "qwer",
...             "method": "aria2.addUri",
...             "params": [["http://example.org"]],
...         },
...         {
...             "jsonrpc": "2.0",
...             "id": "asdf",
...             "method": "aria2.addTorrent",
...             "params": [base64.b64encode(open("file.torrent").read())],
...         },
...     ]
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
[{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'0000000000000001'},
 {u'id': u'asdf', u'jsonrpc': u'2.0', u'result': u'd2703803b52216d1'}]
Source code in src/aria2p/client.py
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
def multicall(self, methods: list[dict]) -> list[CallReturnType]:
    """Call multiple methods in a single request.

    This methods encapsulates multiple method calls in a single request.

    Original signature:

        system.multicall(methods)

    Parameters:
        methods: An array of structs. The structs contain two keys: `methodName` and `params`.
            - `methodName` is the method name to call and
            - `params` is array containing parameters to the method call.

    Returns:
        An array of responses.
        The elements will be either a one-item array containing the return value of the method call or a struct of fault
        element if an encapsulated method call fails.

    Examples:
        **Original JSON-RPC Example**

        In the following examples, we add 2 downloads. The first one is http://example.org/file and the second one is
        file.torrent.

        >>> import urllib2, json, base64
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "system.multicall",
        ...         "params": [
        ...             [
        ...                 {
        ...                     "methodName": "aria2.addUri",
        ...                     "params": [["http://example.org"]],
        ...                 },
        ...                 {
        ...                     "methodName": "aria2.addTorrent",
        ...                     "params": [base64.b64encode(open("file.torrent").read())],
        ...                 },
        ...             ]
        ...         ],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer', u'jsonrpc': u'2.0', u'result': [[u'0000000000000001'], [u'd2703803b52216d1']]}

        JSON-RPC additionally supports Batch requests as described in the JSON-RPC 2.0 Specification:

        >>> jsonreq = json.dumps(
        ...     [
        ...         {
        ...             "jsonrpc": "2.0",
        ...             "id": "qwer",
        ...             "method": "aria2.addUri",
        ...             "params": [["http://example.org"]],
        ...         },
        ...         {
        ...             "jsonrpc": "2.0",
        ...             "id": "asdf",
        ...             "method": "aria2.addTorrent",
        ...             "params": [base64.b64encode(open("file.torrent").read())],
        ...         },
        ...     ]
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        [{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'0000000000000001'},
         {u'id': u'asdf', u'jsonrpc': u'2.0', u'result': u'd2703803b52216d1'}]
    """
    return self.call(self.MULTICALL, [methods])  # type: ignore

multicall2 ¤

multicall2(
    calls: Multicalls2Type, insert_secret: bool = True
) -> CallReturnType

Call multiple methods in one request.

A method equivalent to multicall, but with a simplified usage.

Instead of providing dictionaries with "methodName" and "params" keys and values, this method allows you to provide the values only, in tuples of length 2.

With a classic multicall, you would write your params like:

[
    {"methodName": client.REMOVE, "params": ["0000000000000001"]},
    {"methodName": client.REMOVE, "params": ["2fa07b6e85c40205"]},
]

With multicall2, you can reduce the verbosity:

[
    (client.REMOVE, ["0000000000000001"]),
    (client.REMOVE, ["2fa07b6e85c40205"]),
]
Note

multicall2 is not part of the JSON-RPC protocol specification. It is implemented here as a simple convenience method.

Parameters:

  • calls (Multicalls2Type) –

    List of tuples composed of method name and parameters.

  • insert_secret (bool, default: True ) –

    Whether to insert the secret token in the parameters or not.

Returns:

  • CallReturnType

    The answer from the server, as a Python object (dict / list / str / int).

Source code in src/aria2p/client.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def multicall2(self, calls: Multicalls2Type, insert_secret: bool = True) -> CallReturnType:  # noqa: FBT001,FBT002
    """Call multiple methods in one request.

    A method equivalent to multicall, but with a simplified usage.

    Instead of providing dictionaries with "methodName" and "params" keys and values, this method allows you
    to provide the values only, in tuples of length 2.

    With a classic multicall, you would write your params like:

        [
            {"methodName": client.REMOVE, "params": ["0000000000000001"]},
            {"methodName": client.REMOVE, "params": ["2fa07b6e85c40205"]},
        ]

    With multicall2, you can reduce the verbosity:

        [
            (client.REMOVE, ["0000000000000001"]),
            (client.REMOVE, ["2fa07b6e85c40205"]),
        ]

    Note:
        multicall2 is not part of the JSON-RPC protocol specification.
        It is implemented here as a simple convenience method.

    Parameters:
        calls: List of tuples composed of method name and parameters.
        insert_secret: Whether to insert the secret token in the parameters or not.

    Returns:
        The answer from the server, as a Python object (dict / list / str / int).
    """
    multicall_params = []

    for method, params in calls:
        params = self.get_params(*params)  # noqa: PLW2901
        if insert_secret and self.secret and method.startswith("aria2."):
            params.insert(0, f"token:{self.secret}")
        multicall_params.append({"methodName": method, "params": params})

    payload: str = self.get_payload(self.MULTICALL, [multicall_params])  # type: ignore
    return self.res_or_raise(self.post(payload))

pause ¤

pause(gid: str) -> str

Pause a download.

This method pauses the download denoted by gid (string). The status of paused download becomes paused. If the download was active, the download is placed in the front of waiting queue. While the status is paused, the download is not started. To change status to waiting, use the unpause() method.

Original signature:

aria2.pause([secret], gid)

Parameters:

  • gid (str) –

    The download to pause.

Returns:

  • str

    The GID of the paused download.

Source code in src/aria2p/client.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
def pause(self, gid: str) -> str:
    """Pause a download.

    This method pauses the download denoted by gid (string).
    The status of paused download becomes paused.
    If the download was active, the download is placed in the front of waiting queue.
    While the status is paused, the download is not started.
    To change status to waiting, use the [`unpause()`][aria2p.client.Client.unpause] method.

    Original signature:

        aria2.pause([secret], gid)

    Parameters:
        gid: The download to pause.

    Returns:
        The GID of the paused download.
    """
    return self.call(self.PAUSE, [gid])  # type: ignore

pause_all ¤

pause_all() -> str

Pause all active/waiting downloads.

This method is equal to calling pause() for every active/waiting download.

Original signature:

aria2.pauseAll([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
676
677
678
679
680
681
682
683
684
685
686
687
688
def pause_all(self) -> str:
    """Pause all active/waiting downloads.

    This method is equal to calling [`pause()`][aria2p.client.Client.pause] for every active/waiting download.

    Original signature:

        aria2.pauseAll([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.PAUSE_ALL)  # type: ignore

post ¤

post(payload: str) -> dict

Send a POST request to the server.

The response is a JSON string, which we then load as a Python object.

Parameters:

  • payload (str) –

    The payload / data to send to the remote process. It contains the following key-value pairs: "jsonrpc": "2.0", "method": method, "id": id, "params": params (optional).

Returns:

  • dict

    The answer from the server, as a Python dictionary.

Source code in src/aria2p/client.py
339
340
341
342
343
344
345
346
347
348
349
350
351
def post(self, payload: str) -> dict:
    """Send a POST request to the server.

    The response is a JSON string, which we then load as a Python object.

    Parameters:
        payload: The payload / data to send to the remote process. It contains the following key-value pairs:
            "jsonrpc": "2.0", "method": method, "id": id, "params": params (optional).

    Returns:
        The answer from the server, as a Python dictionary.
    """
    return requests.post(self.server, data=payload, timeout=self.timeout).json()

purge_download_result ¤

purge_download_result() -> str

Purge completed/error/removed downloads from memory.

Original signature:

aria2.purgeDownloadResult([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
def purge_download_result(self) -> str:
    """Purge completed/error/removed downloads from memory.

    Original signature:

        aria2.purgeDownloadResult([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.PURGE_DOWNLOAD_RESULT)  # type: ignore

remove ¤

remove(gid: str) -> str

Remove a download.

This method removes the download denoted by gid (string). If the specified download is in progress, it is first stopped. The status of the removed download becomes removed. This method returns GID of removed download.

Original signature:

aria2.remove([secret], gid)

Parameters:

  • gid (str) –

    The download to remove.

Returns:

  • str

    The GID of the removed download.

Examples:

Original JSON-RPC Example

The following examples remove a download with GID#0000000000000001.

>>> import urllib2, json
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.remove",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> c.read()
'{"id":"qwer","jsonrpc":"2.0","result":"0000000000000001"}'
Source code in src/aria2p/client.py
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
def remove(self, gid: str) -> str:
    """Remove a download.

    This method removes the download denoted by gid (string). If the specified download is in progress,
    it is first stopped. The status of the removed download becomes removed. This method returns GID of
    removed download.

    Original signature:

        aria2.remove([secret], gid)

    Parameters:
        gid: The download to remove.

    Returns:
        The GID of the removed download.

    Examples:
        **Original JSON-RPC Example**

        The following examples remove a download with GID#0000000000000001.

        >>> import urllib2, json
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.remove",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> c.read()
        '{"id":"qwer","jsonrpc":"2.0","result":"0000000000000001"}'
    """
    return self.call(self.REMOVE, [gid])  # type: ignore[return-value]

remove_download_result ¤

remove_download_result(gid: str) -> str

Remove a completed/error/removed download from memory.

Original signature:

aria2.removeDownloadResult([secret], gid)

Parameters:

  • gid (str) –

    The download result to remove.

Returns:

  • str

    "OK" for success.

Examples:

Original JSON-RPC Example

The following examples remove the download result of the download GID#0000000000000001.

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.removeDownloadResult",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'OK'}
Source code in src/aria2p/client.py
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
def remove_download_result(self, gid: str) -> str:
    """Remove a completed/error/removed download from memory.

    Original signature:

        aria2.removeDownloadResult([secret], gid)

    Parameters:
        gid: The download result to remove.

    Returns:
        `"OK"` for success.

    Examples:
        **Original JSON-RPC Example**

        The following examples remove the download result of the download GID#0000000000000001.

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.removeDownloadResult",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer', u'jsonrpc': u'2.0', u'result': u'OK'}
    """
    return self.call(self.REMOVE_DOWNLOAD_RESULT, [gid])  # type: ignore

res_or_raise staticmethod ¤

res_or_raise(response: dict) -> CallReturnType

Return the result of the response, or raise an error with code and message.

Parameters:

  • response (dict) –

    A response sent by the server.

Returns:

  • CallReturnType

    The "result" value of the response.

Raises:

Source code in src/aria2p/client.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
@staticmethod
def res_or_raise(response: dict) -> CallReturnType:
    """Return the result of the response, or raise an error with code and message.

    Parameters:
        response: A response sent by the server.

    Returns:
        The "result" value of the response.

    Raises:
        ClientException: When the response contains an error (client/server error).
            See the [`ClientException`][aria2p.client.ClientException] class.
    """
    if "error" in response:
        raise Client.response_as_exception(response)
    return response["result"]

response_as_exception staticmethod ¤

response_as_exception(response: dict) -> ClientException

Transform the response as a ClientException instance and return it.

Parameters:

  • response (dict) –

    A response sent by the server.

Returns:

Source code in src/aria2p/client.py
353
354
355
356
357
358
359
360
361
362
363
@staticmethod
def response_as_exception(response: dict) -> ClientException:
    """Transform the response as a [`ClientException`][aria2p.client.ClientException] instance and return it.

    Parameters:
        response: A response sent by the server.

    Returns:
        An instance of the [`ClientException`][aria2p.client.ClientException] class.
    """
    return ClientException(response["error"]["code"], response["error"]["message"])

save_session ¤

save_session() -> str

Save the current session to a file.

This method saves the current session to a file specified by the --save-session option.

Original signature:

aria2.saveSession([secret])

Returns:

  • str

    "OK" if it succeeds.

Source code in src/aria2p/client.py
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
def save_session(self) -> str:
    """Save the current session to a file.

    This method saves the current session to a file specified
    by the [`--save-session`][aria2p.options.Options.save_session] option.

    Original signature:

        aria2.saveSession([secret])

    Returns:
        `"OK"` if it succeeds.
    """
    return self.call(self.SAVE_SESSION)  # type: ignore

shutdown ¤

shutdown() -> str

Shutdown aria2.

Original signature:

aria2.shutdown([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
def shutdown(self) -> str:
    """Shutdown aria2.

    Original signature:

        aria2.shutdown([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.SHUTDOWN)  # type: ignore

stop_listening ¤

stop_listening() -> None

Stop listening to notifications.

Although this method returns instantly, the actual listening loop can take some time to break out, depending on the timeout that was given to Client.listen_to_notifications.

Source code in src/aria2p/client.py
1821
1822
1823
1824
1825
1826
1827
def stop_listening(self) -> None:
    """Stop listening to notifications.

    Although this method returns instantly, the actual listening loop can take some time to break out,
    depending on the timeout that was given to [`Client.listen_to_notifications`][aria2p.client.Client.listen_to_notifications].
    """
    self.listening = False

tell_active ¤

tell_active(keys: list[str] | None = None) -> list[dict]

Return the list of active downloads.

Original signature:

aria2.tellActive([secret][, keys])

Parameters:

  • keys (list[str] | None, default: None ) –

    The keys to return. Please refer to the tell_status() method.

Returns:

Source code in src/aria2p/client.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
def tell_active(self, keys: list[str] | None = None) -> list[dict]:
    """Return the list of active downloads.

    Original signature:

        aria2.tellActive([secret][, keys])

    Parameters:
        keys: The keys to return. Please refer to the [`tell_status()`][aria2p.client.Client.tell_status] method.

    Returns:
        An array of the same structs as returned by the [`tell_status()`][aria2p.client.Client.tell_status] method.
    """
    return self.call(self.TELL_ACTIVE, [keys])  # type: ignore

tell_status ¤

tell_status(
    gid: str, keys: list[str] | None = None
) -> dict

Tell status of a download.

This method returns the progress of the download denoted by gid (string). keys is an array of strings. If specified, the response contains only keys in the keys array. If keys is empty or omitted, the response contains all keys. This is useful when you just want specific keys and avoid unnecessary transfers. For example, tell_status("0000000000000001", ["gid", "status"]) returns the gid and status keys only. The response is a struct and contains following keys. Values are strings.

  • gid: GID of the download.
  • status: active for currently downloading/seeding downloads. waiting for downloads in the queue; download is not started. paused for paused downloads. error for downloads that were stopped because of error. complete for stopped and completed downloads. removed for the downloads removed by user.
  • totalLength: Total length of the download in bytes.
  • completedLength: Completed length of the download in bytes.
  • uploadLength: Uploaded length of the download in bytes.
  • bitfield: Hexadecimal representation of the download progress. The highest bit corresponds to the piece at index 0. Any set bits indicate loaded pieces, while unset bits indicate not yet loaded and/or missing pieces. Any overflow bits at the end are set to zero. When the download was not started yet, this key will not be included in the response.
  • downloadSpeed: Download speed of this download measured in bytes/sec.
  • uploadSpeed: Upload speed of this download measured in bytes/sec.
  • infoHash: InfoHash. BitTorrent only.
  • numSeeders: The number of seeders aria2 has connected to. BitTorrent only.
  • seeder true if the local endpoint is a seeder. Otherwise false. BitTorrent only.
  • pieceLength: Piece length in bytes.
  • numPieces: The number of pieces.
  • connections: The number of peers/servers aria2 has connected to.
  • errorCode: The code of the last error for this item, if any. The value is a string. The error codes are defined in the EXIT STATUS section. This value is only available for stopped/completed downloads.
  • errorMessage: The (hopefully) human readable error message associated to errorCode.
  • followedBy: List of GIDs which are generated as the result of this download. For example, when aria2 downloads a Metalink file, it generates downloads described in the Metalink (see the --follow-metalink option). This value is useful to track auto-generated downloads. If there are no such downloads, this key will not be included in the response.
  • following: The reverse link for followedBy. A download included in followedBy has this object's GID in its following value.
  • belongsTo: GID of a parent download. Some downloads are a part of another download. For example, if a file in a Metalink has BitTorrent resources, the downloads of ".torrent" files are parts of that parent. If this download has no parent, this key will not be included in the response.
  • dir:Directory to save files.
  • files: Return the list of files. The elements of this list are the same structs used in get_files() method.
  • bittorrent: Struct which contains information retrieved from the .torrent (file). BitTorrent only. It contains the following keys:
    • announceList: List of lists of announce URIs. If the torrent contains announce and no announce-list, announce is converted to the announce-list format.
    • comment: The comment of the torrent. comment.utf-8 is used if available.
    • creationDate: The creation time of the torrent. The value is an integer since the epoch, measured in seconds.
    • mode: File mode of the torrent. The value is either single or multi.
    • info: Struct which contains data from Info dictionary. It contains following keys.
      • name: name in info dictionary. name.utf-8 is used if available.
  • verifiedLength: The number of verified number of bytes while the files are being hash checked. This key exists only when this download is being hash checked.
  • verifyIntegrityPending: true if this download is waiting for the hash check in a queue. This key exists only when this download is in the queue.

Original signature:

aria2.tellStatus([secret], gid[, keys])

Parameters:

  • gid (str) –

    The download to tell status of.

  • keys (list[str] | None, default: None ) –

    The keys to return.

Returns:

  • dict

    The details of a download.

Examples:

Original JSON-RPC Example

The following example gets information about a download with GID#0000000000000001:

>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.tellStatus",
...         "params": ["0000000000000001"],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'bitfield': u'0000000000',
             u'completedLength': u'901120',
             u'connections': u'1',
             u'dir': u'/downloads',
             u'downloadSpeed': u'15158',
             u'files': [{u'index': u'1',
                         u'length': u'34896138',
                         u'completedLength': u'34896138',
                         u'path': u'/downloads/file',
                         u'selected': u'true',
                         u'uris': [{u'status': u'used',
                                    u'uri': u'http://example.org/file'}]}],
             u'gid': u'0000000000000001',
             u'numPieces': u'34',
             u'pieceLength': u'1048576',
             u'status': u'active',
             u'totalLength': u'34896138',
             u'uploadLength': u'0',
             u'uploadSpeed': u'0'}}

The following example gets only specific keys:

>>> jsonreq = json.dumps(
...     {
...         "jsonrpc": "2.0",
...         "id": "qwer",
...         "method": "aria2.tellStatus",
...         "params": [
...             "0000000000000001",
...             ["gid", "totalLength", "completedLength"],
...         ],
...     }
... )
>>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
>>> pprint(json.loads(c.read()))
{u'id': u'qwer',
 u'jsonrpc': u'2.0',
 u'result': {u'completedLength': u'5701632',
             u'gid': u'0000000000000001',
             u'totalLength': u'34896138'}}
Source code in src/aria2p/client.py
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def tell_status(self, gid: str, keys: list[str] | None = None) -> dict:
    """Tell status of a download.

    This method returns the progress of the download denoted by gid (string). keys is an array of strings. If
    specified, the response contains only keys in the keys array. If keys is empty or omitted, the response
    contains all keys. This is useful when you just want specific keys and avoid unnecessary transfers. For
    example, `tell_status("0000000000000001", ["gid", "status"])` returns the gid and status keys only. The
    response is a struct and contains following keys. Values are strings.

    - `gid`: GID of the download.
    - `status`: active for currently downloading/seeding downloads. waiting for downloads in the queue; download is
      not started. paused for paused downloads. error for downloads that were stopped because of error.
      complete for stopped and completed downloads. removed for the downloads removed by user.
    - `totalLength`: Total length of the download in bytes.
    - `completedLength`: Completed length of the download in bytes.
    - `uploadLength`: Uploaded length of the download in bytes.
    - `bitfield`: Hexadecimal representation of the download progress. The highest bit corresponds to the piece at
      index 0. Any set bits indicate loaded pieces, while unset bits indicate not yet loaded and/or missing
      pieces. Any overflow bits at the end are set to zero. When the download was not started yet, this key
      will not be included in the response.
    - `downloadSpeed`: Download speed of this download measured in bytes/sec.
    - `uploadSpeed`: Upload speed of this download measured in bytes/sec.
    - `infoHash`: InfoHash. BitTorrent only.
    - `numSeeders`: The number of seeders aria2 has connected to. BitTorrent only.
    - `seeder` true if the local endpoint is a seeder. Otherwise false. BitTorrent only.
    - `pieceLength`: Piece length in bytes.
    - `numPieces`: The number of pieces.
    - `connections`: The number of peers/servers aria2 has connected to.
    - `errorCode`: The code of the last error for this item, if any. The value is a string. The error codes are defined
      in the EXIT STATUS section. This value is only available for stopped/completed downloads.
    - `errorMessage`: The (hopefully) human readable error message associated to errorCode.
    - `followedBy`: List of GIDs which are generated as the result of this download. For example, when aria2 downloads a
      Metalink file, it generates downloads described in the Metalink
      (see the [`--follow-metalink`][aria2p.options.Options.follow_metalink] option).
      This value is useful to track auto-generated downloads. If there are no such downloads,
      this key will not be included in the response.
    - `following`: The reverse link for followedBy.
      A download included in followedBy has this object's GID in its following value.
    - `belongsTo`: GID of a parent download. Some downloads are a part of another download. For example, if a file in a
      Metalink has BitTorrent resources, the downloads of ".torrent" files are parts of that parent. If
      this download has no parent, this key will not be included in the response.
    - `dir`:Directory to save files.
    - `files`: Return the list of files.
      The elements of this list are the same structs used in [`get_files()`][aria2p.client.Client.get_files] method.
    - `bittorrent`: Struct which contains information retrieved from the .torrent (file). BitTorrent only.
      It contains the following keys:
        - `announceList`: List of lists of announce URIs. If the torrent contains announce and no announce-list, announce
          is converted to the announce-list format.
        - `comment`: The comment of the torrent. comment.utf-8 is used if available.
        - `creationDate`: The creation time of the torrent. The value is an integer since the epoch, measured in seconds.
        - `mode`: File mode of the torrent. The value is either single or multi.
        - `info`: Struct which contains data from Info dictionary. It contains following keys.
            - `name`: name in info dictionary. name.utf-8 is used if available.
    - `verifiedLength`: The number of verified number of bytes while the files are being hash checked. This key exists only
      when this download is being hash checked.
    - `verifyIntegrityPending`: true if this download is waiting for the hash check in a queue.
      This key exists only when this download is in the queue.

    Original signature:

        aria2.tellStatus([secret], gid[, keys])

    Parameters:
        gid: The download to tell status of.
        keys: The keys to return.

    Returns:
        The details of a download.

    Examples:
        **Original JSON-RPC Example**

        The following example gets information about a download with GID#0000000000000001:

        >>> import urllib2, json
        >>> from pprint import pprint
        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.tellStatus",
        ...         "params": ["0000000000000001"],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'bitfield': u'0000000000',
                     u'completedLength': u'901120',
                     u'connections': u'1',
                     u'dir': u'/downloads',
                     u'downloadSpeed': u'15158',
                     u'files': [{u'index': u'1',
                                 u'length': u'34896138',
                                 u'completedLength': u'34896138',
                                 u'path': u'/downloads/file',
                                 u'selected': u'true',
                                 u'uris': [{u'status': u'used',
                                            u'uri': u'http://example.org/file'}]}],
                     u'gid': u'0000000000000001',
                     u'numPieces': u'34',
                     u'pieceLength': u'1048576',
                     u'status': u'active',
                     u'totalLength': u'34896138',
                     u'uploadLength': u'0',
                     u'uploadSpeed': u'0'}}

        The following example gets only specific keys:

        >>> jsonreq = json.dumps(
        ...     {
        ...         "jsonrpc": "2.0",
        ...         "id": "qwer",
        ...         "method": "aria2.tellStatus",
        ...         "params": [
        ...             "0000000000000001",
        ...             ["gid", "totalLength", "completedLength"],
        ...         ],
        ...     }
        ... )
        >>> c = urllib2.urlopen("http://localhost:6800/jsonrpc", jsonreq)
        >>> pprint(json.loads(c.read()))
        {u'id': u'qwer',
         u'jsonrpc': u'2.0',
         u'result': {u'completedLength': u'5701632',
                     u'gid': u'0000000000000001',
                     u'totalLength': u'34896138'}}
    """
    return self.call(self.TELL_STATUS, [gid, keys])  # type: ignore

tell_stopped ¤

tell_stopped(
    offset: int, num: int, keys: list[str] | None = None
) -> list[dict]

Return the list of stopped downloads.

This method returns a list of stopped downloads. offset is an integer and specifies the offset from the least recently stopped download.

Original signature:

aria2.tellStopped([secret], offset, num[, keys])

Parameters:

  • offset (int) –

    Same semantics as described in the tell_waiting() method.

  • num (int) –

    An integer to specify the maximum number of downloads to be returned.

  • keys (list[str] | None, default: None ) –

    The keys to return. Please refer to the tell_status() method.

Returns:

Source code in src/aria2p/client.py
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
def tell_stopped(self, offset: int, num: int, keys: list[str] | None = None) -> list[dict]:
    """Return the list of stopped downloads.

    This method returns a list of stopped downloads. offset is an integer and specifies the offset from the
    least recently stopped download.

    Original signature:

        aria2.tellStopped([secret], offset, num[, keys])

    Parameters:
        offset: Same semantics as described in the [`tell_waiting()`][aria2p.client.Client.tell_waiting] method.
        num: An integer to specify the maximum number of downloads to be returned.
        keys: The keys to return. Please refer to the [`tell_status()`][aria2p.client.Client.tell_status] method.

    Returns:
        An array of the same structs as returned by the [`tell_status()`][aria2p.client.Client.tell_status] method.
    """
    return self.call(self.TELL_STOPPED, [offset, num, keys])  # type: ignore

tell_waiting ¤

tell_waiting(
    offset: int, num: int, keys: list[str] | None = None
) -> list[dict]

Return the list of waiting downloads.

This method returns a list of waiting downloads, including paused ones.

Original signature:

aria2.tellWaiting([secret], offset, num[, keys])

Parameters:

  • offset (int) –

    An integer to specify the offset from the download waiting at the front. If offset is a positive integer, this method returns downloads in the range of [offset, offset + num). offset can be a negative integer. offset == -1 points last download in the waiting queue and offset == -2 points the download before the last download, and so on. Downloads in the response are in reversed order then. For example, imagine three downloads "A","B" and "C" are waiting in this order. tell_waiting(0, 1) returns ["A"]. tell_waiting(1, 2) returns ["B", "C"]. tell_waiting(-1, 2) returns ["C", "B"].

  • num (int) –

    An integer to specify the maximum number of downloads to be returned.

  • keys (list[str] | None, default: None ) –

    The keys to return. Please refer to the tell_status() method.

Returns:

Source code in src/aria2p/client.py
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
def tell_waiting(self, offset: int, num: int, keys: list[str] | None = None) -> list[dict]:
    """Return the list of waiting downloads.

    This method returns a list of waiting downloads, including paused ones.

    Original signature:

        aria2.tellWaiting([secret], offset, num[, keys])

    Parameters:
        offset: An integer to specify the offset from the download waiting at the front.
            If `offset` is a positive integer, this method returns downloads in the range of [`offset`, `offset` + `num`).
            `offset` can be a negative integer. `offset == -1` points last download in the waiting queue and `offset == -2`
            points the download before the last download, and so on. Downloads in the response are in reversed order then.
            For example, imagine three downloads "A","B" and "C" are waiting in this order. `tell_waiting(0, 1)`
            returns `["A"]`. `tell_waiting(1, 2)` returns `["B", "C"]`. `tell_waiting(-1, 2)` returns `["C", "B"]`.
        num: An integer to specify the maximum number of downloads to be returned.
        keys: The keys to return. Please refer to the [`tell_status()`][aria2p.client.Client.tell_status] method.

    Returns:
        An array of the same structs as returned by [`tell_status()`][aria2p.client.Client.tell_status] method.
    """
    return self.call(self.TELL_WAITING, [offset, num, keys])  # type: ignore

unpause ¤

unpause(gid: str) -> str

Resume a download.

This method changes the status of the download denoted by gid (string) from paused to waiting, making the download eligible to be restarted. This method returns the GID of the unpaused download.

Original signature:

aria2.unpause([secret], gid)

Parameters:

  • gid (str) –

    The download to resume.

Returns:

  • str

    The GID of the resumed download.

Source code in src/aria2p/client.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def unpause(self, gid: str) -> str:
    """Resume a download.

    This method changes the status of the download denoted by gid (string) from paused to waiting,
    making the download eligible to be restarted. This method returns the GID of the unpaused download.

    Original signature:

        aria2.unpause([secret], gid)

    Parameters:
        gid: The download to resume.

    Returns:
        The GID of the resumed download.
    """
    return self.call(self.UNPAUSE, [gid])  # type: ignore

unpause_all ¤

unpause_all() -> str

Resume all downloads.

This method is equal to calling unpause() for every active/waiting download.

Original signature:

aria2.unpauseAll([secret])

Returns:

  • str

    "OK".

Source code in src/aria2p/client.py
742
743
744
745
746
747
748
749
750
751
752
753
754
def unpause_all(self) -> str:
    """Resume all downloads.

    This method is equal to calling [`unpause()`][aria2p.client.Client.unpause] for every active/waiting download.

    Original signature:

        aria2.unpauseAll([secret])

    Returns:
        `"OK"`.
    """
    return self.call(self.UNPAUSE_ALL)  # type: ignore

ClientException ¤

ClientException(code: int, message: str)

Bases: Exception

An exception specific to JSON-RPC errors.

Parameters:

  • code (int) –

    The error code.

  • message (str) –

    The error message.

Source code in src/aria2p/client.py
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(self, code: int, message: str) -> None:
    """Initialize the exception.

    Parameters:
        code: The error code.
        message: The error message.
    """
    super().__init__()
    if code in JSONRPC_CODES:
        message = f"{JSONRPC_CODES[code]}\n{message}"

    self.code = code
    self.message = message

Download ¤

Download(api: API, struct: dict)

Class containing all information about a download, as retrieved with the client.

Parameters:

  • api (API) –

    The reference to an API instance.

  • struct (dict) –

    A dictionary Python object returned by the JSON-RPC client.

Methods:

Attributes:

Source code in src/aria2p/downloads.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def __init__(self, api: API, struct: dict) -> None:
    """Initialize the object.

    Parameters:
        api: The reference to an [`API`][aria2p.api.API] instance.
        struct: A dictionary Python object returned by the JSON-RPC client.
    """
    self.api = api
    self._struct = struct or {}
    self._files: list[File] = []
    self._root_files_paths: list[Path] = []
    self._bittorrent: BitTorrent | None = None
    self._name = ""
    self._options: Options | None = None
    self._followed_by: list[Download] | None = None
    self._following: Download | None = None
    self._belongs_to: Download | None = None

belongs_to property ¤

belongs_to: Download | None

Parent download.

Returns:

belongs_to_id property ¤

belongs_to_id: str | None

GID of a parent download.

Some downloads are a part of another download. For example, if a file in a Metalink has BitTorrent resources, The downloads of ".torrent" files are parts of that parent. If this download has no parent, this key will not be included in the response.

Returns:

  • str | None

    The GID of the parent download.

bitfield property ¤

bitfield: str | None

Hexadecimal representation of the download progress.

The highest bit corresponds to the piece at index 0. Any set bits indicate loaded pieces, while unset bits indicate not yet loaded and/or missing pieces. Any overflow bits at the end are set to zero. When the download was not started yet, this key will not be included in the response.

Returns:

  • str | None

    The hexadecimal representation of the download progress.

bittorrent property ¤

bittorrent: BitTorrent | None

Struct which contains information retrieved from the .torrent (file).

BitTorrent only.

Returns:

completed_length property ¤

completed_length: int

Completed length of the download in bytes.

Returns:

  • int

    The completed length in bytes.

connections property ¤

connections: int

Return the number of peers/servers aria2 has connected to.

Returns:

  • int

    The number of connected peers/servers.

control_file_path property ¤

control_file_path: Path

Return the path to the aria2 control file for this download.

Returns:

  • Path

    The control file path.

dir property ¤

dir: Path

Directory to save files.

Returns:

  • Path

    The directory where the files are saved.

download_speed property ¤

download_speed: int

Download speed of this download measured in bytes/sec.

Returns:

  • int

    The download speed in bytes/sec.

error_code property ¤

error_code: str | None

Return the code of the last error for this item, if any.

The value is a string. The error codes are defined in the EXIT STATUS section. This value is only available for stopped/completed downloads.

Returns:

  • str | None

    The error code.

error_message property ¤

error_message: str | None

Return the (hopefully) human readable error message associated to errorCode.

Returns:

  • str | None

    The error message.

eta property ¤

eta: timedelta

Return the Estimated Time of Arrival (a timedelta).

Returns:

  • timedelta

    ETA or timedelta.max if unknown.

files property ¤

files: list[File]

Return the list of files.

The elements of this list are the same structs used in aria2.getFiles() method.

Returns:

  • list[File]

    The files of this download.

followed_by property ¤

followed_by: list[Download]

List of downloads generated as the result of this download.

Returns:

followed_by_ids property ¤

followed_by_ids: list[str]

List of GIDs which are generated as the result of this download.

For example, when aria2 downloads a Metalink file, it generates downloads described in the Metalink (see the --follow-metalink option). This value is useful to track auto-generated downloads. If there are no such downloads, this key will not be included in the response.

Returns:

  • list[str]

    The children downloads IDs.

following property ¤

following: Download | None

Return the download this download is following.

Returns:

following_id property ¤

following_id: str | None

Return the reverse link for followedBy.

A download included in followedBy has this object's GID in its following value.

Returns:

  • str | None

    The parent download ID.

gid property ¤

gid: str

GID of the download.

Returns:

  • str

    The download GID.

has_failed property ¤

has_failed: bool

Return True if download has errored.

Returns:

  • bool

    If this download has failed.

info_hash property ¤

info_hash: str | None

Return the InfoHash.

BitTorrent only.

Returns:

  • str | None

    The InfoHash.

is_active property ¤

is_active: bool

Return True if download is active.

Returns:

  • bool

    If this download is active.

is_complete property ¤

is_complete: bool

Return True if download is complete.

Returns:

  • bool

    If this download is complete.

is_metadata property ¤

is_metadata: bool

Return True if this download is only composed of metadata, and no actual files.

Returns:

  • bool

    If this is a metadata download.

is_paused property ¤

is_paused: bool

Return True if download is paused.

Returns:

  • bool

    If this download is paused.

is_removed property ¤

is_removed: bool

Return True if download was removed.

Returns:

  • bool

    If this download was removed.

is_torrent property ¤

is_torrent: bool

Return true if this download is a torrent.

Returns:

  • bool

    If this is a torrent downlaod.

is_waiting property ¤

is_waiting: bool

Return True if download is waiting.

Returns:

  • bool

    If this download is waiting.

live property ¤

live: Download

Return the same object with updated data.

Returns:

name property ¤

name: str

Return the name of the download.

Name is the name of the file if single-file, first file's directory name if multi-file.

Returns:

  • str

    The download name.

num_pieces property ¤

num_pieces: int

Return the number of pieces.

Returns:

  • int

    The number of pieces.

num_seeders property ¤

num_seeders: int

Return the number of seeders aria2 has connected to.

BitTorrent only.

Returns:

  • int

    The numbers of seeders.

options property writable ¤

options: Options

Options specific to this download.

Returns:

  • Options

    The download options.

piece_length property ¤

piece_length: int

Piece length in bytes.

Returns:

  • int

    The piece length in bytes.

progress property ¤

progress: float

Return the progress of the download as float.

Returns:

  • float

    Progress percentage.

root_files_paths property ¤

root_files_paths: list[Path]

Return the unique set of directories/files for this download.

Instead of returning all the leaves like self.files, return the relative root directories if any, and relative root files.

This property is useful when we need to list the directories and files in order to move or copy them. We don't want to copy files one by one, but rather entire directories at once when possible.

Returns:

Examples:

Download directory is /a/b.

>>> self.files
["/a/b/c/1.txt", "/a/b/c/2.txt", "/a/b/3.txt"]
>>> self.root_files_paths
["/a/b/c", "/a/b/3.txt"]

seeder property ¤

seeder: bool

Return True if the local endpoint is a seeder, otherwise false.

BitTorrent only.

Returns:

  • bool

    If the local endpoint is a seeder.

status property ¤

status: str

Return the status of the download.

Returns:

  • str

    active, waiting, paused, error, complete or removed.

total_length property ¤

total_length: int

Total length of the download in bytes.

Returns:

  • int

    The total length in bytes.

upload_length property ¤

upload_length: int

Return the uploaded length of the download in bytes.

Returns:

  • int

    The uploaded length in bytes.

upload_speed property ¤

upload_speed: int

Upload speed of this download measured in bytes/sec.

Returns:

  • int

    The upload speed in bytes/sec.

verified_length property ¤

verified_length: int

Return the number of verified number of bytes while the files are being hash checked.

This key exists only when this download is being hash checked.

Returns:

  • int

    The verified length.

verify_integrity_pending property ¤

verify_integrity_pending: bool | None

Return True if this download is waiting for the hash check in a queue.

This key exists only when this download is in the queue.

Returns:

  • bool | None

    Whether this download is waiting for the hash check.

completed_length_string ¤

completed_length_string(human_readable: bool = True) -> str

Return the completed length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The completed length string.

Source code in src/aria2p/downloads.py
479
480
481
482
483
484
485
486
487
488
489
490
def completed_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the completed length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The completed length string.
    """
    if human_readable:
        return human_readable_bytes(self.completed_length, delim=" ")
    return str(self.completed_length) + " B"

copy_files ¤

copy_files(
    to_directory: str | Path, force: bool = False
) -> bool

Copy downloaded files to another directory.

Parameters:

  • to_directory (str | Path) –

    The target directory to copy files into.

  • force (bool, default: False ) –

    Whether to move files even if download is not complete.

Returns:

  • bool

    Success or failure of the operation.

Source code in src/aria2p/downloads.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
def copy_files(self, to_directory: str | Path, force: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Copy downloaded files to another directory.

    Parameters:
        to_directory: The target directory to copy files into.
        force: Whether to move files even if download is not complete.

    Returns:
        Success or failure of the operation.
    """
    return self.api.copy_files([self], to_directory, force)[0]

download_speed_string ¤

download_speed_string(human_readable: bool = True) -> str

Return the download speed as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The download speed string.

Source code in src/aria2p/downloads.py
536
537
538
539
540
541
542
543
544
545
546
547
def download_speed_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the download speed as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The download speed string.
    """
    if human_readable:
        return human_readable_bytes(self.download_speed, delim=" ", postfix="/s")
    return str(self.download_speed) + " B/s"

eta_string ¤

eta_string(precision: int = 0) -> str

Return the Estimated Time of Arrival as a string.

Parameters:

  • precision (int, default: 0 ) –

    The precision to use, see [aria2p.utils.human_readable_timedelta].

Returns:

  • str

    The Estimated Time of Arrival as a string.

Source code in src/aria2p/downloads.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def eta_string(self, precision: int = 0) -> str:
    """Return the Estimated Time of Arrival as a string.

    Parameters:
        precision: The precision to use, see [aria2p.utils.human_readable_timedelta].

    Returns:
        The Estimated Time of Arrival as a string.
    """
    eta = self.eta

    if eta == timedelta.max:
        return "-"

    return human_readable_timedelta(eta, precision=precision)

move ¤

move(pos: int) -> int

Move the download in the queue, relatively.

Parameters:

  • pos (int) –

    Number of times to move.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
883
884
885
886
887
888
889
890
891
892
def move(self, pos: int) -> int:
    """Move the download in the queue, relatively.

    Parameters:
        pos: Number of times to move.

    Returns:
        The new position of the download.
    """
    return self.api.move(self, pos)

move_down ¤

move_down(pos: int = 1) -> int

Move the download down in the queue.

Parameters:

  • pos (int, default: 1 ) –

    Number of times to move down.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
916
917
918
919
920
921
922
923
924
925
def move_down(self, pos: int = 1) -> int:
    """Move the download down in the queue.

    Parameters:
        pos: Number of times to move down.

    Returns:
        The new position of the download.
    """
    return self.api.move_down(self, pos)

move_files ¤

move_files(
    to_directory: str | Path, force: bool = False
) -> bool

Move downloaded files to another directory.

Parameters:

  • to_directory (str | Path) –

    The target directory to move files to.

  • force (bool, default: False ) –

    Whether to move files even if download is not complete.

Returns:

  • bool

    Success or failure of the operation.

Source code in src/aria2p/downloads.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def move_files(self, to_directory: str | Path, force: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Move downloaded files to another directory.

    Parameters:
        to_directory: The target directory to move files to.
        force: Whether to move files even if download is not complete.

    Returns:
        Success or failure of the operation.
    """
    return self.api.move_files([self], to_directory, force)[0]

move_to ¤

move_to(pos: int) -> int

Move the download in the queue, absolutely.

Parameters:

  • pos (int) –

    The absolute position in the queue to take.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
894
895
896
897
898
899
900
901
902
903
def move_to(self, pos: int) -> int:
    """Move the download in the queue, absolutely.

    Parameters:
        pos: The absolute position in the queue to take.

    Returns:
        The new position of the download.
    """
    return self.api.move_to(self, pos)

move_to_bottom ¤

move_to_bottom() -> int

Move the download to the bottom of the queue.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
935
936
937
938
939
940
941
def move_to_bottom(self) -> int:
    """Move the download to the bottom of the queue.

    Returns:
        The new position of the download.
    """
    return self.api.move_to_bottom(self)

move_to_top ¤

move_to_top() -> int

Move the download to the top of the queue.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
927
928
929
930
931
932
933
def move_to_top(self) -> int:
    """Move the download to the top of the queue.

    Returns:
        The new position of the download.
    """
    return self.api.move_to_top(self)

move_up ¤

move_up(pos: int = 1) -> int

Move the download up in the queue.

Parameters:

  • pos (int, default: 1 ) –

    Number of times to move up.

Returns:

  • int

    The new position of the download.

Source code in src/aria2p/downloads.py
905
906
907
908
909
910
911
912
913
914
def move_up(self, pos: int = 1) -> int:
    """Move the download up in the queue.

    Parameters:
        pos: Number of times to move up.

    Returns:
        The new position of the download.
    """
    return self.api.move_up(self, pos)

pause ¤

pause(force: bool = False) -> bool

Pause the download.

Parameters:

  • force (bool, default: False ) –

    Whether to force pause (don't contact servers).

Returns:

  • bool

    Always True (raises exception otherwise).

Raises:

Source code in src/aria2p/downloads.py
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def pause(self, force: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Pause the download.

    Parameters:
        force: Whether to force pause (don't contact servers).

    Returns:
        Always True (raises exception otherwise).

    Raises:
        ClientException: When pausing failed.
    """
    result = self.api.pause([self], force=force)[0]
    if not result:
        raise result  # type: ignore  # we know it's a ClientException
    return True

piece_length_string ¤

piece_length_string(human_readable: bool = True) -> str

Return the piece length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The piece length string.

Source code in src/aria2p/downloads.py
613
614
615
616
617
618
619
620
621
622
623
624
def piece_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the piece length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The piece length string.
    """
    if human_readable:
        return human_readable_bytes(self.piece_length, delim=" ")
    return str(self.piece_length) + " B"

progress_string ¤

progress_string(digits: int = 2) -> str

Return the progress percentage as string.

Parameters:

  • digits (int, default: 2 ) –

    Number of decimal digits to use.

Returns:

  • str

    The progress percentage.

Source code in src/aria2p/downloads.py
844
845
846
847
848
849
850
851
852
853
def progress_string(self, digits: int = 2) -> str:
    """Return the progress percentage as string.

    Parameters:
        digits: Number of decimal digits to use.

    Returns:
        The progress percentage.
    """
    return f"{self.progress:.{digits}f}%"

purge ¤

purge() -> bool

Purge itself from the results.

Returns:

  • bool

    Success or failure of the operation.

Source code in src/aria2p/downloads.py
992
993
994
995
996
997
998
def purge(self) -> bool:
    """Purge itself from the results.

    Returns:
        Success or failure of the operation.
    """
    return self.api.client.remove_download_result(self.gid) == "OK"

remove ¤

remove(force: bool = False, files: bool = False) -> bool

Remove the download from the queue (even if active).

Parameters:

  • force (bool, default: False ) –

    Whether to force removal.

  • files (bool, default: False ) –

    Whether to remove files as well.

Returns:

  • bool

    Always True (raises exception otherwise).

Raises:

Source code in src/aria2p/downloads.py
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def remove(self, force: bool = False, files: bool = False) -> bool:  # noqa: FBT001,FBT002
    """Remove the download from the queue (even if active).

    Parameters:
        force: Whether to force removal.
        files: Whether to remove files as well.

    Returns:
        Always True (raises exception otherwise).

    Raises:
        ClientException: When removal failed.
    """
    result = self.api.remove([self], force=force, files=files)[0]
    if not result:
        raise result  # type: ignore  # we know it's a ClientException
    return True

resume ¤

resume() -> bool

Resume the download.

Returns:

  • bool

    Always True (raises exception otherwise).

Raises:

Source code in src/aria2p/downloads.py
978
979
980
981
982
983
984
985
986
987
988
989
990
def resume(self) -> bool:
    """Resume the download.

    Returns:
        Always True (raises exception otherwise).

    Raises:
        ClientException: When resuming failed.
    """
    result = self.api.resume([self])[0]
    if not result:
        raise result  # type: ignore  # we know it's a ClientException
    return True

total_length_string ¤

total_length_string(human_readable: bool = True) -> str

Return the total length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The total length string.

Source code in src/aria2p/downloads.py
457
458
459
460
461
462
463
464
465
466
467
468
def total_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the total length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The total length string.
    """
    if human_readable:
        return human_readable_bytes(self.total_length, delim=" ")
    return str(self.total_length) + " B"

update ¤

update() -> None

Update the internal values of the download with more recent values.

Source code in src/aria2p/downloads.py
243
244
245
246
247
248
249
250
251
252
253
def update(self) -> None:
    """Update the internal values of the download with more recent values."""
    self._struct = self.api.client.tell_status(self.gid)

    self._files = []
    self._name = ""
    self._bittorrent = None
    self._followed_by = None
    self._following = None
    self._belongs_to = None
    self._options = None

update_options ¤

update_options() -> None

Re-fetch the options from the remote.

Source code in src/aria2p/downloads.py
354
355
356
def update_options(self) -> None:
    """Re-fetch the options from the remote."""
    self._options = self.api.get_options(downloads=[self])[0]

upload_length_string ¤

upload_length_string(human_readable: bool = True) -> str

Return the upload length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The upload length string.

Source code in src/aria2p/downloads.py
501
502
503
504
505
506
507
508
509
510
511
512
def upload_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the upload length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The upload length string.
    """
    if human_readable:
        return human_readable_bytes(self.upload_length, delim=" ")
    return str(self.upload_length) + " B"

upload_speed_string ¤

upload_speed_string(human_readable: bool = True) -> str

Return the upload speed as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The upload speed string.

Source code in src/aria2p/downloads.py
558
559
560
561
562
563
564
565
566
567
568
569
def upload_speed_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the upload speed as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The upload speed string.
    """
    if human_readable:
        return human_readable_bytes(self.upload_speed, delim=" ", postfix="/s")
    return str(self.upload_speed) + " B/s"

verified_length_string ¤

verified_length_string(human_readable: bool = True) -> str

Return the verified length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The verified length string.

Source code in src/aria2p/downloads.py
808
809
810
811
812
813
814
815
816
817
818
819
def verified_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the verified length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The verified length string.
    """
    if human_readable:
        return human_readable_bytes(self.verified_length, delim=" ")
    return str(self.verified_length) + " B"

File ¤

File(struct: dict)

Information about a download's file.

Parameters:

  • struct (dict) –

    A dictionary Python object returned by the JSON-RPC client.

Methods:

Attributes:

  • completed_length (int) –

    Completed length of this file in bytes.

  • index (int) –

    Index of the file, starting at 1, in the same order as files appear in the multi-file torrent.

  • is_metadata (bool) –

    Return True if this file is aria2 metadata and not an actual file.

  • length (int) –

    Return the file size in bytes.

  • path (Path) –

    File path.

  • selected (bool) –

    Return True if this file is selected by --select-file option.

  • uris (list[dict]) –

    Return a list of URIs for this file.

Source code in src/aria2p/downloads.py
 97
 98
 99
100
101
102
103
def __init__(self, struct: dict) -> None:
    """Initialize the object.

    Parameters:
        struct: A dictionary Python object returned by the JSON-RPC client.
    """
    self._struct = struct or {}

completed_length property ¤

completed_length: int

Completed length of this file in bytes.

Please note that it is possible that sum of completedLength is less than the completedLength returned by the aria2.tellStatus() method. This is because completedLength in aria2.getFiles() only includes completed pieces. On the other hand, completedLength in aria2.tellStatus() also includes partially completed pieces.

Returns:

  • int

    The completed length.

index property ¤

index: int

Index of the file, starting at 1, in the same order as files appear in the multi-file torrent.

Returns:

  • int

    The index of the file.

is_metadata property ¤

is_metadata: bool

Return True if this file is aria2 metadata and not an actual file.

Returns:

  • bool

    If the file is metadata.

length property ¤

length: int

Return the file size in bytes.

Returns:

  • int

    The file size in bytes.

path property ¤

path: Path

File path.

Returns:

  • Path

    The file path.

selected property ¤

selected: bool

Return True if this file is selected by --select-file option.

If --select-file is not specified or this is single-file torrent or not a torrent download at all, this value is always true. Otherwise false.

Returns:

  • bool

    If this file is selected.

uris property ¤

uris: list[dict]

Return a list of URIs for this file.

The element type is the same struct used in the client.get_uris() method.

Returns:

completed_length_string ¤

completed_length_string(human_readable: bool = True) -> str

Return the completed length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The completed length string.

Source code in src/aria2p/downloads.py
175
176
177
178
179
180
181
182
183
184
185
186
def completed_length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the completed length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The completed length string.
    """
    if human_readable:
        return human_readable_bytes(self.completed_length, delim=" ")
    return str(self.completed_length) + " B"

length_string ¤

length_string(human_readable: bool = True) -> str

Return the length as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The length string.

Source code in src/aria2p/downloads.py
149
150
151
152
153
154
155
156
157
158
159
160
def length_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the length as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The length string.
    """
    if human_readable:
        return human_readable_bytes(self.length, delim=" ")
    return str(self.length) + " B"

Options ¤

Options(
    api: API, struct: dict, download: Download | None = None
)

This class holds information retrieved with the get_option or get_global_option methods of the client.

Instances are given a reference to an API instance to be able to change their values both locally and remotely, by using the API client and calling remote methods to change options.

The options are available with the same names, using underscores instead of dashes, except for "continue" (which is a Python reserved keyword) which is here called "continue_downloads". For example, "max-concurrent-downloads" is used like options.max_concurrent_downloads = 5.

Parameters:

  • api (API) –

    The reference to an API instance.

  • struct (dict) –

    A dictionary Python object returned by the JSON-RPC client.

  • download (Download | None, default: None ) –

    An optional Download object to inform about the owner, or None to tell they are global options.

Methods:

  • get

    Get the value of an option given its name.

  • get_struct

    Return a copy of the struct dictionary of this Options object.

  • set

    Set the value of an option given its name.

Attributes:

Source code in src/aria2p/options.py
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(self, api: API, struct: dict, download: Download | None = None):
    """Initialize the object.

    Parameters:
        api: The reference to an [`API`][aria2p.api.API] instance.
        struct: A dictionary Python object returned by the JSON-RPC client.
        download: An optional [`Download`][aria2p.downloads.Download] object
            to inform about the owner, or None to tell they are global options.
    """
    self.api = api
    self.download = download
    self._struct = struct or {}

all_proxy property writable ¤

all_proxy: str

Return the all-proxy option value.

Use a proxy server for all protocols.

To override a previously defined proxy, use "". You also can override this setting and specify a proxy server for a particular protocol using --http-proxy, --https-proxy and --ftp-proxy options. This affects all downloads. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT]. See also ENVIRONMENT section.

Note

If user and password are embedded in proxy URI and they are also specified by --{http,https,ftp, all}-proxy-{user,passwd} options, those specified later override prior options. For example, if you specified http-proxy-user=myname, http-proxy-passwd=mypass in aria2.conf and you specified --http-proxy="http://proxy" on the command-line, then you'd get HTTP proxy http://proxy with user myname and password mypass.

Another example: if you specified on the command-line --http-proxy="http://user:pass@proxy" --http-proxy-user="myname" --http-proxy-passwd="mypass", then you'd get HTTP proxy http://proxy with user myname and password mypass.

One more example: if you specified in command-line --http-proxy-user="myname" --http-proxy-passwd="mypass" --http-proxy="http://user:pass@proxy", then you'd get HTTP proxy http://proxy with user user and password pass.

Returns:

all_proxy_passwd property writable ¤

all_proxy_passwd: str

Return the all-proxy-passwd option value.

Set password for --all-proxy option.

Returns:

all_proxy_user property writable ¤

all_proxy_user: str

Return the all-proxy-user option value.

Set user for --all-proxy option.

Returns:

allow_overwrite property writable ¤

allow_overwrite: bool

Return the allow-overwrite option value.

Restart download from scratch if the corresponding control file doesn't exist.

See also --auto-file-renaming option. Default: false.

Returns:

allow_piece_length_change property writable ¤

allow_piece_length_change: bool

Return the allow-piece-length-change option value.

If false is given, aria2 aborts download when a piece length is different from one in a control file.

If true is given, you can proceed but some download progress will be lost. Default: false.

Returns:

always_resume property writable ¤

always_resume: bool

Return the always-resume option value.

Always resume download.

If true is given, aria2 always tries to resume download and if resume is not possible, aborts download. If false is given, when all given URIs do not support resume or aria2 encounters N URIs which does not support resume (N is the value specified using --max-resume-failure-tries option), aria2 downloads file from scratch. See --max-resume-failure-tries option. Default: true.

Returns:

are_global property ¤

are_global: bool

Tell if options are global, or tied to a Download object.

Returns:

  • bool

    Whether these options are global.

async_dns property writable ¤

async_dns: bool

Return the async-dns option value.

Enable asynchronous DNS.

Default: True.

Returns:

async_dns_server property writable ¤

async_dns_server: list[str]

Return the async-dns-server option value.

Comma separated list of DNS server address used in asynchronous DNS resolver.

Usually asynchronous DNS resolver reads DNS server addresses from /etc/resolv.conf. When this option is used, it uses DNS servers specified in this option instead of ones in /etc/resolv.conf. You can specify both IPv4 and IPv6 address. This option is useful when the system does not have /etc/resolv.conf and user does not have the permission to create it.

Returns:

auto_file_renaming property writable ¤

auto_file_renaming: bool

Return the auto-file-renaming option value.

Rename file name if the same file already exists.

This option works only in HTTP(S)/FTP download. The new file name has a dot and a number(1..9999) appended after the name, but before the file extension, if any. Default: true.

Returns:

auto_save_interval property writable ¤

auto_save_interval: int

Save a control file (*.aria2) every SEC seconds.

If 0 is given, a control file is not saved during download. aria2 saves a control file when it stops regardless of the value. The possible values are between 0 to 600. Default: 60.

Returns:

bt_detach_seed_only property writable ¤

bt_detach_seed_only: bool

Return the bt-detach-seed-only option value.

Exclude seed only downloads when counting concurrent active downloads (See -j option).

This means that if -j3 is given and this option is turned on and 3 downloads are active and one of those enters seed mode, then it is excluded from active download count (thus it becomes 2), and the next download waiting in queue gets started. But be aware that seeding item is still recognized as active download in RPC method. Default: false.

Returns:

bt_enable_hook_after_hash_check property writable ¤

bt_enable_hook_after_hash_check: bool

Return the bt-enable-hook-after-hash-check option value.

Allow hook command invocation after hash check (see -V option) in BitTorrent download.

By default, when hash check succeeds, the command given by --on-bt-download-complete is executed. To disable this action, give false to this option. Default: true.

Returns:

bt_enable_lpd property writable ¤

bt_enable_lpd: bool

Return the bt-enable-lpd option value.

Enable Local Peer Discovery.

If a private flag is set in a torrent, aria2 doesn't use this feature for that download even if true is given. Default: false.

Returns:

bt_exclude_tracker property writable ¤

bt_exclude_tracker: list[str]

Return the bt-exclude-tracker option value.

Comma separated list of BitTorrent tracker's announce URI to remove.

You can use special value * which matches all URIs, thus removes all announce URIs. When specifying * in shell command-line, don't forget to escape or quote it. See also --bt-tracker option.

Returns:

bt_external_ip property writable ¤

bt_external_ip: str

Return the bt-external-ip option value.

Specify the external IP address to use in BitTorrent download and DHT.

It may be sent to BitTorrent tracker. For DHT, this option should be set to report that local node is downloading a particular torrent. This is critical to use DHT in a private network. Although this function is named external, it can accept any kind of IP addresses.

Returns:

bt_force_encryption property writable ¤

bt_force_encryption: bool

Return the bt-force-encryption option value.

Requires BitTorrent message payload encryption with arc4.

This is a shorthand of --bt-require-crypto --bt-min-crypto-level=arc4. This option does not change the option value of those options. If true is given, deny legacy BitTorrent handshake and only use Obfuscation handshake and always encrypt message payload. Default: false.

Returns:

bt_hash_check_seed property writable ¤

bt_hash_check_seed: bool

Return the bt-hash-check-seed option value.

If true is given, after hash check using --check-integrity option and file is complete, continue to seed file.

If you want to check file and download it only when it is damaged or incomplete, set this option to false. This option has effect only on BitTorrent download. Default: true

Returns:

bt_lpd_interface property writable ¤

bt_lpd_interface: str

Return the bt-lpd-interface option value.

Use given interface for Local Peer Discovery.

If this option is not specified, the default interface is chosen. You can specify interface name and IP address. Possible Values: interface, IP address.

Returns:

bt_max_open_files property writable ¤

bt_max_open_files: int

Return the bt-max-open-files option value.

Specify maximum number of files to open in multi-file BitTorrent/Metalink download globally.

Default: 100.

Returns:

bt_max_peers property writable ¤

bt_max_peers: int

Return the bt-max-peers option value.

Specify the maximum number of peers per torrent. 0 means unlimited.

See also --bt-request-peer-speed-limit option. Default: 55.

Returns:

bt_metadata_only property writable ¤

bt_metadata_only: bool

Return the bt-metadata-only option value.

Download meta data only.

The file(s) described in meta data will not be downloaded. This option has effect only when BitTorrent Magnet URI is used. See also --bt-save-metadata option. Default: false.

Returns:

bt_min_crypto_level property writable ¤

bt_min_crypto_level: str

Return the bt-min-crypto-level option value.

Set minimum level of encryption method (plain/arc4).

If several encryption methods are provided by a peer, aria2 chooses the lowest one which satisfies the given level. Default: plain.

Returns:

bt_prioritize_piece property writable ¤

bt_prioritize_piece: str

Return the bt-prioritize-piece option value.

Try to download first and last pieces of each file first (head[=<SIZE>],tail[=<SIZE>]).

This is useful for previewing files. The argument can contain 2 keywords: head and tail. To include both keywords, they must be separated by comma. These keywords can take one parameter, SIZE. For example, if head=<SIZE> is specified, pieces in the range of first SIZE bytes of each file get higher priority. tail=<SIZE> means the range of last SIZE bytes of each file. SIZE can include K or M (1K = 1024, 1M = 1024K). If SIZE is omitted, SIZE=1M is used.

Returns:

bt_remove_unselected_file property writable ¤

bt_remove_unselected_file: bool

Return the bt-remove-unselected-file option value.

Removes the unselected files when download is completed in BitTorrent.

To select files, use --select-file option. If it is not used, all files are assumed to be selected. Please use this option with care because it will actually remove files from your disk. Default: false.

Returns:

bt_request_peer_speed_limit property writable ¤

bt_request_peer_speed_limit: int

Return the bt-request-peer-speed-limit option value.

If the whole download speed of every torrent is lower than SPEED, aria2 temporarily increases the number of peers to try for more download speed.

Configuring this option with your preferred download speed can increase your download speed in some cases. You can append K or M (1K = 1024, 1M = 1024K). Default: 50K.

Returns:

bt_require_crypto property writable ¤

bt_require_crypto: bool

Return the bt-require-crypto option value.

If true is given, aria2 doesn't accept and establish connection with legacy BitTorrent handshake (BitTorrent protocol).

Thus aria2 always uses Obfuscation handshake. Default: false.

Returns:

bt_save_metadata property writable ¤

bt_save_metadata: bool

Return the bt-save-metadata option value.

Save meta data as ".torrent" file.

This option has effect only when BitTorrent Magnet URI is used. The file name is hex encoded info hash with suffix ".torrent". The directory to be saved is the same directory where download file is saved. If the same file already exists, meta data is not saved. See also --bt-metadata-only option. Default: false.

Returns:

bt_seed_unverified property writable ¤

bt_seed_unverified: bool

Return the bt-seed-unverified option value.

Seed previously downloaded files without verifying piece hashes.

Default: False.

Returns:

bt_stop_timeout property writable ¤

bt_stop_timeout: int

Return the bt-stop-timeout option value.

Stop BitTorrent download if download speed is 0 in consecutive SEC seconds.

If 0 is given, this feature is disabled. Default: 0.

Returns:

bt_tracker property writable ¤

bt_tracker: list[str]

Return the bt-tracker option value.

Comma separated list of additional BitTorrent tracker's announce URI.

These URIs are not affected by --bt-exclude-tracker option because they are added after URIs in --bt-exclude-tracker option are removed.

Returns:

bt_tracker_connect_timeout property writable ¤

bt_tracker_connect_timeout: int

Return the bt-tracker-connect-timeout option value.

Set the connect timeout in seconds to establish connection to tracker.

After the connection is established, this option makes no effect and --bt-tracker-timeout option is used instead. Default: 60.

Returns:

bt_tracker_interval property writable ¤

bt_tracker_interval: int

Return the bt-tracker-interval option value.

Set the interval in seconds between tracker requests.

This completely overrides interval value and aria2 just uses this value and ignores the min interval and interval value in the response of tracker. If 0 is set, aria2 determines interval based on the response of tracker and the download progress. Default: 0.

Returns:

bt_tracker_timeout property writable ¤

bt_tracker_timeout: int

Return the bt-tracker-timeout option value.

Set timeout in seconds.

Default: 60.

Returns:

ca_certificate property writable ¤

ca_certificate: str

Return the ca-certificate option value.

Use the certificate authorities in FILE to verify the peers.

The certificate file must be in PEM format and can contain multiple CA certificates. Use --check-certificate option to enable verification.

Note

If you build with OpenSSL or the recent version of GnuTLS which has gnutls_certificateset_x509_system_trust() function and the library is properly configured to locate the system-wide CA certificates store, aria2 will automatically load those certificates at the startup.

Note

WinTLS and AppleTLS do not support this option. Instead you will have to import the certificate into the OS trust store.

Returns:

certificate property writable ¤

certificate: str

Return the certificate option value.

Use the client certificate in FILE.

The certificate must be either in PKCS12 (.p12, .pfx) or in PEM format.

PKCS12 files must contain the certificate, a key and optionally a chain of additional certificates. Only PKCS12 files with a blank import password can be opened!

When using PEM, you have to specify the private key via --private-key as well.

Note

WinTLS does not support PEM files at the moment. Users have to use PKCS12 files.

Note

AppleTLS users should use the KeyChain Access utility to import the client certificate and get the SHA-1 fingerprint from the Information dialog corresponding to that certificate. To start aria2c use --certificate=<SHA-1>. Alternatively PKCS12 files are also supported. PEM files, however, are not supported.

Returns:

check_certificate property writable ¤

check_certificate: bool

Return the check-certificate option value.

Verify the peer using certificates specified in --ca-certificate option.

Default: True.

Returns:

check_integrity property writable ¤

check_integrity: bool

Return the check-integrity option value.

Check file integrity by validating piece hashes or a hash of entire file.

This option has effect only in BitTorrent, Metalink downloads with checksums or HTTP(S)/FTP downloads with --checksum option. If piece hashes are provided, this option can detect damaged portions of a file and re-download them. If a hash of entire file is provided, hash check is only done when file has been already downloaded. This is determined by file length. If hash check fails, file is re-downloaded from scratch. If both piece hashes and a hash of entire file are provided, only piece hashes are used. Default: false.

Returns:

checksum property writable ¤

checksum: str

Return the checksum option value.

Set checksum (<TYPE>=<DIGEST>).

TYPE is hash type. The supported hash type is listed in Hash Algorithms in aria2c -v. DIGEST is hex digest. For example, setting sha-1 digest looks like this: sha-1=0192ba11326fe2298c8cb4de616f4d4140213838 This option applies only to HTTP(S)/FTP downloads.

Returns:

conditional_get property writable ¤

conditional_get: bool

Return the conditional-get option value.

Download file only when the local file is older than remote file.

This function only works with HTTP(S) downloads only. It does not work if file size is specified in Metalink. It also ignores Content-Disposition header. If a control file exists, this option will be ignored. This function uses If-Modified-Since header to get only newer file conditionally. When getting modification time of local file, it uses user supplied file name (see --out option) or file name part in URI if --out is not specified. To overwrite existing file, --allow-overwrite is required. Default: false.

Returns:

conf_path property writable ¤

conf_path: str

Return the conf-path option value.

Change the configuration file path to PATH.

Default: $HOME/.aria2/aria2.conf if present, otherwise $XDG_CONFIG_HOME/aria2/aria2.conf.

Returns:

connect_timeout property writable ¤

connect_timeout: int

Return the connect-timeout option value.

Set the connect timeout in seconds to establish connection to HTTP/FTP/proxy server.

After the connection is established, this option makes no effect and --timeout option is used instead. Default: 60.

Returns:

console_log_level property writable ¤

console_log_level: str

Return the console-log-level option value.

Set log level to output to console.

LEVEL is either debug, info, notice, warn or error. Default: notice.

Returns:

continue_downloads property writable ¤

continue_downloads: bool

Return the continue-downloads option value.

Continue downloading a partially downloaded file.

Use this option to resume a download started by a web browser or another program which downloads files sequentially from the beginning. Currently this option is only applicable to HTTP(S)/FTP downloads.

Returns:

daemon property writable ¤

daemon: bool

Return the daemon option value.

Run as daemon.

The current working directory will be changed to / and standard input, standard output and standard error will be redirected to /dev/null. Default: false.

Returns:

deferred_input property writable ¤

deferred_input: bool

Return the deferred-input option value.

If true is given, aria2 does not read all URIs and options from file specified by --input-file option at startup, but it reads one by one when it needs later.

This may reduce memory usage if input file contains a lot of URIs to download. If false is given, aria2 reads all URIs and options at startup. Default: false.

Warning

--deferred-input option will be disabled when --save-session is used together.

Returns:

dht_entry_point property writable ¤

dht_entry_point: str

Return the dht-entry-point option value.

Set host and port as an entry point to IPv4 DHT network (<HOST>:<PORT>).

Returns:

dht_entry_point6 property writable ¤

dht_entry_point6: str

Return the dht-entry-point6 option value.

Set host and port as an entry point to IPv6 DHT network (<HOST>:<PORT>).

Returns:

dht_file_path property writable ¤

dht_file_path: str

Return the dht-file-path option value.

Change the IPv4 DHT routing table file to PATH.

Default: $HOME/.aria2/dht.dat if present, otherwise $XDG_CACHE_HOME/aria2/dht.dat.

Returns:

dht_file_path6 property writable ¤

dht_file_path6: str

Return the dht-file-path6 option value.

Change the IPv6 DHT routing table file to PATH.

Default: $HOME/.aria2/dht6.dat if present, otherwise $XDG_CACHE_HOME/aria2/dht6.dat.

Returns:

dht_listen_addr6 property writable ¤

dht_listen_addr6: str

Return the dht-listen-addr6 option value.

Specify address to bind socket for IPv6 DHT.

It should be a global unicast IPv6 address of the host.

Returns:

dht_listen_port property writable ¤

dht_listen_port: str

Return the dht-listen-port option value.

Set UDP listening port used by DHT(IPv4, IPv6) and UDP tracker.

Multiple ports can be specified by using ,, for example: 6881,6885. You can also use - to specify a range: 6881-6999. , and - can be used together. Default: 6881-6999.

Note

Make sure that the specified ports are open for incoming UDP traffic.

Returns:

dht_message_timeout property writable ¤

dht_message_timeout: int

Return the dht-message-timeout option value.

Set timeout in seconds.

Default: 10.

Returns:

dir property writable ¤

dir: str

Return the dir option value.

The directory to store the downloaded file.

Returns:

disable_ipv6 property writable ¤

disable_ipv6: bool

Return the disable-ipv6 option value.

Disable IPv6.

This is useful if you have to use broken DNS and want to avoid terribly slow AAAA record lookup. Default: false.

Returns:

disk_cache property writable ¤

disk_cache: int

Return the disk-cache option value.

Enable disk cache.

If SIZE is 0, the disk cache is disabled. This feature caches the downloaded data in memory, which grows to at most SIZE bytes. The cache storage is created for aria2 instance and shared by all downloads. The one advantage of the disk cache is reduce the disk I/O because the data are written in larger unit and it is reordered by the offset of the file. If hash checking is involved and the data are cached in memory, we don't need to read them from the disk. SIZE can include K or M (1K = 1024, 1M = 1024K). Default: 16M.

Returns:

download_result property writable ¤

download_result: str

Return the download-result option value.

This option changes the way Download Results is formatted.

If OPT is default, print GID, status, average download speed and path/URI. If multiple files are involved, path/URI of first requested file is printed and remaining ones are omitted. If OPT is full, print GID, status, average download speed, percentage of progress and path/URI. The percentage of progress and path/URI are printed for each requested file in each row. If OPT is hide, Download Results is hidden. Default: default.

Returns:

dry_run property writable ¤

dry_run: bool

Return the dry-run option value.

If true is given, aria2 just checks whether the remote file is available and doesn't download data.

This option has effect on HTTP/FTP download. BitTorrent downloads are canceled if true is specified. Default: false.

Returns:

dscp property writable ¤

dscp: str

Return the dscp option value.

Set DSCP value in outgoing IP packets of BitTorrent traffic for QoS.

This parameter sets only DSCP bits in TOS field of IP packets, not the whole field. If you take values from /usr/include/netinet/ip.h divide them by 4 (otherwise values would be incorrect, e.g. your CS1 class would turn into CS4). If you take commonly used values from RFC, network vendors' documentation, Wikipedia or any other source, use them as they are.

Returns:

enable_color property writable ¤

enable_color: bool

Return the enable-color option value.

Enable color output for a terminal.

Default: True.

Returns:

enable_dht property writable ¤

enable_dht: bool

Return the enable-dht option value.

Enable IPv4 DHT functionality.

It also enables UDP tracker support. If a private flag is set in a torrent, aria2 doesn't use DHT for that download even if true is given. Default: true.

Returns:

enable_dht6 property writable ¤

enable_dht6: bool

Return the enable-dht6 option value.

Enable IPv6 DHT functionality.

If a private flag is set in a torrent, aria2 doesn't use DHT for that download even if true is given. Use --dht-listen-port option to specify port number to listen on. See also --dht-listen-addr6 option.

Returns:

enable_http_keep_alive property writable ¤

enable_http_keep_alive: bool

Return the enable-http-keep-alive option value.

Enable HTTP/1.1 persistent connection.

Default: True.

Returns:

enable_http_pipelining property writable ¤

enable_http_pipelining: bool

Return the enable-http-pipelining option value.

Enable HTTP/1.1 pipelining.

Default: False.

Note

In performance perspective, there is usually no advantage to enable this option.

Returns:

enable_mmap property writable ¤

enable_mmap: bool

Return the enable-mmap option value.

Map files into memory.

This option may not work if the file space is not pre-allocated. See --file-allocation. Default: false.

Returns:

enable_peer_exchange property writable ¤

enable_peer_exchange: bool

Return the enable-peer-exchange option value.

Enable Peer Exchange extension.

If a private flag is set in a torrent, this feature is disabled for that download even if true is given. Default: True.

Returns:

enable_rpc property writable ¤

enable_rpc: bool

Return the enable-rpc option value.

Enable JSON-RPC/XML-RPC server.

It is strongly recommended to set secret authorization token using --rpc-secret option. See also --rpc-listen-port option. Default: false

Returns:

event_poll property writable ¤

event_poll: str

Specify the method for polling events.

The possible values are epoll, kqueue, port, poll and select. For each epoll, kqueue, port and poll, it is available if system supports it. epoll is available on recent Linux. kqueue is available on various *BSD systems including Mac OS X. port is available on Open Solaris. The default value may vary depending on the system you use.

Returns:

file_allocation property writable ¤

file_allocation: str

Return the file-allocation option value.

Specify file allocation method.

Possible Values: none, prealloc, trunc, falloc.

  • none: Doesn't pre-allocate file space.
  • prealloc: Pre-allocates file space before download begins. This may take some time depending on the size of the file.

  • falloc: If you are using newer file systems such as ext4 (with extents support), btrfs, xfs or NTFS(MinGW build only), falloc is your best choice. It allocates large(few GiB) files almost instantly. Don't use falloc with legacy file systems such as ext3 and FAT32 because it takes almost same time as prealloc and it blocks aria2 entirely until allocation finishes. falloc may not be available if your system doesn't have posix_fallocate(3) function.

  • trunc: Uses ftruncate(2) system call or platform-specific counterpart to truncate a file to a specified length.

Default: prealloc.

Warning

Using trunc seemingly allocates disk space very quickly, but what it actually does is that it sets file length metadata in file system, and does not allocate disk space at all. This means that it does not help avoiding fragmentation.

Note

In multi file torrent downloads, the files adjacent forward to the specified files are also allocated if they share the same piece.

Returns:

follow_metalink: str

Return the follow-metalink option value.

If true or mem is specified, when a file whose suffix is .meta4 or .metalink or content type of application/metalink4+xml or application/metalink+xml is downloaded, aria2 parses it as a metalink file and downloads files mentioned in it.

If mem is specified, a metalink file is not written to the disk, but is just kept in memory. If false is specified, the .metalink file is downloaded to the disk, but is not parsed as a metalink file and its contents are not downloaded. Default: true.

Returns:

follow_torrent property writable ¤

follow_torrent: str

Return the follow-torrent option value.

If true or mem is specified, when a file whose suffix is .torrent or content type is application/x-bittorrent is downloaded, aria2 parses it as a torrent file and downloads files mentioned in it.

If mem is specified, a torrent file is not written to the disk, but is just kept in memory. If false is specified, the .torrent file is downloaded to the disk, but is not parsed as a torrent and its contents are not downloaded. Default: true.

Returns:

force_save property writable ¤

force_save: bool

Return the force-save option value.

Save download with --save-session option even if the download is completed or removed.

This option also saves control file in that situations. This may be useful to save BitTorrent seeding which is recognized as completed state. Default: false.

Returns:

force_sequential property writable ¤

force_sequential: bool

Return the force-sequential option value.

Fetch URIs in the command-line sequentially and download each URI in a separate session, like the usual command-line download utilities.

Default: False.

Returns:

ftp_passwd property writable ¤

ftp_passwd: str

Return the ftp-passwd option value.

Set FTP password. This affects all URIs.

If user name is embedded but password is missing in URI, aria2 tries to resolve password using .netrc. If password is found in .netrc, then use it as password. If not, use the password specified in this option. Default: ARIA2USER@.

Returns:

ftp_pasv property writable ¤

ftp_pasv: bool

Return the ftp-pasv option value.

Use the passive mode in FTP.

If false is given, the active mode will be used. Default: true.

Note

This option is ignored for SFTP transfer.

Returns:

ftp_proxy property writable ¤

ftp_proxy: str

Return the ftp-proxy option value.

Use a proxy server for FTP.

To override a previously defined proxy, use "". See also the --all-proxy option. This affects all ftp downloads. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].

Returns:

ftp_proxy_passwd property writable ¤

ftp_proxy_passwd: str

Return the ftp-proxy-passwd option value.

Set password for --ftp-proxy option.

Returns:

ftp_proxy_user property writable ¤

ftp_proxy_user: str

Return the ftp-proxy-user option value.

Set user for --ftp-proxy option.

Returns:

ftp_reuse_connection property writable ¤

ftp_reuse_connection: bool

Return the ftp-reuse-connection option value.

Reuse connection in FTP.

Default: True.

Returns:

ftp_type property writable ¤

ftp_type: str

Return the ftp-type option value.

Set FTP transfer type.

TYPE is either binary or ascii. Default: binary.

Note

This option is ignored for SFTP transfer.

Returns:

ftp_user property writable ¤

ftp_user: str

Return the ftp-user option value.

Set FTP user. This affects all URIs.

Default: anonymous.

Returns:

gid property writable ¤

gid: str

Return the gid option value.

Set GID manually.

aria2 identifies each download by the ID called GID. The GID must be hex string of 16 characters, thus [0-9a-zA-Z] are allowed and leading zeros must not be stripped. The GID all 0 is reserved and must not be used. The GID must be unique, otherwise error is reported and the download is not added. This option is useful when restoring the sessions saved using --save-session option. If this option is not used, new GID is generated by aria2.

Returns:

hash_check_only property writable ¤

hash_check_only: bool

Return the hash-check-only option value.

If true is given, after hash check using --check-integrity option, abort download whether or not download is complete.

Default: False.

Returns:

header property writable ¤

header: str

Return the header option value.

Append HEADER to HTTP request header.

You can use this option repeatedly to specify more than one header:

$ aria2c --header="X-A: b78" --header="X-B: 9J1" "http://host/file"

Returns:

http_accept_gzip property writable ¤

http_accept_gzip: bool

Return the http-accept-gzip option value.

Send Accept: deflate, gzip request header and inflate response if remote server responds with Content-Encoding: gzip or Content-Encoding: deflate.

Default: False.

Note

Some server responds with Content-Encoding: gzip for files which itself is gzipped file. aria2 inflates them anyway because of the response header.

Returns:

http_auth_challenge property writable ¤

http_auth_challenge: bool

Return the http-auth-challenge option value.

Send HTTP authorization header only when it is requested by the server.

If false is set, then authorization header is always sent to the server. There is an exception: if user name and password are embedded in URI, authorization header is always sent to the server regardless of this option. Default: false.

Returns:

http_no_cache property writable ¤

http_no_cache: bool

Return the http-no-cache option value.

Send Cache-Control: no-cache and Pragma: no-cache header to avoid cached content.

If false is given, these headers are not sent and you can add Cache-Control header with a directive you like using --header option. Default: false.

Returns:

http_passwd property writable ¤

http_passwd: str

Return the http-passwd option value.

Set HTTP password. This affects all URIs.

Returns:

http_proxy property writable ¤

http_proxy: str

Return the http-proxy option value.

Use a proxy server for HTTP.

To override a previously defined proxy, use "". See also the --all-proxy option. This affects all http downloads. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].

Returns:

http_proxy_passwd property writable ¤

http_proxy_passwd: str

Return the http-proxy-passwd option value.

Set password for --http-proxy.

Returns:

http_proxy_user property writable ¤

http_proxy_user: str

Return the http-proxy-user option value.

Set user for --http-proxy.

Returns:

http_user property writable ¤

http_user: str

Return the http-user option value.

Set HTTP user. This affects all URIs.

Returns:

https_proxy property writable ¤

https_proxy: str

Return the https-proxy option value.

Use a proxy server for HTTPS.

To override a previously defined proxy, use "". See also the --all-proxy option. This affects all https download. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].

Returns:

https_proxy_passwd property writable ¤

https_proxy_passwd: str

Return the https-proxy-passwd option value.

Set password for --https-proxy.

Returns:

https_proxy_user property writable ¤

https_proxy_user: str

Return the https-proxy-user option value.

Set user for --https-proxy.

Returns:

human_readable property writable ¤

human_readable: bool

Return the human-readable option value.

Print sizes and speed in human readable format (e.g., 1.2Ki, 3.4Mi) in the console readout.

Default: True.

Returns:

index_out property writable ¤

index_out: str

Return the index-out option value.

Set file path for file with index=INDEX (<INDEX>=<PATH>).

You can find the file index using the --show-files option. PATH is a relative path to the path specified in --dir option. You can use this option multiple times. Using this option, you can specify the output file names of BitTorrent downloads.

Returns:

input_file property writable ¤

input_file: str

Return the input-file option value.

Downloads the URIs listed in FILE.

You can specify multiple sources for a single entity by putting multiple URIs on a single line separated by the TAB character. Additionally, options can be specified after each URI line. Option lines must start with one or more white space characters (SPACE or TAB) and must only contain one option per line. Input files can use gzip compression. When FILE is specified as -, aria2 will read the input from stdin. See the Input File subsection for details. See also the --deferred-input option. See also the --save-session option.

Returns:

interface property writable ¤

interface: str

Return the interface option value.

Bind sockets to given interface.

You can specify interface name, IP address and host name. Possible Values: interface, IP address, host name.

Note

If an interface has multiple addresses, it is highly recommended to specify IP address explicitly. See also --disable-ipv6. If your system doesn't have getifaddrs(3), this option doesn't accept interface name.

Returns:

keep_unfinished_download_result property writable ¤

keep_unfinished_download_result: bool

Return the keep-unfinished-download-result option value.

Keep unfinished download results even if doing so exceeds --max-download-result.

This is useful if all unfinished downloads must be saved in session file (see --save-session option). Please keep in mind that there is no upper bound to the number of unfinished download result to keep. If that is undesirable, turn this option off. Default: true.

Returns:

listen_port property writable ¤

listen_port: str

Return the listen-port option value.

Set TCP port number for BitTorrent downloads.

Multiple ports can be specified by using, for example: 6881,6885. You can also use - to specify a range: 6881-6999. , and - can be used together: 6881-6889, 6999. Default: 6881-6999

Note

Make sure that the specified ports are open for incoming TCP traffic.

Returns:

load_cookies property writable ¤

load_cookies: str

Return the load-cookies option value.

Load Cookies from FILE using the Firefox3 format (SQLite3), Chromium/Google Chrome (SQLite3) and the Mozilla/Firefox(1.x/2.x)/Netscape format.

Note

If aria2 is built without libsqlite3, then it doesn't support Firefox3 and Chromium/Google Chrome cookie format.

Returns:

log property writable ¤

log: str

Return the log option value.

The file name of the log file.

If - is specified, log is written to stdout. If empty string("") is specified, or this option is omitted, no log is written to disk at all.

Returns:

log_level property writable ¤

log_level: str

Return the log-level option value.

Set log level to output.

LEVEL is either debug, info, notice, warn or error. Default: debug.

Returns:

lowest_speed_limit property writable ¤

lowest_speed_limit: int

Return the lowest-speed-limit option value.

Close connection if download speed is lower than or equal to this value(bytes per sec).

0 means aria2 does not have a lowest speed limit. You can append K or M (1K = 1024, 1M = 1024K). This option does not affect BitTorrent downloads. Default: 0.

Returns:

max_concurrent_downloads property writable ¤

max_concurrent_downloads: int

Return the max-concurrent-downloads option value.

Set the maximum number of parallel downloads for every queue item.

See also the --split option. Default: 5.

Returns:

max_connection_per_server property writable ¤

max_connection_per_server: int

Return the max-connection-per-server option value.

The maximum number of connections to one server for each download.

Default: 1.

Returns:

max_download_limit property writable ¤

max_download_limit: int

Return the max-download-limit option value.

Set max download speed per each download in bytes/sec.

0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall download speed, use --max-overall-download-limit option. Default: 0.

Returns:

max_download_result property writable ¤

max_download_result: int

Return the max-download-result option value.

Set maximum number of download result kept in memory.

The download results are completed/error/removed downloads. The download results are stored in FIFO queue and it can store at most NUM download results. When queue is full and new download result is created, oldest download result is removed from the front of the queue and new one is pushed to the back. Setting big number in this option may result high memory consumption after thousands of downloads. Specifying 0 means no download result is kept. Note that unfinished downloads are kept in memory regardless of this option value. See --keep-unfinished-download-result option. Default: 1000.

Returns:

max_file_not_found property writable ¤

max_file_not_found: int

Return the max-file-not-found option value.

If aria2 receives "file not found" status from the remote HTTP/FTP servers NUM times without getting a single byte, then force the download to fail.

Specify 0 to disable this option. This options is effective only when using HTTP/FTP servers. The number of retry attempt is counted toward --max-tries, so it should be configured too.

Default: 0.

Returns:

max_mmap_limit property writable ¤

max_mmap_limit: int

Return the max-mmap-limit option value.

Set the maximum file size to enable mmap (see --enable-mmap option).

The file size is determined by the sum of all files contained in one download. For example, if a download contains 5 files, then file size is the total size of those files. If file size is strictly greater than the size specified in this option, mmap will be disabled. Default: 9223372036854775807.

Returns:

max_overall_download_limit property writable ¤

max_overall_download_limit: int

Return the max-overall-download-limit option value.

Set max overall download speed in bytes/sec.

0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the download speed per download, use --max-download-limit option. Default: 0.

Returns:

max_overall_upload_limit property writable ¤

max_overall_upload_limit: int

Return the max-overall-upload-limit option value.

Set max overall upload speed in bytes/sec.

0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the upload speed per torrent, use --max-upload-limit option. Default: 0.

Returns:

max_resume_failure_tries property writable ¤

max_resume_failure_tries: int

Return the max-resume-failure-tries option value.

When used with --always-resume=false, aria2 downloads file from scratch when aria2 detects N number of URIs that does not support resume.

If N is 0, aria2 downloads file from scratch when all given URIs do not support resume. See --always-resume option. Default: 0.

Returns:

max_tries property writable ¤

max_tries: int

Return the max-tries option value.

Set number of tries.

0 means unlimited. See also --retry-wait. Default: 5.

Returns:

max_upload_limit property writable ¤

max_upload_limit: int

Return the max-upload-limit option value.

Set max upload speed per each torrent in bytes/sec.

0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall upload speed, use --max-overall-upload-limit option. Default: 0.

Returns:

metalink_base_uri: str

Return the metalink-base-uri option value.

Specify base URI to resolve relative URI in metalink:url and metalink:metaurl element in a metalink file stored in local disk.

If URI points to a directory, URI must end with /.

Returns:

metalink_enable_unique_protocol: bool

Return the metalink-enable-unique-protocol option value.

If true is given and several protocols are available for a mirror in a metalink file, aria2 uses one of them.

Use --metalink-preferred-protocol option to specify the preference of protocol. Default: true.

Returns:

metalink_file: str

Return the metalink-file option value.

The file path to ".meta4" and ".metalink" file.

Reads input from stdin when - is specified. You are not required to use this option because you can specify ".metalink" files without --metalink-file.

Returns:

metalink_language: str

Return the metalink-language option value.

The language of the file to download.

Returns:

metalink_location: list[str]

Return the metalink-location option value.

The location of the preferred server.

A comma-delimited list of locations is acceptable, for example, jp,us.

Returns:

metalink_os: str

Return the metalink-os option value.

The operating system of the file to download.

Returns:

metalink_preferred_protocol: str

Return the metalink-preferred-protocol option value.

Specify preferred protocol.

The possible values are http, https, ftp and none. Specify none to disable this feature. Default: none.

Returns:

metalink_version: str

Return the metalink-version option value.

The version of the file to download.

Returns:

min_split_size property writable ¤

min_split_size: int

Return the min-split-size option value.

aria2 does not split less than 2*SIZE byte range.

For example, let's consider downloading 20MiB file. If SIZE is 10M, aria2 can split file into 2 range [ 0-10MiB) and [10MiB-20MiB) and download it using 2 sources(if --split >= 2, of course). If SIZE is 15M, since 2*15M > 20MiB, aria2 does not split file and download it using 1 source. You can append K or M (1K = 1024, 1M = 1024K). Possible Values: 1M -1024M Default: 20M

Returns:

min_tls_version property writable ¤

min_tls_version: str

Return the min-tls-version option value.

Specify minimum SSL/TLS version to enable.

Possible Values: SSLv3, TLSv1, TLSv1.1, TLSv1.2. Default: TLSv1.

Returns:

multiple_interface property writable ¤

multiple_interface: list[str]

Return the multiple-interface option value.

Comma separated list of interfaces to bind sockets to.

Requests will be split among the interfaces to achieve link aggregation. You can specify interface name, IP address and hostname. If --interface is used, this option will be ignored. Possible Values: interface, IP address, hostname.

Returns:

netrc_path property writable ¤

netrc_path: str

Return the netrc-path option value.

Specify the path to the netrc file.

Default: $(HOME)/.netrc.

Note

Permission of the .netrc file must be 600. Otherwise, the file will be ignored.

Returns:

no_conf property writable ¤

no_conf: bool

Return the no-conf option value.

Disable loading aria2.conf file.

Returns:

no_file_allocation_limit property writable ¤

no_file_allocation_limit: int

Return the no-file-allocation-limit option value.

No file allocation is made for files whose size is smaller than SIZE.

You can append K or M (1K = 1024, 1M = 1024K). Default: 5M.

Returns:

no_netrc property writable ¤

no_netrc: bool

Return the no-netrc option value.

Disable netrc support.

netrc support is enabled by default.

Note

netrc file is only read at the startup if --no-netrc is false. So if --no-netrc is true at the startup, no netrc is available throughout the session. You cannot get netrc enabled even if you send --no-netrc=false using aria2.changeGlobalOption().

Returns:

no_proxy property writable ¤

no_proxy: str

Return the no-proxy option value.

Specify a comma separated list of host names, domains and network addresses with or without a subnet mask where no proxy should be used.

Note

For network addresses with a subnet mask, both IPv4 and IPv6 addresses work. The current implementation does not resolve the host name in an URI to compare network addresses specified in --no-proxy. So it is only effective if URI has numeric IP addresses.

Returns:

on_bt_download_complete property writable ¤

on_bt_download_complete: str

Return the on-bt-download-complete option value.

For BitTorrent, a command specified in --on-download-complete is called after download completed and seeding is over.

On the other hand, this option set the command to be executed after download completed but before seeding. See Event Hook for more details about COMMAND. Possible Values: /path/to/command.

Returns:

on_download_complete property writable ¤

on_download_complete: str

Return the on-download-complete option value.

Set the command to be executed after download completed.

See See Event Hook for more details about COMMAND. See also --on-download-stop option. Possible Values: /path/to/command.

Returns:

on_download_error property writable ¤

on_download_error: str

Return the on-download-error option value.

Set the command to be executed after download aborted due to error.

See Event Hook for more details about COMMAND. See also --on-download-stop option. Possible Values: /path/to/command.

Returns:

on_download_pause property writable ¤

on_download_pause: str

Return the on-download-pause option value.

Set the command to be executed after download was paused.

See Event Hook for more details about COMMAND. Possible Values: /path/to/command.

Returns:

on_download_start property writable ¤

on_download_start: str

Return the on-download-start option value.

Set the command to be executed after download got started.

See Event Hook for more details about COMMAND. Possible Values: /path/to/command.

Returns:

on_download_stop property writable ¤

on_download_stop: str

Return the on-download-stop option value.

Set the command to be executed after download stopped.

You can override the command to be executed for particular download result using --on-download-complete and --on-download-error. If they are specified, command specified in this option is not executed. See Event Hook for more details about COMMAND. Possible Values: /path/to/command.

Returns:

optimize_concurrent_downloads property writable ¤

optimize_concurrent_downloads: str

Return the optimize-concurrent-downloads option value.

Optimizes the number of concurrent downloads according to the bandwidth available (true|false|<A>:<B>).

aria2 uses the download speed observed in the previous downloads to adapt the number of downloads launched in parallel according to the rule N = A + B Log10(speed in Mbps). The coefficients A and B can be customized in the option arguments with A and B separated by a colon. The default values (A=5, B=25) lead to using typically 5 parallel downloads on 1Mbps networks and above 50 on 100Mbps networks. The number of parallel downloads remains constrained under the maximum defined by the --max-concurrent-downloads parameter. Default: false.

Returns:

out property writable ¤

out: str

Return the out option value.

The file name of the downloaded file.

It is always relative to the directory given in --dir option. When the --force-sequential option is used, this option is ignored.

Note

You cannot specify a file name for Metalink or BitTorrent downloads. The file name specified here is only used when the URIs fed to aria2 are given on the command line directly, but not when using --input-file, --force-sequential option.

aria2c -o myfile.zip "http://mirror1/file.zip" "http://mirror2/file.zip"

Returns:

parameterized_uri property writable ¤

parameterized_uri: bool

Return the parameterized-uri option value.

Enable parameterized URI support.

You can specify set of parts: http://{sv1,sv2,sv3}/foo.iso. Also you can specify numeric sequences with step counter: http://host/image[000-100:2].img. A step counter can be omitted. If all URIs do not point to the same file, such as the second example above, -Z option is required. Default: false.

Returns:

pause property writable ¤

pause: bool

Return the pause option value.

Pause download after added.

This option is effective only when --enable-rpc=true is given. Default: false.

Returns:

pause_metadata property writable ¤

pause_metadata: bool

Return the pause-metadata option value.

Pause downloads created as a result of metadata download.

There are 3 types of metadata downloads in aria2: (1) downloading .torrent file. (2) downloading torrent metadata using magnet link. (3) downloading metalink file. These metadata downloads will generate downloads using their metadata. This option pauses these subsequent downloads. This option is effective only when --enable-rpc=true is given. Default: false.

Returns:

peer_id_prefix property writable ¤

peer_id_prefix: str

Return the peer-id-prefix option value.

Specify the prefix of peer ID.

The peer ID in BitTorrent is 20 byte length. If more than 20 bytes are specified, only first 20 bytes are used. If less than 20 bytes are specified, random byte data are added to make its length 20 bytes.

Default: A2-$MAJOR-$MINOR-$PATCH-, $MAJOR, $MINOR and $PATCH are replaced by major, minor and patch version number respectively. For instance, aria2 version 1.18.8 has prefix ID A2-1-18-8-.

Returns:

piece_length property writable ¤

piece_length: str

Return the piece-length option value.

Set a piece length for HTTP/FTP downloads.

This is the boundary when aria2 splits a file. All splits occur at multiple of this length. This option will be ignored in BitTorrent downloads. It will be also ignored if Metalink file contains piece hashes. Default: 1M.

Note

The possible use case of --piece-length option is change the request range in one HTTP pipelined request. To enable HTTP pipelining use --enable-http-pipelining.

Returns:

private_key property writable ¤

private_key: str

Return the private-key option value.

Use the private key in FILE.

The private key must be decrypted and in PEM format. The behavior when encrypted one is given is undefined. See also --certificate option.

Returns:

proxy_method property writable ¤

proxy_method: str

Return the proxy-method option value.

Set the method to use in proxy request.

METHOD is either get or tunnel. HTTPS downloads always use tunnel regardless of this option. Default: get

Returns:

quiet property writable ¤

quiet: bool

Return the quiet option value.

Make aria2 quiet (no console output).

Default: False.

Returns:

realtime_chunk_checksum property writable ¤

realtime_chunk_checksum: bool

Return the realtime-chunk-checksum option value.

Validate chunk of data by calculating checksum while downloading a file if chunk checksums are provided.

Default: True.

Returns:

referer property writable ¤

referer: str

Return the referer option value.

Set an http referrer (Referer).

This affects all http/https downloads. If * is given, the download URI is also used as the referrer. This may be useful when used together with the --parameterized-uri option.

Returns:

remote_time property writable ¤

remote_time: bool

Return the remote-time option value.

Retrieve timestamp of the remote file from the remote HTTP/FTP server and if it is available, apply it to the local file.

Default: False.

Returns:

remove_control_file property writable ¤

remove_control_file: bool

Return the remove-control-file option value.

Remove control file before download.

Using with --allow-overwrite=true, download always starts from scratch. This will be useful for users behind proxy server which disables resume.

Returns:

retry_wait property writable ¤

retry_wait: int

Return the retry-wait option value.

Set the seconds to wait between retries.

When SEC >` 0, aria2 will retry downloads when the HTTP server returns a 503 response. Default: 0.

Returns:

reuse_uri property writable ¤

reuse_uri: bool

Return the reuse-uri option value.

Reuse already used URIs if no unused URIs are left.

Default: True.

Returns:

rlimit_nofile property writable ¤

rlimit_nofile: int

Return the rlimit-nofile option value.

Set the soft limit of open file descriptors.

This open will only have effect when:

a. The system supports it (posix)

b. The limit does not exceed the hard limit.

c. The specified limit is larger than the current soft limit.

This is equivalent to setting nofile via ulimit, except that it will never decrease the limit.

This option is only available on systems supporting the rlimit API.

Returns:

rpc_allow_origin_all property writable ¤

rpc_allow_origin_all: bool

Return the rpc-allow-origin-all option value.

Add Access-Control-Allow-Origin header field with value * to the RPC response.

Default: False.

Returns:

rpc_certificate property writable ¤

rpc_certificate: str

Return the rpc-certificate option value.

Use the certificate in FILE for RPC server.

The certificate must be either in PKCS12 (.p12, .pfx) or in PEM format.

PKCS12 files must contain the certificate, a key and optionally a chain of additional certificates. Only PKCS12 files with a blank import password can be opened!

When using PEM, you have to specify the private key via --rpc-private-key as well. Use --rpc-secure option to enable encryption.

Note

WinTLS does not support PEM files at the moment. Users have to use PKCS12 files.

Note

AppleTLS users should use the KeyChain Access utility to first generate a self-signed SSL-Server certificate, e.g. using the wizard, and get the SHA-1 fingerprint from the Information dialog corresponding to that new certificate. To start aria2c with --rpc-secure use --rpc-certificate=<SHA-1>. Alternatively PKCS12 files are also supported. PEM files, however, are not supported.

Returns:

rpc_listen_all property writable ¤

rpc_listen_all: bool

Return the rpc-listen-all option value.

Listen incoming JSON-RPC/XML-RPC requests on all network interfaces.

If false is given, listen only on local loopback interface. Default: false.

Returns:

rpc_listen_port property writable ¤

rpc_listen_port: int

Return the rpc-listen-port option value.

Specify a port number for JSON-RPC/XML-RPC server to listen to.

Possible Values: 1024-65535. Default: 6800.

Returns:

rpc_max_request_size property writable ¤

rpc_max_request_size: str

Return the rpc-max-request-size option value.

Set max size of JSON-RPC/XML-RPC request in bytes.

If aria2 detects the request is more than SIZE bytes, it drops connection. Default: 2M.

Returns:

rpc_passwd property writable ¤

rpc_passwd: str

Return the rpc-passwd option value.

Set JSON-RPC/XML-RPC password.

Warning

--rpc-passwd option will be deprecated in the future release. Migrate to --rpc-secret option as soon as possible.

Returns:

rpc_private_key property writable ¤

rpc_private_key: str

Return the rpc-private-key option value.

Use the private key in FILE for RPC server.

The private key must be decrypted and in PEM format. Use --rpc-secure option to enable encryption. See also --rpc-certificate option.

Returns:

rpc_save_upload_metadata property writable ¤

rpc_save_upload_metadata: bool

Return the rpc-save-upload-metadata option value.

Save the uploaded torrent or metalink meta data in the directory specified by --dir option.

The file name consists of SHA-1 hash hex string of meta data plus extension. For torrent, the extension is '.torrent'. For metalink, it is '.meta4'. If false is given to this option, the downloads added by aria2.addTorrent() or aria2.addMetalink() will not be saved by --save-session option. Default: true.

Returns:

rpc_secret property writable ¤

rpc_secret: str

Return the rpc-secret option value.

Set RPC secret authorization token.

Read RPC authorization secret token to know how this option value is used.

Returns:

rpc_secure property writable ¤

rpc_secure: bool

Return the rpc-secure option value.

RPC transport will be encrypted by SSL/TLS.

The RPC clients must use https scheme to access the server. For WebSocket client, use wss scheme. Use --rpc-certificate and --rpc-private-key options to specify the server certificate and private key.

Returns:

rpc_user property writable ¤

rpc_user: str

Return the rpc-user option value.

Set JSON-RPC/XML-RPC user.

Warning

--rpc-user option will be deprecated in the future release. Migrate to --rpc-secret option as soon as possible.

Returns:

save_cookies property writable ¤

save_cookies: str

Return the save-cookies option value.

Save Cookies to FILE in Mozilla/Firefox(1.x/2.x)/ Netscape format.

If FILE already exists, it is overwritten. Session Cookies are also saved and their expiry values are treated as 0. Possible Values: /path/to/file.

Returns:

save_not_found property writable ¤

save_not_found: bool

Return the save-not-found option value.

Save download with --save-session option even if the file was not found on the server.

This option also saves control file in that situations. Default: true.

Returns:

save_session property writable ¤

save_session: str

Return the save-session option value.

Save error/unfinished downloads to FILE on exit.

You can pass this output file to aria2c with --input-file option on restart. If you like the output to be gzipped append a .gz extension to the file name. Please note that downloads added by aria2.addTorrent() and aria2.addMetalink() RPC method and whose meta data could not be saved as a file are not saved. Downloads removed using aria2.remove() and aria2.forceRemove() will not be saved. GID is also saved with gid, but there are some restrictions, see below.

Note

Normally, GID of the download itself is saved. But some downloads use meta data (e.g., BitTorrent and Metalink). In this case, there are some restrictions.

magnet URI, and followed by torrent download: GID of BitTorrent meta data download is saved.

URI to torrent file, and followed by torrent download: GID of torrent file download is saved.

URI to metalink file, and followed by file downloads described in metalink file: GID of metalink file download is saved.

local torrent file: GID of torrent download is saved.

local metalink file: Any meaningful GID is not saved.

Returns:

save_session_interval property writable ¤

save_session_interval: int

Return the save-session-interval option value.

Save error/unfinished downloads to a file specified by --save-session option every SEC seconds.

If 0 is given, file will be saved only when aria2 exits. Default: 0.

Returns:

seed_ratio property writable ¤

seed_ratio: float

Return the seed-ratio option value.

Specify share ratio.

Seed completed torrents until share ratio reaches RATIO. You are strongly encouraged to specify equals or more than 1.0 here. Specify 0.0 if you intend to do seeding regardless of share ratio. If --seed-time option is specified along with this option, seeding ends when at least one of the conditions is satisfied. Default: 1.0.

Returns:

seed_time property writable ¤

seed_time: float

Return the seed-time option value.

Specify seeding time in (fractional) minutes.

Also see the --seed-ratio option.

Note

Specifying --seed-time=0 disables seeding after download completed.

Returns:

select_file property writable ¤

select_file: str

Return the select-file option value.

Set file to download by specifying its index.

You can find the file index using the --show-files option. Multiple indexes can be specified by using ,, for example: 3,6. You can also use - to specify a range: 1-5. , and - can be used together: 1-5,8, 9. When used with the -M option, index may vary depending on the query (see --metalink-* options).

Note

In multi file torrent, the adjacent files specified by this option may also be downloaded. This is by design, not a bug. A single piece may include several files or part of files, and aria2 writes the piece to the appropriate files.

Returns:

server_stat_if property writable ¤

server_stat_if: str

Return the server-stat-if option value.

Specify the file name to load performance profile of the servers.

The loaded data will be used in some URI selector such as feedback. See also --uri-selector option. See Server Performance Profile subsection below for file format.

Returns:

server_stat_of property writable ¤

server_stat_of: str

Return the server-stat-of option value.

Specify the file name to which performance profile of the servers is saved.

You can load saved data using --server-stat-if option. See Server Performance Profile subsection below for file format.

Returns:

server_stat_timeout property writable ¤

server_stat_timeout: int

Return the server-stat-timeout option value.

Specifies timeout in seconds to invalidate performance profile of the servers since the last contact to them.

Default: 86400 (24hours).

Returns:

show_console_readout property writable ¤

show_console_readout: bool

Return the show-console-readout option value.

Show console readout.

Default: True.

Returns:

show_files property writable ¤

show_files: bool

Return the show-files option value.

Print file listing of ".torrent", ".meta4" and ".metalink" file and exit.

In case of ".torrent" file, additional information (infohash, piece length, etc) is also printed.

Returns:

socket_recv_buffer_size property writable ¤

socket_recv_buffer_size: int

Return the socket-recv-buffer-size option value.

Set the maximum socket receive buffer in bytes.

Specifying 0 will disable this option. This value will be set to socket file descriptor using SO_RCVBUF socket option with setsockopt() call. Default: 0.

Returns:

split property writable ¤

split: int

Return the split option value.

Download a file using N connections.

If more than N URIs are given, first N URIs are used and remaining URIs are used for backup. If less than N URIs are given, those URIs are used more than once so that N connections total are made simultaneously. The number of connections to the same host is restricted by the --max-connection-per-server option. See also the --min-split-size option. Default: 5

Note

Some Metalinks regulate the number of servers to connect. aria2 strictly respects them. This means that if Metalink defines the maxconnections attribute lower than N, then aria2 uses the value of this lower value instead of N.

Returns:

ssh_host_key_md property writable ¤

ssh_host_key_md: str

Return the ssh-host-key-md option value.

Set checksum for SSH host public key (<TYPE>=<DIGEST>).

TYPE is hash type. The supported hash type is sha-1 or md5. DIGEST is hex digest. For example: sha-1=b030503d4de4539dc7885e6f0f5e256704edf4c3. This option can be used to validate server's public key when SFTP is used. If this option is not set, which is default, no validation takes place.

Returns:

stderr property writable ¤

stderr: bool

Return the stderr option value.

Redirect all console output that would be otherwise printed in stdout to stderr.

Default: False.

Returns:

stop property writable ¤

stop: int

Return the stop option value.

Stop application after SEC seconds has passed.

If 0 is given, this feature is disabled. Default: 0.

Returns:

stop_with_process property writable ¤

stop_with_process: int

Return the stop-with-process option value.

Stop application when process PID is not running.

This is useful if aria2 process is forked from a parent process. The parent process can fork aria2 with its own pid and when parent process exits for some reason, aria2 can detect it and shutdown itself.

Returns:

stream_piece_selector property writable ¤

stream_piece_selector: str

Return the stream-piece-selector option value.

Specify piece selection algorithm used in HTTP/FTP download.

Piece means fixed length segment which is downloaded in parallel in segmented download. If default is given, aria2 selects piece so that it reduces the number of establishing connection. This is reasonable default behavior because establishing connection is an expensive operation. If inorder is given, aria2 selects piece which has minimum index. Index=0 means first of the file. This will be useful to view movie while downloading it. --enable-http-pipelining option may be useful to reduce re-connection overhead. Please note that aria2 honors --min-split-size option, so it will be necessary to specify a reasonable value to --min-split-size option. If random is given, aria2 selects piece randomly. Like inorder, --min-split-size option is honored. If geom is given, at the beginning aria2 selects piece which has minimum index like inorder, but it exponentially increasingly keeps space from previously selected piece. This will reduce the number of establishing connection and at the same time it will download the beginning part of the file first. This will be useful to view movie while downloading it. Default: default.

Returns:

summary_interval property writable ¤

summary_interval: int

Return the summary-interval option value.

Set interval in seconds to output download progress summary.

Setting 0 suppresses the output. Default: 60.

Returns:

timeout property writable ¤

timeout: int

Return the timeout option value.

Set timeout in seconds.

Default: 60.

Returns:

torrent_file property writable ¤

torrent_file: str

Return the torrent-file option value.

The path to the ".torrent" file.

You are not required to use this option because you can specify ".torrent" files without --torrent-file.

Returns:

truncate_console_readout property writable ¤

truncate_console_readout: bool

Return the truncate-console-readout option value.

Truncate console readout to fit in a single line.

Default: True.

Returns:

uri_selector property writable ¤

uri_selector: str

Return the uri-selector option value.

Specify URI selection algorithm.

The possible values are inorder, feedback and adaptive. If inorder is given, URI is tried in the order appeared in the URI list. If feedback is given, aria2 uses download speed observed in the previous downloads and choose fastest server in the URI list. This also effectively skips dead mirrors. The observed download speed is a part of performance profile of servers mentioned in --server-stat-of and --server-stat-if options. If adaptive is given, selects one of the best mirrors for the first and reserved connections. For supplementary ones, it returns mirrors which has not been tested yet, and if each of them has already been tested, returns mirrors which has to be tested again. Otherwise, it doesn't select anymore mirrors. Like feedback, it uses a performance profile of servers. Default: feedback.

Returns:

use_head property writable ¤

use_head: bool

Return the use-head option value.

Use HEAD method for the first request to the HTTP server.

Default: False.

Returns:

user_agent property writable ¤

user_agent: str

Return the user-agent option value.

Set user agent for HTTP(S) downloads.

Default: aria2/$VERSION, $VERSION is replaced by package version.

Returns:

get ¤

get(
    item: str, class_: Callable | None = None
) -> OptionType

Get the value of an option given its name.

Parameters:

  • item (str) –

    The name of the option (example: "input-file").

  • class_ (Callable | None, default: None ) –

    Pass the value through this class/function to change its type.

Returns:

  • OptionType

    The option value.

Source code in src/aria2p/options.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def get(self, item: str, class_: Callable | None = None) -> OptionType:
    """Get the value of an option given its name.

    Parameters:
        item: The name of the option (example: "input-file").
        class_: Pass the value through this class/function to change its type.

    Returns:
        The option value.
    """
    value = self._struct.get(item)
    if class_ is not None and value is not None:
        return class_(value)
    return value

get_struct ¤

get_struct() -> dict

Return a copy of the struct dictionary of this Options object.

Returns:

  • dict

    A copy of the struct dictionary.

Source code in src/aria2p/options.py
54
55
56
57
58
59
60
def get_struct(self) -> dict:
    """Return a copy of the struct dictionary of this Options object.

    Returns:
        A copy of the struct dictionary.
    """
    return deepcopy(self._struct)

set ¤

set(
    key: str, value: str | float | bool | list[str]
) -> bool

Set the value of an option given its name.

Parameters:

  • key (str) –

    The name of the option (example: "input-file").

  • value (str | float | bool | list[str]) –

    The value to set.

Returns:

  • bool

    True if the value was successfully set, False otherwise.

Source code in src/aria2p/options.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def set(self, key: str, value: str | float | bool | list[str]) -> bool:
    """Set the value of an option given its name.

    Parameters:
        key: The name of the option (example: "input-file").
        value: The value to set.

    Returns:
        True if the value was successfully set, False otherwise.
    """
    if not isinstance(value, str):
        value = str(value)
    if self.download:
        success = self.api.set_options({key: value}, [self.download])[0]
    else:
        success = self.api.set_global_options({key: value})
    if success:
        self._struct[key] = value
    return success

Stats ¤

Stats(struct: dict)

This class holds information retrieved with the get_global_stat method of the client.

Parameters:

  • struct (dict) –

    A dictionary Python object returned by the JSON-RPC client.

Methods:

Attributes:

Source code in src/aria2p/stats.py
14
15
16
17
18
19
20
def __init__(self, struct: dict) -> None:
    """Initialize the object.

    Parameters:
        struct: A dictionary Python object returned by the JSON-RPC client.
    """
    self._struct = struct or {}

download_speed property ¤

download_speed: int

Overall download speed (byte/sec).

Returns:

  • int

    The overall download speed in bytes per second.

num_active property ¤

num_active: int

Return the number of active downloads.

Returns:

  • int

    The number of active downloads.

num_stopped property ¤

num_stopped: int

Return the number of stopped downloads in the current session.

This value is capped by the --max-download-result option.

Returns:

  • int

    The number of stopped downloads in the current session (capped).

num_stopped_total property ¤

num_stopped_total: int

Return the number of stopped downloads in the current session.

This value is not capped by the --max-download-result option.

Returns:

  • int

    The number of stopped downloads in the current session (not capped).

num_waiting property ¤

num_waiting: int

Return the number of waiting downloads.

Returns:

  • int

    The number of waiting downloads.

upload_speed property ¤

upload_speed: int

Overall upload speed (byte/sec).

Returns:

  • int

    The overall upload speed in bytes per second.

download_speed_string ¤

download_speed_string(human_readable: bool = True) -> str

Return the download speed as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The download speed string.

Source code in src/aria2p/stats.py
31
32
33
34
35
36
37
38
39
40
41
42
def download_speed_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the download speed as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The download speed string.
    """
    if human_readable:
        return human_readable_bytes(self.download_speed, delim=" ", postfix="/s")
    return str(self.download_speed) + " B/s"

upload_speed_string ¤

upload_speed_string(human_readable: bool = True) -> str

Return the upload speed as string.

Parameters:

  • human_readable (bool, default: True ) –

    Return in human readable format or not.

Returns:

  • str

    The upload speed string.

Source code in src/aria2p/stats.py
53
54
55
56
57
58
59
60
61
62
63
64
def upload_speed_string(self, human_readable: bool = True) -> str:  # noqa: FBT001,FBT002
    """Return the upload speed as string.

    Parameters:
        human_readable: Return in human readable format or not.

    Returns:
        The upload speed string.
    """
    if human_readable:
        return human_readable_bytes(self.upload_speed, delim=" ", postfix="/s")
    return str(self.upload_speed) + " B/s"

enable_logger ¤

enable_logger(
    sink: str | TextIO = stderr, level: str = "WARNING"
) -> None

Enable the logging of messages.

Configure the logger variable imported from loguru.

Parameters:

  • sink (file, default: stderr ) –

    An opened file pointer, or stream handler. Default to standard error.

  • level (str, default: 'WARNING' ) –

    The log level to use. Possible values are TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL. Default to WARNING.

Source code in src/aria2p/__init__.py
22
23
24
25
26
27
28
29
30
31
32
33
34
def enable_logger(sink: str | TextIO = sys.stderr, level: str = "WARNING") -> None:
    """Enable the logging of messages.

    Configure the `logger` variable imported from `loguru`.

    Parameters:
        sink (file): An opened file pointer, or stream handler. Default to standard error.
        level (str): The log level to use. Possible values are TRACE, DEBUG, INFO, WARNING, ERROR, CRITICAL.
            Default to WARNING.
    """
    logger.remove()
    logger.configure(handlers=[{"sink": sink, "level": level}])  # type: ignore[misc,list-item]
    logger.enable("aria2p")