Skip to content

api ¤

Aria2 API.

This module defines the API class, which makes use of a JSON-RPC client to provide higher-level methods to interact easily with a remote aria2c process.

Classes:

  • API

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

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
38
39
40
41
42
43
44
45
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
50
51
52
53
54
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
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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
120
121
122
123
124
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
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")

    gid = self.client.add_torrent(encoded_contents, uris, client_options, position)

    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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
558
559
560
561
562
563
564
565
566
567
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
703
704
705
706
707
708
709
710
711
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
@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
255
256
257
258
259
260
261
262
263
264
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
584
585
586
587
588
589
590
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
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
625
626
627
628
629
630
631
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
739
740
741
742
743
744
745
746
747
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
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
289
290
291
292
293
294
295
296
297
298
299
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
330
331
332
333
334
335
336
337
338
339
340
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
@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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
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
353
354
355
356
357
358
359
360
361
362
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
342
343
344
345
346
347
348
349
350
351
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
318
319
320
321
322
323
324
325
326
327
328
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
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
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
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
506
507
508
509
510
511
512
513
514
515
516
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
550
551
552
553
554
555
556
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
400
401
402
403
404
405
406
407
408
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
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
468
469
470
471
472
473
474
475
476
477
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
633
634
635
636
637
638
639
640
641
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
@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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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
542
543
544
545
546
547
548
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
364
365
366
367
368
369
370
371
372
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
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
212
213
214
215
216
217
218
219
220
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
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
611
612
613
614
615
616
617
618
619
620
621
622
623
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
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
793
794
795
796
797
798
799
800
801
802
803
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