Skip to content

client ¤

Client module.

This module defines the ClientException and Client classes, which are used to communicate with a remote aria2c process through the JSON-RPC protocol.

Classes:

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
530
531
532
533
534
535
536
537
538
539
540
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
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
472
473
474
475
476
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
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
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
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
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
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
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
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
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
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
1150
1151
1152
1153
1154
1155
1156
1157
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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
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
689
690
691
692
693
694
695
696
697
698
699
700
701
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
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
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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
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
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
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
1203
1204
1205
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
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
 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
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
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
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
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
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
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
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
886
887
888
889
890
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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
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
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
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
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
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
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
1671
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
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
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
1524
1525
1526
1527
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
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
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
655
656
657
658
659
660
661
662
663
664
665
666
667
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
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
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
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
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
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
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
1723
1724
1725
1726
1727
1728
1729
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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
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
735
736
737
738
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
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
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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
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
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
721
722
723
724
725
726
727
728
729
730
731
732
733
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

Notification ¤

Notification(event_type: str, gid: str)

A helper class for notifications.

You should not need to use this class. It simply provides methods to instantiate a notification with a message received from the server through a WebSocket, or to raise a ClientException if the message is invalid.

Parameters:

  • event_type (str) –

    The notification type. Possible types are available in the NOTIFICATION_TYPES variable.

  • gid (str) –

    The GID of the download related to the notification.

Methods:

  • from_message

    Return an instance of Notification.

  • get_or_raise

    Raise a ClientException when the message is invalid or return a Notification instance.

Source code in src/aria2p/client.py
1739
1740
1741
1742
1743
1744
1745
1746
1747
def __init__(self, event_type: str, gid: str) -> None:
    """Initialize the object.

    Parameters:
        event_type: The notification type. Possible types are available in the NOTIFICATION_TYPES variable.
        gid: The GID of the download related to the notification.
    """
    self.type = event_type
    self.gid = gid

from_message staticmethod ¤

from_message(message: dict) -> Notification

Return an instance of Notification.

This method expects a valid message (not containing errors).

Parameters:

  • message (dict) –

    A valid message received over WebSocket.

Returns:

Source code in src/aria2p/client.py
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
@staticmethod
def from_message(message: dict) -> Notification:
    """Return an instance of Notification.

    This method expects a valid message (not containing errors).

    Parameters:
        message: A valid message received over WebSocket.

    Returns:
        A Notification instance.
    """
    return Notification(event_type=message["method"], gid=message["params"][0]["gid"])

get_or_raise staticmethod ¤

get_or_raise(message: dict) -> Notification

Raise a ClientException when the message is invalid or return a Notification instance.

Parameters:

  • message (dict) –

    The JSON-loaded message received over WebSocket.

Returns:

  • Notification

    A Notification instance if the message is valid.

Raises:

Source code in src/aria2p/client.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
@staticmethod
def get_or_raise(message: dict) -> Notification:
    """Raise a ClientException when the message is invalid or return a Notification instance.

    Parameters:
        message: The JSON-loaded message received over WebSocket.

    Returns:
        A Notification instance if the message is valid.

    Raises:
        ClientException: When the message contains an error.
    """
    if "error" in message:
        raise Client.response_as_exception(message)
    return Notification.from_message(message)